compiler.umd.js 1.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507
  1. /**
  2. * @license Angular v8.1.0
  3. * (c) 2010-2019 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  8. typeof define === 'function' && define.amd ? define('@angular/compiler', ['exports'], factory) :
  9. (global = global || self, factory((global.ng = global.ng || {}, global.ng.compiler = {})));
  10. }(this, function (exports) { 'use strict';
  11. /*! *****************************************************************************
  12. Copyright (c) Microsoft Corporation. All rights reserved.
  13. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  14. this file except in compliance with the License. You may obtain a copy of the
  15. License at http://www.apache.org/licenses/LICENSE-2.0
  16. THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17. KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  18. WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  19. MERCHANTABLITY OR NON-INFRINGEMENT.
  20. See the Apache Version 2.0 License for specific language governing permissions
  21. and limitations under the License.
  22. ***************************************************************************** */
  23. /* global Reflect, Promise */
  24. var extendStatics = function(d, b) {
  25. extendStatics = Object.setPrototypeOf ||
  26. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  27. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  28. return extendStatics(d, b);
  29. };
  30. function __extends(d, b) {
  31. extendStatics(d, b);
  32. function __() { this.constructor = d; }
  33. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  34. }
  35. var __assign = function() {
  36. __assign = Object.assign || function __assign(t) {
  37. for (var s, i = 1, n = arguments.length; i < n; i++) {
  38. s = arguments[i];
  39. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
  40. }
  41. return t;
  42. };
  43. return __assign.apply(this, arguments);
  44. };
  45. function __values(o) {
  46. var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
  47. if (m) return m.call(o);
  48. return {
  49. next: function () {
  50. if (o && i >= o.length) o = void 0;
  51. return { value: o && o[i++], done: !o };
  52. }
  53. };
  54. }
  55. function __read(o, n) {
  56. var m = typeof Symbol === "function" && o[Symbol.iterator];
  57. if (!m) return o;
  58. var i = m.call(o), r, ar = [], e;
  59. try {
  60. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  61. }
  62. catch (error) { e = { error: error }; }
  63. finally {
  64. try {
  65. if (r && !r.done && (m = i["return"])) m.call(i);
  66. }
  67. finally { if (e) throw e.error; }
  68. }
  69. return ar;
  70. }
  71. function __spread() {
  72. for (var ar = [], i = 0; i < arguments.length; i++)
  73. ar = ar.concat(__read(arguments[i]));
  74. return ar;
  75. }
  76. /**
  77. * @license
  78. * Copyright Google Inc. All Rights Reserved.
  79. *
  80. * Use of this source code is governed by an MIT-style license that can be
  81. * found in the LICENSE file at https://angular.io/license
  82. */
  83. (function (TagContentType) {
  84. TagContentType[TagContentType["RAW_TEXT"] = 0] = "RAW_TEXT";
  85. TagContentType[TagContentType["ESCAPABLE_RAW_TEXT"] = 1] = "ESCAPABLE_RAW_TEXT";
  86. TagContentType[TagContentType["PARSABLE_DATA"] = 2] = "PARSABLE_DATA";
  87. })(exports.TagContentType || (exports.TagContentType = {}));
  88. function splitNsName(elementName) {
  89. if (elementName[0] != ':') {
  90. return [null, elementName];
  91. }
  92. var colonIndex = elementName.indexOf(':', 1);
  93. if (colonIndex == -1) {
  94. throw new Error("Unsupported format \"" + elementName + "\" expecting \":namespace:name\"");
  95. }
  96. return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)];
  97. }
  98. // `<ng-container>` tags work the same regardless the namespace
  99. function isNgContainer(tagName) {
  100. return splitNsName(tagName)[1] === 'ng-container';
  101. }
  102. // `<ng-content>` tags work the same regardless the namespace
  103. function isNgContent(tagName) {
  104. return splitNsName(tagName)[1] === 'ng-content';
  105. }
  106. // `<ng-template>` tags work the same regardless the namespace
  107. function isNgTemplate(tagName) {
  108. return splitNsName(tagName)[1] === 'ng-template';
  109. }
  110. function getNsPrefix(fullName) {
  111. return fullName === null ? null : splitNsName(fullName)[0];
  112. }
  113. function mergeNsAndName(prefix, localName) {
  114. return prefix ? ":" + prefix + ":" + localName : localName;
  115. }
  116. // see http://www.w3.org/TR/html51/syntax.html#named-character-references
  117. // see https://html.spec.whatwg.org/multipage/entities.json
  118. // This list is not exhaustive to keep the compiler footprint low.
  119. // The `&#123;` / `&#x1ab;` syntax should be used when the named character reference does not
  120. // exist.
  121. var NAMED_ENTITIES = {
  122. 'Aacute': '\u00C1',
  123. 'aacute': '\u00E1',
  124. 'Acirc': '\u00C2',
  125. 'acirc': '\u00E2',
  126. 'acute': '\u00B4',
  127. 'AElig': '\u00C6',
  128. 'aelig': '\u00E6',
  129. 'Agrave': '\u00C0',
  130. 'agrave': '\u00E0',
  131. 'alefsym': '\u2135',
  132. 'Alpha': '\u0391',
  133. 'alpha': '\u03B1',
  134. 'amp': '&',
  135. 'and': '\u2227',
  136. 'ang': '\u2220',
  137. 'apos': '\u0027',
  138. 'Aring': '\u00C5',
  139. 'aring': '\u00E5',
  140. 'asymp': '\u2248',
  141. 'Atilde': '\u00C3',
  142. 'atilde': '\u00E3',
  143. 'Auml': '\u00C4',
  144. 'auml': '\u00E4',
  145. 'bdquo': '\u201E',
  146. 'Beta': '\u0392',
  147. 'beta': '\u03B2',
  148. 'brvbar': '\u00A6',
  149. 'bull': '\u2022',
  150. 'cap': '\u2229',
  151. 'Ccedil': '\u00C7',
  152. 'ccedil': '\u00E7',
  153. 'cedil': '\u00B8',
  154. 'cent': '\u00A2',
  155. 'Chi': '\u03A7',
  156. 'chi': '\u03C7',
  157. 'circ': '\u02C6',
  158. 'clubs': '\u2663',
  159. 'cong': '\u2245',
  160. 'copy': '\u00A9',
  161. 'crarr': '\u21B5',
  162. 'cup': '\u222A',
  163. 'curren': '\u00A4',
  164. 'dagger': '\u2020',
  165. 'Dagger': '\u2021',
  166. 'darr': '\u2193',
  167. 'dArr': '\u21D3',
  168. 'deg': '\u00B0',
  169. 'Delta': '\u0394',
  170. 'delta': '\u03B4',
  171. 'diams': '\u2666',
  172. 'divide': '\u00F7',
  173. 'Eacute': '\u00C9',
  174. 'eacute': '\u00E9',
  175. 'Ecirc': '\u00CA',
  176. 'ecirc': '\u00EA',
  177. 'Egrave': '\u00C8',
  178. 'egrave': '\u00E8',
  179. 'empty': '\u2205',
  180. 'emsp': '\u2003',
  181. 'ensp': '\u2002',
  182. 'Epsilon': '\u0395',
  183. 'epsilon': '\u03B5',
  184. 'equiv': '\u2261',
  185. 'Eta': '\u0397',
  186. 'eta': '\u03B7',
  187. 'ETH': '\u00D0',
  188. 'eth': '\u00F0',
  189. 'Euml': '\u00CB',
  190. 'euml': '\u00EB',
  191. 'euro': '\u20AC',
  192. 'exist': '\u2203',
  193. 'fnof': '\u0192',
  194. 'forall': '\u2200',
  195. 'frac12': '\u00BD',
  196. 'frac14': '\u00BC',
  197. 'frac34': '\u00BE',
  198. 'frasl': '\u2044',
  199. 'Gamma': '\u0393',
  200. 'gamma': '\u03B3',
  201. 'ge': '\u2265',
  202. 'gt': '>',
  203. 'harr': '\u2194',
  204. 'hArr': '\u21D4',
  205. 'hearts': '\u2665',
  206. 'hellip': '\u2026',
  207. 'Iacute': '\u00CD',
  208. 'iacute': '\u00ED',
  209. 'Icirc': '\u00CE',
  210. 'icirc': '\u00EE',
  211. 'iexcl': '\u00A1',
  212. 'Igrave': '\u00CC',
  213. 'igrave': '\u00EC',
  214. 'image': '\u2111',
  215. 'infin': '\u221E',
  216. 'int': '\u222B',
  217. 'Iota': '\u0399',
  218. 'iota': '\u03B9',
  219. 'iquest': '\u00BF',
  220. 'isin': '\u2208',
  221. 'Iuml': '\u00CF',
  222. 'iuml': '\u00EF',
  223. 'Kappa': '\u039A',
  224. 'kappa': '\u03BA',
  225. 'Lambda': '\u039B',
  226. 'lambda': '\u03BB',
  227. 'lang': '\u27E8',
  228. 'laquo': '\u00AB',
  229. 'larr': '\u2190',
  230. 'lArr': '\u21D0',
  231. 'lceil': '\u2308',
  232. 'ldquo': '\u201C',
  233. 'le': '\u2264',
  234. 'lfloor': '\u230A',
  235. 'lowast': '\u2217',
  236. 'loz': '\u25CA',
  237. 'lrm': '\u200E',
  238. 'lsaquo': '\u2039',
  239. 'lsquo': '\u2018',
  240. 'lt': '<',
  241. 'macr': '\u00AF',
  242. 'mdash': '\u2014',
  243. 'micro': '\u00B5',
  244. 'middot': '\u00B7',
  245. 'minus': '\u2212',
  246. 'Mu': '\u039C',
  247. 'mu': '\u03BC',
  248. 'nabla': '\u2207',
  249. 'nbsp': '\u00A0',
  250. 'ndash': '\u2013',
  251. 'ne': '\u2260',
  252. 'ni': '\u220B',
  253. 'not': '\u00AC',
  254. 'notin': '\u2209',
  255. 'nsub': '\u2284',
  256. 'Ntilde': '\u00D1',
  257. 'ntilde': '\u00F1',
  258. 'Nu': '\u039D',
  259. 'nu': '\u03BD',
  260. 'Oacute': '\u00D3',
  261. 'oacute': '\u00F3',
  262. 'Ocirc': '\u00D4',
  263. 'ocirc': '\u00F4',
  264. 'OElig': '\u0152',
  265. 'oelig': '\u0153',
  266. 'Ograve': '\u00D2',
  267. 'ograve': '\u00F2',
  268. 'oline': '\u203E',
  269. 'Omega': '\u03A9',
  270. 'omega': '\u03C9',
  271. 'Omicron': '\u039F',
  272. 'omicron': '\u03BF',
  273. 'oplus': '\u2295',
  274. 'or': '\u2228',
  275. 'ordf': '\u00AA',
  276. 'ordm': '\u00BA',
  277. 'Oslash': '\u00D8',
  278. 'oslash': '\u00F8',
  279. 'Otilde': '\u00D5',
  280. 'otilde': '\u00F5',
  281. 'otimes': '\u2297',
  282. 'Ouml': '\u00D6',
  283. 'ouml': '\u00F6',
  284. 'para': '\u00B6',
  285. 'permil': '\u2030',
  286. 'perp': '\u22A5',
  287. 'Phi': '\u03A6',
  288. 'phi': '\u03C6',
  289. 'Pi': '\u03A0',
  290. 'pi': '\u03C0',
  291. 'piv': '\u03D6',
  292. 'plusmn': '\u00B1',
  293. 'pound': '\u00A3',
  294. 'prime': '\u2032',
  295. 'Prime': '\u2033',
  296. 'prod': '\u220F',
  297. 'prop': '\u221D',
  298. 'Psi': '\u03A8',
  299. 'psi': '\u03C8',
  300. 'quot': '\u0022',
  301. 'radic': '\u221A',
  302. 'rang': '\u27E9',
  303. 'raquo': '\u00BB',
  304. 'rarr': '\u2192',
  305. 'rArr': '\u21D2',
  306. 'rceil': '\u2309',
  307. 'rdquo': '\u201D',
  308. 'real': '\u211C',
  309. 'reg': '\u00AE',
  310. 'rfloor': '\u230B',
  311. 'Rho': '\u03A1',
  312. 'rho': '\u03C1',
  313. 'rlm': '\u200F',
  314. 'rsaquo': '\u203A',
  315. 'rsquo': '\u2019',
  316. 'sbquo': '\u201A',
  317. 'Scaron': '\u0160',
  318. 'scaron': '\u0161',
  319. 'sdot': '\u22C5',
  320. 'sect': '\u00A7',
  321. 'shy': '\u00AD',
  322. 'Sigma': '\u03A3',
  323. 'sigma': '\u03C3',
  324. 'sigmaf': '\u03C2',
  325. 'sim': '\u223C',
  326. 'spades': '\u2660',
  327. 'sub': '\u2282',
  328. 'sube': '\u2286',
  329. 'sum': '\u2211',
  330. 'sup': '\u2283',
  331. 'sup1': '\u00B9',
  332. 'sup2': '\u00B2',
  333. 'sup3': '\u00B3',
  334. 'supe': '\u2287',
  335. 'szlig': '\u00DF',
  336. 'Tau': '\u03A4',
  337. 'tau': '\u03C4',
  338. 'there4': '\u2234',
  339. 'Theta': '\u0398',
  340. 'theta': '\u03B8',
  341. 'thetasym': '\u03D1',
  342. 'thinsp': '\u2009',
  343. 'THORN': '\u00DE',
  344. 'thorn': '\u00FE',
  345. 'tilde': '\u02DC',
  346. 'times': '\u00D7',
  347. 'trade': '\u2122',
  348. 'Uacute': '\u00DA',
  349. 'uacute': '\u00FA',
  350. 'uarr': '\u2191',
  351. 'uArr': '\u21D1',
  352. 'Ucirc': '\u00DB',
  353. 'ucirc': '\u00FB',
  354. 'Ugrave': '\u00D9',
  355. 'ugrave': '\u00F9',
  356. 'uml': '\u00A8',
  357. 'upsih': '\u03D2',
  358. 'Upsilon': '\u03A5',
  359. 'upsilon': '\u03C5',
  360. 'Uuml': '\u00DC',
  361. 'uuml': '\u00FC',
  362. 'weierp': '\u2118',
  363. 'Xi': '\u039E',
  364. 'xi': '\u03BE',
  365. 'Yacute': '\u00DD',
  366. 'yacute': '\u00FD',
  367. 'yen': '\u00A5',
  368. 'yuml': '\u00FF',
  369. 'Yuml': '\u0178',
  370. 'Zeta': '\u0396',
  371. 'zeta': '\u03B6',
  372. 'zwj': '\u200D',
  373. 'zwnj': '\u200C',
  374. };
  375. // The &ngsp; pseudo-entity is denoting a space. see:
  376. // https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart
  377. var NGSP_UNICODE = '\uE500';
  378. NAMED_ENTITIES['ngsp'] = NGSP_UNICODE;
  379. /**
  380. * @license
  381. * Copyright Google Inc. All Rights Reserved.
  382. *
  383. * Use of this source code is governed by an MIT-style license that can be
  384. * found in the LICENSE file at https://angular.io/license
  385. */
  386. var HtmlTagDefinition = /** @class */ (function () {
  387. function HtmlTagDefinition(_a) {
  388. var _this = this;
  389. var _b = _a === void 0 ? {} : _a, closedByChildren = _b.closedByChildren, implicitNamespacePrefix = _b.implicitNamespacePrefix, _c = _b.contentType, contentType = _c === void 0 ? exports.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;
  390. this.closedByChildren = {};
  391. this.closedByParent = false;
  392. this.canSelfClose = false;
  393. if (closedByChildren && closedByChildren.length > 0) {
  394. closedByChildren.forEach(function (tagName) { return _this.closedByChildren[tagName] = true; });
  395. }
  396. this.isVoid = isVoid;
  397. this.closedByParent = closedByParent || isVoid;
  398. this.implicitNamespacePrefix = implicitNamespacePrefix || null;
  399. this.contentType = contentType;
  400. this.ignoreFirstLf = ignoreFirstLf;
  401. }
  402. HtmlTagDefinition.prototype.isClosedByChild = function (name) {
  403. return this.isVoid || name.toLowerCase() in this.closedByChildren;
  404. };
  405. return HtmlTagDefinition;
  406. }());
  407. var _DEFAULT_TAG_DEFINITION;
  408. // see http://www.w3.org/TR/html51/syntax.html#optional-tags
  409. // This implementation does not fully conform to the HTML5 spec.
  410. var TAG_DEFINITIONS;
  411. function getHtmlTagDefinition(tagName) {
  412. if (!TAG_DEFINITIONS) {
  413. _DEFAULT_TAG_DEFINITION = new HtmlTagDefinition();
  414. TAG_DEFINITIONS = {
  415. 'base': new HtmlTagDefinition({ isVoid: true }),
  416. 'meta': new HtmlTagDefinition({ isVoid: true }),
  417. 'area': new HtmlTagDefinition({ isVoid: true }),
  418. 'embed': new HtmlTagDefinition({ isVoid: true }),
  419. 'link': new HtmlTagDefinition({ isVoid: true }),
  420. 'img': new HtmlTagDefinition({ isVoid: true }),
  421. 'input': new HtmlTagDefinition({ isVoid: true }),
  422. 'param': new HtmlTagDefinition({ isVoid: true }),
  423. 'hr': new HtmlTagDefinition({ isVoid: true }),
  424. 'br': new HtmlTagDefinition({ isVoid: true }),
  425. 'source': new HtmlTagDefinition({ isVoid: true }),
  426. 'track': new HtmlTagDefinition({ isVoid: true }),
  427. 'wbr': new HtmlTagDefinition({ isVoid: true }),
  428. 'p': new HtmlTagDefinition({
  429. closedByChildren: [
  430. 'address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset',
  431. 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5',
  432. 'h6', 'header', 'hgroup', 'hr', 'main', 'nav', 'ol',
  433. 'p', 'pre', 'section', 'table', 'ul'
  434. ],
  435. closedByParent: true
  436. }),
  437. 'thead': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'] }),
  438. 'tbody': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'], closedByParent: true }),
  439. 'tfoot': new HtmlTagDefinition({ closedByChildren: ['tbody'], closedByParent: true }),
  440. 'tr': new HtmlTagDefinition({ closedByChildren: ['tr'], closedByParent: true }),
  441. 'td': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
  442. 'th': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
  443. 'col': new HtmlTagDefinition({ isVoid: true }),
  444. 'svg': new HtmlTagDefinition({ implicitNamespacePrefix: 'svg' }),
  445. 'math': new HtmlTagDefinition({ implicitNamespacePrefix: 'math' }),
  446. 'li': new HtmlTagDefinition({ closedByChildren: ['li'], closedByParent: true }),
  447. 'dt': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'] }),
  448. 'dd': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'], closedByParent: true }),
  449. 'rb': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
  450. 'rt': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
  451. 'rtc': new HtmlTagDefinition({ closedByChildren: ['rb', 'rtc', 'rp'], closedByParent: true }),
  452. 'rp': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
  453. 'optgroup': new HtmlTagDefinition({ closedByChildren: ['optgroup'], closedByParent: true }),
  454. 'option': new HtmlTagDefinition({ closedByChildren: ['option', 'optgroup'], closedByParent: true }),
  455. 'pre': new HtmlTagDefinition({ ignoreFirstLf: true }),
  456. 'listing': new HtmlTagDefinition({ ignoreFirstLf: true }),
  457. 'style': new HtmlTagDefinition({ contentType: exports.TagContentType.RAW_TEXT }),
  458. 'script': new HtmlTagDefinition({ contentType: exports.TagContentType.RAW_TEXT }),
  459. 'title': new HtmlTagDefinition({ contentType: exports.TagContentType.ESCAPABLE_RAW_TEXT }),
  460. 'textarea': new HtmlTagDefinition({ contentType: exports.TagContentType.ESCAPABLE_RAW_TEXT, ignoreFirstLf: true }),
  461. };
  462. }
  463. return TAG_DEFINITIONS[tagName.toLowerCase()] || _DEFAULT_TAG_DEFINITION;
  464. }
  465. /**
  466. * @license
  467. * Copyright Google Inc. All Rights Reserved.
  468. *
  469. * Use of this source code is governed by an MIT-style license that can be
  470. * found in the LICENSE file at https://angular.io/license
  471. */
  472. var _SELECTOR_REGEXP = new RegExp('(\\:not\\()|' + //":not("
  473. '([-\\w]+)|' + // "tag"
  474. '(?:\\.([-\\w]+))|' + // ".class"
  475. // "-" should appear first in the regexp below as FF31 parses "[.-\w]" as a range
  476. '(?:\\[([-.\\w*]+)(?:=([\"\']?)([^\\]\"\']*)\\5)?\\])|' + // "[name]", "[name=value]",
  477. // "[name="value"]",
  478. // "[name='value']"
  479. '(\\))|' + // ")"
  480. '(\\s*,\\s*)', // ","
  481. 'g');
  482. /**
  483. * A css selector contains an element name,
  484. * css classes and attribute/value pairs with the purpose
  485. * of selecting subsets out of them.
  486. */
  487. var CssSelector = /** @class */ (function () {
  488. function CssSelector() {
  489. this.element = null;
  490. this.classNames = [];
  491. /**
  492. * The selectors are encoded in pairs where:
  493. * - even locations are attribute names
  494. * - odd locations are attribute values.
  495. *
  496. * Example:
  497. * Selector: `[key1=value1][key2]` would parse to:
  498. * ```
  499. * ['key1', 'value1', 'key2', '']
  500. * ```
  501. */
  502. this.attrs = [];
  503. this.notSelectors = [];
  504. }
  505. CssSelector.parse = function (selector) {
  506. var results = [];
  507. var _addResult = function (res, cssSel) {
  508. if (cssSel.notSelectors.length > 0 && !cssSel.element && cssSel.classNames.length == 0 &&
  509. cssSel.attrs.length == 0) {
  510. cssSel.element = '*';
  511. }
  512. res.push(cssSel);
  513. };
  514. var cssSelector = new CssSelector();
  515. var match;
  516. var current = cssSelector;
  517. var inNot = false;
  518. _SELECTOR_REGEXP.lastIndex = 0;
  519. while (match = _SELECTOR_REGEXP.exec(selector)) {
  520. if (match[1]) {
  521. if (inNot) {
  522. throw new Error('Nesting :not is not allowed in a selector');
  523. }
  524. inNot = true;
  525. current = new CssSelector();
  526. cssSelector.notSelectors.push(current);
  527. }
  528. if (match[2]) {
  529. current.setElement(match[2]);
  530. }
  531. if (match[3]) {
  532. current.addClassName(match[3]);
  533. }
  534. if (match[4]) {
  535. current.addAttribute(match[4], match[6]);
  536. }
  537. if (match[7]) {
  538. inNot = false;
  539. current = cssSelector;
  540. }
  541. if (match[8]) {
  542. if (inNot) {
  543. throw new Error('Multiple selectors in :not are not supported');
  544. }
  545. _addResult(results, cssSelector);
  546. cssSelector = current = new CssSelector();
  547. }
  548. }
  549. _addResult(results, cssSelector);
  550. return results;
  551. };
  552. CssSelector.prototype.isElementSelector = function () {
  553. return this.hasElementSelector() && this.classNames.length == 0 && this.attrs.length == 0 &&
  554. this.notSelectors.length === 0;
  555. };
  556. CssSelector.prototype.hasElementSelector = function () { return !!this.element; };
  557. CssSelector.prototype.setElement = function (element) {
  558. if (element === void 0) { element = null; }
  559. this.element = element;
  560. };
  561. /** Gets a template string for an element that matches the selector. */
  562. CssSelector.prototype.getMatchingElementTemplate = function () {
  563. var tagName = this.element || 'div';
  564. var classAttr = this.classNames.length > 0 ? " class=\"" + this.classNames.join(' ') + "\"" : '';
  565. var attrs = '';
  566. for (var i = 0; i < this.attrs.length; i += 2) {
  567. var attrName = this.attrs[i];
  568. var attrValue = this.attrs[i + 1] !== '' ? "=\"" + this.attrs[i + 1] + "\"" : '';
  569. attrs += " " + attrName + attrValue;
  570. }
  571. return getHtmlTagDefinition(tagName).isVoid ? "<" + tagName + classAttr + attrs + "/>" :
  572. "<" + tagName + classAttr + attrs + "></" + tagName + ">";
  573. };
  574. CssSelector.prototype.getAttrs = function () {
  575. var result = [];
  576. if (this.classNames.length > 0) {
  577. result.push('class', this.classNames.join(' '));
  578. }
  579. return result.concat(this.attrs);
  580. };
  581. CssSelector.prototype.addAttribute = function (name, value) {
  582. if (value === void 0) { value = ''; }
  583. this.attrs.push(name, value && value.toLowerCase() || '');
  584. };
  585. CssSelector.prototype.addClassName = function (name) { this.classNames.push(name.toLowerCase()); };
  586. CssSelector.prototype.toString = function () {
  587. var res = this.element || '';
  588. if (this.classNames) {
  589. this.classNames.forEach(function (klass) { return res += "." + klass; });
  590. }
  591. if (this.attrs) {
  592. for (var i = 0; i < this.attrs.length; i += 2) {
  593. var name_1 = this.attrs[i];
  594. var value = this.attrs[i + 1];
  595. res += "[" + name_1 + (value ? '=' + value : '') + "]";
  596. }
  597. }
  598. this.notSelectors.forEach(function (notSelector) { return res += ":not(" + notSelector + ")"; });
  599. return res;
  600. };
  601. return CssSelector;
  602. }());
  603. /**
  604. * Reads a list of CssSelectors and allows to calculate which ones
  605. * are contained in a given CssSelector.
  606. */
  607. var SelectorMatcher = /** @class */ (function () {
  608. function SelectorMatcher() {
  609. this._elementMap = new Map();
  610. this._elementPartialMap = new Map();
  611. this._classMap = new Map();
  612. this._classPartialMap = new Map();
  613. this._attrValueMap = new Map();
  614. this._attrValuePartialMap = new Map();
  615. this._listContexts = [];
  616. }
  617. SelectorMatcher.createNotMatcher = function (notSelectors) {
  618. var notMatcher = new SelectorMatcher();
  619. notMatcher.addSelectables(notSelectors, null);
  620. return notMatcher;
  621. };
  622. SelectorMatcher.prototype.addSelectables = function (cssSelectors, callbackCtxt) {
  623. var listContext = null;
  624. if (cssSelectors.length > 1) {
  625. listContext = new SelectorListContext(cssSelectors);
  626. this._listContexts.push(listContext);
  627. }
  628. for (var i = 0; i < cssSelectors.length; i++) {
  629. this._addSelectable(cssSelectors[i], callbackCtxt, listContext);
  630. }
  631. };
  632. /**
  633. * Add an object that can be found later on by calling `match`.
  634. * @param cssSelector A css selector
  635. * @param callbackCtxt An opaque object that will be given to the callback of the `match` function
  636. */
  637. SelectorMatcher.prototype._addSelectable = function (cssSelector, callbackCtxt, listContext) {
  638. var matcher = this;
  639. var element = cssSelector.element;
  640. var classNames = cssSelector.classNames;
  641. var attrs = cssSelector.attrs;
  642. var selectable = new SelectorContext(cssSelector, callbackCtxt, listContext);
  643. if (element) {
  644. var isTerminal = attrs.length === 0 && classNames.length === 0;
  645. if (isTerminal) {
  646. this._addTerminal(matcher._elementMap, element, selectable);
  647. }
  648. else {
  649. matcher = this._addPartial(matcher._elementPartialMap, element);
  650. }
  651. }
  652. if (classNames) {
  653. for (var i = 0; i < classNames.length; i++) {
  654. var isTerminal = attrs.length === 0 && i === classNames.length - 1;
  655. var className = classNames[i];
  656. if (isTerminal) {
  657. this._addTerminal(matcher._classMap, className, selectable);
  658. }
  659. else {
  660. matcher = this._addPartial(matcher._classPartialMap, className);
  661. }
  662. }
  663. }
  664. if (attrs) {
  665. for (var i = 0; i < attrs.length; i += 2) {
  666. var isTerminal = i === attrs.length - 2;
  667. var name_2 = attrs[i];
  668. var value = attrs[i + 1];
  669. if (isTerminal) {
  670. var terminalMap = matcher._attrValueMap;
  671. var terminalValuesMap = terminalMap.get(name_2);
  672. if (!terminalValuesMap) {
  673. terminalValuesMap = new Map();
  674. terminalMap.set(name_2, terminalValuesMap);
  675. }
  676. this._addTerminal(terminalValuesMap, value, selectable);
  677. }
  678. else {
  679. var partialMap = matcher._attrValuePartialMap;
  680. var partialValuesMap = partialMap.get(name_2);
  681. if (!partialValuesMap) {
  682. partialValuesMap = new Map();
  683. partialMap.set(name_2, partialValuesMap);
  684. }
  685. matcher = this._addPartial(partialValuesMap, value);
  686. }
  687. }
  688. }
  689. };
  690. SelectorMatcher.prototype._addTerminal = function (map, name, selectable) {
  691. var terminalList = map.get(name);
  692. if (!terminalList) {
  693. terminalList = [];
  694. map.set(name, terminalList);
  695. }
  696. terminalList.push(selectable);
  697. };
  698. SelectorMatcher.prototype._addPartial = function (map, name) {
  699. var matcher = map.get(name);
  700. if (!matcher) {
  701. matcher = new SelectorMatcher();
  702. map.set(name, matcher);
  703. }
  704. return matcher;
  705. };
  706. /**
  707. * Find the objects that have been added via `addSelectable`
  708. * whose css selector is contained in the given css selector.
  709. * @param cssSelector A css selector
  710. * @param matchedCallback This callback will be called with the object handed into `addSelectable`
  711. * @return boolean true if a match was found
  712. */
  713. SelectorMatcher.prototype.match = function (cssSelector, matchedCallback) {
  714. var result = false;
  715. var element = cssSelector.element;
  716. var classNames = cssSelector.classNames;
  717. var attrs = cssSelector.attrs;
  718. for (var i = 0; i < this._listContexts.length; i++) {
  719. this._listContexts[i].alreadyMatched = false;
  720. }
  721. result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result;
  722. result = this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) ||
  723. result;
  724. if (classNames) {
  725. for (var i = 0; i < classNames.length; i++) {
  726. var className = classNames[i];
  727. result =
  728. this._matchTerminal(this._classMap, className, cssSelector, matchedCallback) || result;
  729. result =
  730. this._matchPartial(this._classPartialMap, className, cssSelector, matchedCallback) ||
  731. result;
  732. }
  733. }
  734. if (attrs) {
  735. for (var i = 0; i < attrs.length; i += 2) {
  736. var name_3 = attrs[i];
  737. var value = attrs[i + 1];
  738. var terminalValuesMap = this._attrValueMap.get(name_3);
  739. if (value) {
  740. result =
  741. this._matchTerminal(terminalValuesMap, '', cssSelector, matchedCallback) || result;
  742. }
  743. result =
  744. this._matchTerminal(terminalValuesMap, value, cssSelector, matchedCallback) || result;
  745. var partialValuesMap = this._attrValuePartialMap.get(name_3);
  746. if (value) {
  747. result = this._matchPartial(partialValuesMap, '', cssSelector, matchedCallback) || result;
  748. }
  749. result =
  750. this._matchPartial(partialValuesMap, value, cssSelector, matchedCallback) || result;
  751. }
  752. }
  753. return result;
  754. };
  755. /** @internal */
  756. SelectorMatcher.prototype._matchTerminal = function (map, name, cssSelector, matchedCallback) {
  757. if (!map || typeof name !== 'string') {
  758. return false;
  759. }
  760. var selectables = map.get(name) || [];
  761. var starSelectables = map.get('*');
  762. if (starSelectables) {
  763. selectables = selectables.concat(starSelectables);
  764. }
  765. if (selectables.length === 0) {
  766. return false;
  767. }
  768. var selectable;
  769. var result = false;
  770. for (var i = 0; i < selectables.length; i++) {
  771. selectable = selectables[i];
  772. result = selectable.finalize(cssSelector, matchedCallback) || result;
  773. }
  774. return result;
  775. };
  776. /** @internal */
  777. SelectorMatcher.prototype._matchPartial = function (map, name, cssSelector, matchedCallback) {
  778. if (!map || typeof name !== 'string') {
  779. return false;
  780. }
  781. var nestedSelector = map.get(name);
  782. if (!nestedSelector) {
  783. return false;
  784. }
  785. // TODO(perf): get rid of recursion and measure again
  786. // TODO(perf): don't pass the whole selector into the recursion,
  787. // but only the not processed parts
  788. return nestedSelector.match(cssSelector, matchedCallback);
  789. };
  790. return SelectorMatcher;
  791. }());
  792. var SelectorListContext = /** @class */ (function () {
  793. function SelectorListContext(selectors) {
  794. this.selectors = selectors;
  795. this.alreadyMatched = false;
  796. }
  797. return SelectorListContext;
  798. }());
  799. // Store context to pass back selector and context when a selector is matched
  800. var SelectorContext = /** @class */ (function () {
  801. function SelectorContext(selector, cbContext, listContext) {
  802. this.selector = selector;
  803. this.cbContext = cbContext;
  804. this.listContext = listContext;
  805. this.notSelectors = selector.notSelectors;
  806. }
  807. SelectorContext.prototype.finalize = function (cssSelector, callback) {
  808. var result = true;
  809. if (this.notSelectors.length > 0 && (!this.listContext || !this.listContext.alreadyMatched)) {
  810. var notMatcher = SelectorMatcher.createNotMatcher(this.notSelectors);
  811. result = !notMatcher.match(cssSelector, null);
  812. }
  813. if (result && callback && (!this.listContext || !this.listContext.alreadyMatched)) {
  814. if (this.listContext) {
  815. this.listContext.alreadyMatched = true;
  816. }
  817. callback(this.selector, this.cbContext);
  818. }
  819. return result;
  820. };
  821. return SelectorContext;
  822. }());
  823. /**
  824. * @license
  825. * Copyright Google Inc. All Rights Reserved.
  826. *
  827. * Use of this source code is governed by an MIT-style license that can be
  828. * found in the LICENSE file at https://angular.io/license
  829. */
  830. var createInject = makeMetadataFactory('Inject', function (token) { return ({ token: token }); });
  831. var createInjectionToken = makeMetadataFactory('InjectionToken', function (desc) { return ({ _desc: desc, ngInjectableDef: undefined }); });
  832. var createAttribute = makeMetadataFactory('Attribute', function (attributeName) { return ({ attributeName: attributeName }); });
  833. var createContentChildren = makeMetadataFactory('ContentChildren', function (selector, data) {
  834. if (data === void 0) { data = {}; }
  835. return (__assign({ selector: selector, first: false, isViewQuery: false, descendants: false }, data));
  836. });
  837. var createContentChild = makeMetadataFactory('ContentChild', function (selector, data) {
  838. if (data === void 0) { data = {}; }
  839. return (__assign({ selector: selector, first: true, isViewQuery: false, descendants: true }, data));
  840. });
  841. var createViewChildren = makeMetadataFactory('ViewChildren', function (selector, data) {
  842. if (data === void 0) { data = {}; }
  843. return (__assign({ selector: selector, first: false, isViewQuery: true, descendants: true }, data));
  844. });
  845. var createViewChild = makeMetadataFactory('ViewChild', function (selector, data) {
  846. return (__assign({ selector: selector, first: true, isViewQuery: true, descendants: true }, data));
  847. });
  848. var createDirective = makeMetadataFactory('Directive', function (dir) {
  849. if (dir === void 0) { dir = {}; }
  850. return dir;
  851. });
  852. var ViewEncapsulation;
  853. (function (ViewEncapsulation) {
  854. ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
  855. ViewEncapsulation[ViewEncapsulation["Native"] = 1] = "Native";
  856. ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
  857. ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
  858. })(ViewEncapsulation || (ViewEncapsulation = {}));
  859. var ChangeDetectionStrategy;
  860. (function (ChangeDetectionStrategy) {
  861. ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush";
  862. ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default";
  863. })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {}));
  864. var createComponent = makeMetadataFactory('Component', function (c) {
  865. if (c === void 0) { c = {}; }
  866. return (__assign({ changeDetection: ChangeDetectionStrategy.Default }, c));
  867. });
  868. var createPipe = makeMetadataFactory('Pipe', function (p) { return (__assign({ pure: true }, p)); });
  869. var createInput = makeMetadataFactory('Input', function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); });
  870. var createOutput = makeMetadataFactory('Output', function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); });
  871. var createHostBinding = makeMetadataFactory('HostBinding', function (hostPropertyName) { return ({ hostPropertyName: hostPropertyName }); });
  872. var createHostListener = makeMetadataFactory('HostListener', function (eventName, args) { return ({ eventName: eventName, args: args }); });
  873. var createNgModule = makeMetadataFactory('NgModule', function (ngModule) { return ngModule; });
  874. var createInjectable = makeMetadataFactory('Injectable', function (injectable) {
  875. if (injectable === void 0) { injectable = {}; }
  876. return injectable;
  877. });
  878. var CUSTOM_ELEMENTS_SCHEMA = {
  879. name: 'custom-elements'
  880. };
  881. var NO_ERRORS_SCHEMA = {
  882. name: 'no-errors-schema'
  883. };
  884. var createOptional = makeMetadataFactory('Optional');
  885. var createSelf = makeMetadataFactory('Self');
  886. var createSkipSelf = makeMetadataFactory('SkipSelf');
  887. var createHost = makeMetadataFactory('Host');
  888. var Type = Function;
  889. var SecurityContext;
  890. (function (SecurityContext) {
  891. SecurityContext[SecurityContext["NONE"] = 0] = "NONE";
  892. SecurityContext[SecurityContext["HTML"] = 1] = "HTML";
  893. SecurityContext[SecurityContext["STYLE"] = 2] = "STYLE";
  894. SecurityContext[SecurityContext["SCRIPT"] = 3] = "SCRIPT";
  895. SecurityContext[SecurityContext["URL"] = 4] = "URL";
  896. SecurityContext[SecurityContext["RESOURCE_URL"] = 5] = "RESOURCE_URL";
  897. })(SecurityContext || (SecurityContext = {}));
  898. var MissingTranslationStrategy;
  899. (function (MissingTranslationStrategy) {
  900. MissingTranslationStrategy[MissingTranslationStrategy["Error"] = 0] = "Error";
  901. MissingTranslationStrategy[MissingTranslationStrategy["Warning"] = 1] = "Warning";
  902. MissingTranslationStrategy[MissingTranslationStrategy["Ignore"] = 2] = "Ignore";
  903. })(MissingTranslationStrategy || (MissingTranslationStrategy = {}));
  904. function makeMetadataFactory(name, props) {
  905. // This must be declared as a function, not a fat arrow, so that ES2015 devmode produces code
  906. // that works with the static_reflector.ts in the ViewEngine compiler.
  907. // In particular, `_registerDecoratorOrConstructor` assumes that the value returned here can be
  908. // new'ed.
  909. function factory() {
  910. var args = [];
  911. for (var _i = 0; _i < arguments.length; _i++) {
  912. args[_i] = arguments[_i];
  913. }
  914. var values = props ? props.apply(void 0, __spread(args)) : {};
  915. return __assign({ ngMetadataName: name }, values);
  916. }
  917. factory.isTypeOf = function (obj) { return obj && obj.ngMetadataName === name; };
  918. factory.ngMetadataName = name;
  919. return factory;
  920. }
  921. function parserSelectorToSimpleSelector(selector) {
  922. var classes = selector.classNames && selector.classNames.length ? __spread([8 /* CLASS */], selector.classNames) :
  923. [];
  924. var elementName = selector.element && selector.element !== '*' ? selector.element : '';
  925. return __spread([elementName], selector.attrs, classes);
  926. }
  927. function parserSelectorToNegativeSelector(selector) {
  928. var classes = selector.classNames && selector.classNames.length ? __spread([8 /* CLASS */], selector.classNames) :
  929. [];
  930. if (selector.element) {
  931. return __spread([
  932. 1 /* NOT */ | 4 /* ELEMENT */, selector.element
  933. ], selector.attrs, classes);
  934. }
  935. else if (selector.attrs.length) {
  936. return __spread([1 /* NOT */ | 2 /* ATTRIBUTE */], selector.attrs, classes);
  937. }
  938. else {
  939. return selector.classNames && selector.classNames.length ? __spread([1 /* NOT */ | 8 /* CLASS */], selector.classNames) :
  940. [];
  941. }
  942. }
  943. function parserSelectorToR3Selector(selector) {
  944. var positive = parserSelectorToSimpleSelector(selector);
  945. var negative = selector.notSelectors && selector.notSelectors.length ?
  946. selector.notSelectors.map(function (notSelector) { return parserSelectorToNegativeSelector(notSelector); }) :
  947. [];
  948. return positive.concat.apply(positive, __spread(negative));
  949. }
  950. function parseSelectorToR3Selector(selector) {
  951. return selector ? CssSelector.parse(selector).map(parserSelectorToR3Selector) : [];
  952. }
  953. var core = /*#__PURE__*/Object.freeze({
  954. createInject: createInject,
  955. createInjectionToken: createInjectionToken,
  956. createAttribute: createAttribute,
  957. createContentChildren: createContentChildren,
  958. createContentChild: createContentChild,
  959. createViewChildren: createViewChildren,
  960. createViewChild: createViewChild,
  961. createDirective: createDirective,
  962. get ViewEncapsulation () { return ViewEncapsulation; },
  963. get ChangeDetectionStrategy () { return ChangeDetectionStrategy; },
  964. createComponent: createComponent,
  965. createPipe: createPipe,
  966. createInput: createInput,
  967. createOutput: createOutput,
  968. createHostBinding: createHostBinding,
  969. createHostListener: createHostListener,
  970. createNgModule: createNgModule,
  971. createInjectable: createInjectable,
  972. CUSTOM_ELEMENTS_SCHEMA: CUSTOM_ELEMENTS_SCHEMA,
  973. NO_ERRORS_SCHEMA: NO_ERRORS_SCHEMA,
  974. createOptional: createOptional,
  975. createSelf: createSelf,
  976. createSkipSelf: createSkipSelf,
  977. createHost: createHost,
  978. Type: Type,
  979. get SecurityContext () { return SecurityContext; },
  980. get MissingTranslationStrategy () { return MissingTranslationStrategy; },
  981. parseSelectorToR3Selector: parseSelectorToR3Selector
  982. });
  983. /**
  984. * @license
  985. * Copyright Google Inc. All Rights Reserved.
  986. *
  987. * Use of this source code is governed by an MIT-style license that can be
  988. * found in the LICENSE file at https://angular.io/license
  989. */
  990. //// Types
  991. var TypeModifier;
  992. (function (TypeModifier) {
  993. TypeModifier[TypeModifier["Const"] = 0] = "Const";
  994. })(TypeModifier || (TypeModifier = {}));
  995. var Type$1 = /** @class */ (function () {
  996. function Type(modifiers) {
  997. if (modifiers === void 0) { modifiers = null; }
  998. this.modifiers = modifiers;
  999. if (!modifiers) {
  1000. this.modifiers = [];
  1001. }
  1002. }
  1003. Type.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; };
  1004. return Type;
  1005. }());
  1006. (function (BuiltinTypeName) {
  1007. BuiltinTypeName[BuiltinTypeName["Dynamic"] = 0] = "Dynamic";
  1008. BuiltinTypeName[BuiltinTypeName["Bool"] = 1] = "Bool";
  1009. BuiltinTypeName[BuiltinTypeName["String"] = 2] = "String";
  1010. BuiltinTypeName[BuiltinTypeName["Int"] = 3] = "Int";
  1011. BuiltinTypeName[BuiltinTypeName["Number"] = 4] = "Number";
  1012. BuiltinTypeName[BuiltinTypeName["Function"] = 5] = "Function";
  1013. BuiltinTypeName[BuiltinTypeName["Inferred"] = 6] = "Inferred";
  1014. BuiltinTypeName[BuiltinTypeName["None"] = 7] = "None";
  1015. })(exports.BuiltinTypeName || (exports.BuiltinTypeName = {}));
  1016. var BuiltinType = /** @class */ (function (_super) {
  1017. __extends(BuiltinType, _super);
  1018. function BuiltinType(name, modifiers) {
  1019. if (modifiers === void 0) { modifiers = null; }
  1020. var _this = _super.call(this, modifiers) || this;
  1021. _this.name = name;
  1022. return _this;
  1023. }
  1024. BuiltinType.prototype.visitType = function (visitor, context) {
  1025. return visitor.visitBuiltinType(this, context);
  1026. };
  1027. return BuiltinType;
  1028. }(Type$1));
  1029. var ExpressionType = /** @class */ (function (_super) {
  1030. __extends(ExpressionType, _super);
  1031. function ExpressionType(value, modifiers, typeParams) {
  1032. if (modifiers === void 0) { modifiers = null; }
  1033. if (typeParams === void 0) { typeParams = null; }
  1034. var _this = _super.call(this, modifiers) || this;
  1035. _this.value = value;
  1036. _this.typeParams = typeParams;
  1037. return _this;
  1038. }
  1039. ExpressionType.prototype.visitType = function (visitor, context) {
  1040. return visitor.visitExpressionType(this, context);
  1041. };
  1042. return ExpressionType;
  1043. }(Type$1));
  1044. var ArrayType = /** @class */ (function (_super) {
  1045. __extends(ArrayType, _super);
  1046. function ArrayType(of, modifiers) {
  1047. if (modifiers === void 0) { modifiers = null; }
  1048. var _this = _super.call(this, modifiers) || this;
  1049. _this.of = of;
  1050. return _this;
  1051. }
  1052. ArrayType.prototype.visitType = function (visitor, context) {
  1053. return visitor.visitArrayType(this, context);
  1054. };
  1055. return ArrayType;
  1056. }(Type$1));
  1057. var MapType = /** @class */ (function (_super) {
  1058. __extends(MapType, _super);
  1059. function MapType(valueType, modifiers) {
  1060. if (modifiers === void 0) { modifiers = null; }
  1061. var _this = _super.call(this, modifiers) || this;
  1062. _this.valueType = valueType || null;
  1063. return _this;
  1064. }
  1065. MapType.prototype.visitType = function (visitor, context) { return visitor.visitMapType(this, context); };
  1066. return MapType;
  1067. }(Type$1));
  1068. var DYNAMIC_TYPE = new BuiltinType(exports.BuiltinTypeName.Dynamic);
  1069. var INFERRED_TYPE = new BuiltinType(exports.BuiltinTypeName.Inferred);
  1070. var BOOL_TYPE = new BuiltinType(exports.BuiltinTypeName.Bool);
  1071. var INT_TYPE = new BuiltinType(exports.BuiltinTypeName.Int);
  1072. var NUMBER_TYPE = new BuiltinType(exports.BuiltinTypeName.Number);
  1073. var STRING_TYPE = new BuiltinType(exports.BuiltinTypeName.String);
  1074. var FUNCTION_TYPE = new BuiltinType(exports.BuiltinTypeName.Function);
  1075. var NONE_TYPE = new BuiltinType(exports.BuiltinTypeName.None);
  1076. (function (BinaryOperator) {
  1077. BinaryOperator[BinaryOperator["Equals"] = 0] = "Equals";
  1078. BinaryOperator[BinaryOperator["NotEquals"] = 1] = "NotEquals";
  1079. BinaryOperator[BinaryOperator["Identical"] = 2] = "Identical";
  1080. BinaryOperator[BinaryOperator["NotIdentical"] = 3] = "NotIdentical";
  1081. BinaryOperator[BinaryOperator["Minus"] = 4] = "Minus";
  1082. BinaryOperator[BinaryOperator["Plus"] = 5] = "Plus";
  1083. BinaryOperator[BinaryOperator["Divide"] = 6] = "Divide";
  1084. BinaryOperator[BinaryOperator["Multiply"] = 7] = "Multiply";
  1085. BinaryOperator[BinaryOperator["Modulo"] = 8] = "Modulo";
  1086. BinaryOperator[BinaryOperator["And"] = 9] = "And";
  1087. BinaryOperator[BinaryOperator["Or"] = 10] = "Or";
  1088. BinaryOperator[BinaryOperator["BitwiseAnd"] = 11] = "BitwiseAnd";
  1089. BinaryOperator[BinaryOperator["Lower"] = 12] = "Lower";
  1090. BinaryOperator[BinaryOperator["LowerEquals"] = 13] = "LowerEquals";
  1091. BinaryOperator[BinaryOperator["Bigger"] = 14] = "Bigger";
  1092. BinaryOperator[BinaryOperator["BiggerEquals"] = 15] = "BiggerEquals";
  1093. })(exports.BinaryOperator || (exports.BinaryOperator = {}));
  1094. function nullSafeIsEquivalent(base, other) {
  1095. if (base == null || other == null) {
  1096. return base == other;
  1097. }
  1098. return base.isEquivalent(other);
  1099. }
  1100. function areAllEquivalent(base, other) {
  1101. var len = base.length;
  1102. if (len !== other.length) {
  1103. return false;
  1104. }
  1105. for (var i = 0; i < len; i++) {
  1106. if (!base[i].isEquivalent(other[i])) {
  1107. return false;
  1108. }
  1109. }
  1110. return true;
  1111. }
  1112. var Expression = /** @class */ (function () {
  1113. function Expression(type, sourceSpan) {
  1114. this.type = type || null;
  1115. this.sourceSpan = sourceSpan || null;
  1116. }
  1117. Expression.prototype.prop = function (name, sourceSpan) {
  1118. return new ReadPropExpr(this, name, null, sourceSpan);
  1119. };
  1120. Expression.prototype.key = function (index, type, sourceSpan) {
  1121. return new ReadKeyExpr(this, index, type, sourceSpan);
  1122. };
  1123. Expression.prototype.callMethod = function (name, params, sourceSpan) {
  1124. return new InvokeMethodExpr(this, name, params, null, sourceSpan);
  1125. };
  1126. Expression.prototype.callFn = function (params, sourceSpan) {
  1127. return new InvokeFunctionExpr(this, params, null, sourceSpan);
  1128. };
  1129. Expression.prototype.instantiate = function (params, type, sourceSpan) {
  1130. return new InstantiateExpr(this, params, type, sourceSpan);
  1131. };
  1132. Expression.prototype.conditional = function (trueCase, falseCase, sourceSpan) {
  1133. if (falseCase === void 0) { falseCase = null; }
  1134. return new ConditionalExpr(this, trueCase, falseCase, null, sourceSpan);
  1135. };
  1136. Expression.prototype.equals = function (rhs, sourceSpan) {
  1137. return new BinaryOperatorExpr(exports.BinaryOperator.Equals, this, rhs, null, sourceSpan);
  1138. };
  1139. Expression.prototype.notEquals = function (rhs, sourceSpan) {
  1140. return new BinaryOperatorExpr(exports.BinaryOperator.NotEquals, this, rhs, null, sourceSpan);
  1141. };
  1142. Expression.prototype.identical = function (rhs, sourceSpan) {
  1143. return new BinaryOperatorExpr(exports.BinaryOperator.Identical, this, rhs, null, sourceSpan);
  1144. };
  1145. Expression.prototype.notIdentical = function (rhs, sourceSpan) {
  1146. return new BinaryOperatorExpr(exports.BinaryOperator.NotIdentical, this, rhs, null, sourceSpan);
  1147. };
  1148. Expression.prototype.minus = function (rhs, sourceSpan) {
  1149. return new BinaryOperatorExpr(exports.BinaryOperator.Minus, this, rhs, null, sourceSpan);
  1150. };
  1151. Expression.prototype.plus = function (rhs, sourceSpan) {
  1152. return new BinaryOperatorExpr(exports.BinaryOperator.Plus, this, rhs, null, sourceSpan);
  1153. };
  1154. Expression.prototype.divide = function (rhs, sourceSpan) {
  1155. return new BinaryOperatorExpr(exports.BinaryOperator.Divide, this, rhs, null, sourceSpan);
  1156. };
  1157. Expression.prototype.multiply = function (rhs, sourceSpan) {
  1158. return new BinaryOperatorExpr(exports.BinaryOperator.Multiply, this, rhs, null, sourceSpan);
  1159. };
  1160. Expression.prototype.modulo = function (rhs, sourceSpan) {
  1161. return new BinaryOperatorExpr(exports.BinaryOperator.Modulo, this, rhs, null, sourceSpan);
  1162. };
  1163. Expression.prototype.and = function (rhs, sourceSpan) {
  1164. return new BinaryOperatorExpr(exports.BinaryOperator.And, this, rhs, null, sourceSpan);
  1165. };
  1166. Expression.prototype.bitwiseAnd = function (rhs, sourceSpan, parens) {
  1167. if (parens === void 0) { parens = true; }
  1168. return new BinaryOperatorExpr(exports.BinaryOperator.BitwiseAnd, this, rhs, null, sourceSpan, parens);
  1169. };
  1170. Expression.prototype.or = function (rhs, sourceSpan) {
  1171. return new BinaryOperatorExpr(exports.BinaryOperator.Or, this, rhs, null, sourceSpan);
  1172. };
  1173. Expression.prototype.lower = function (rhs, sourceSpan) {
  1174. return new BinaryOperatorExpr(exports.BinaryOperator.Lower, this, rhs, null, sourceSpan);
  1175. };
  1176. Expression.prototype.lowerEquals = function (rhs, sourceSpan) {
  1177. return new BinaryOperatorExpr(exports.BinaryOperator.LowerEquals, this, rhs, null, sourceSpan);
  1178. };
  1179. Expression.prototype.bigger = function (rhs, sourceSpan) {
  1180. return new BinaryOperatorExpr(exports.BinaryOperator.Bigger, this, rhs, null, sourceSpan);
  1181. };
  1182. Expression.prototype.biggerEquals = function (rhs, sourceSpan) {
  1183. return new BinaryOperatorExpr(exports.BinaryOperator.BiggerEquals, this, rhs, null, sourceSpan);
  1184. };
  1185. Expression.prototype.isBlank = function (sourceSpan) {
  1186. // Note: We use equals by purpose here to compare to null and undefined in JS.
  1187. // We use the typed null to allow strictNullChecks to narrow types.
  1188. return this.equals(TYPED_NULL_EXPR, sourceSpan);
  1189. };
  1190. Expression.prototype.cast = function (type, sourceSpan) {
  1191. return new CastExpr(this, type, sourceSpan);
  1192. };
  1193. Expression.prototype.toStmt = function () { return new ExpressionStatement(this, null); };
  1194. return Expression;
  1195. }());
  1196. (function (BuiltinVar) {
  1197. BuiltinVar[BuiltinVar["This"] = 0] = "This";
  1198. BuiltinVar[BuiltinVar["Super"] = 1] = "Super";
  1199. BuiltinVar[BuiltinVar["CatchError"] = 2] = "CatchError";
  1200. BuiltinVar[BuiltinVar["CatchStack"] = 3] = "CatchStack";
  1201. })(exports.BuiltinVar || (exports.BuiltinVar = {}));
  1202. var ReadVarExpr = /** @class */ (function (_super) {
  1203. __extends(ReadVarExpr, _super);
  1204. function ReadVarExpr(name, type, sourceSpan) {
  1205. var _this = _super.call(this, type, sourceSpan) || this;
  1206. if (typeof name === 'string') {
  1207. _this.name = name;
  1208. _this.builtin = null;
  1209. }
  1210. else {
  1211. _this.name = null;
  1212. _this.builtin = name;
  1213. }
  1214. return _this;
  1215. }
  1216. ReadVarExpr.prototype.isEquivalent = function (e) {
  1217. return e instanceof ReadVarExpr && this.name === e.name && this.builtin === e.builtin;
  1218. };
  1219. ReadVarExpr.prototype.isConstant = function () { return false; };
  1220. ReadVarExpr.prototype.visitExpression = function (visitor, context) {
  1221. return visitor.visitReadVarExpr(this, context);
  1222. };
  1223. ReadVarExpr.prototype.set = function (value) {
  1224. if (!this.name) {
  1225. throw new Error("Built in variable " + this.builtin + " can not be assigned to.");
  1226. }
  1227. return new WriteVarExpr(this.name, value, null, this.sourceSpan);
  1228. };
  1229. return ReadVarExpr;
  1230. }(Expression));
  1231. var TypeofExpr = /** @class */ (function (_super) {
  1232. __extends(TypeofExpr, _super);
  1233. function TypeofExpr(expr, type, sourceSpan) {
  1234. var _this = _super.call(this, type, sourceSpan) || this;
  1235. _this.expr = expr;
  1236. return _this;
  1237. }
  1238. TypeofExpr.prototype.visitExpression = function (visitor, context) {
  1239. return visitor.visitTypeofExpr(this, context);
  1240. };
  1241. TypeofExpr.prototype.isEquivalent = function (e) {
  1242. return e instanceof TypeofExpr && e.expr.isEquivalent(this.expr);
  1243. };
  1244. TypeofExpr.prototype.isConstant = function () { return this.expr.isConstant(); };
  1245. return TypeofExpr;
  1246. }(Expression));
  1247. var WrappedNodeExpr = /** @class */ (function (_super) {
  1248. __extends(WrappedNodeExpr, _super);
  1249. function WrappedNodeExpr(node, type, sourceSpan) {
  1250. var _this = _super.call(this, type, sourceSpan) || this;
  1251. _this.node = node;
  1252. return _this;
  1253. }
  1254. WrappedNodeExpr.prototype.isEquivalent = function (e) {
  1255. return e instanceof WrappedNodeExpr && this.node === e.node;
  1256. };
  1257. WrappedNodeExpr.prototype.isConstant = function () { return false; };
  1258. WrappedNodeExpr.prototype.visitExpression = function (visitor, context) {
  1259. return visitor.visitWrappedNodeExpr(this, context);
  1260. };
  1261. return WrappedNodeExpr;
  1262. }(Expression));
  1263. var WriteVarExpr = /** @class */ (function (_super) {
  1264. __extends(WriteVarExpr, _super);
  1265. function WriteVarExpr(name, value, type, sourceSpan) {
  1266. var _this = _super.call(this, type || value.type, sourceSpan) || this;
  1267. _this.name = name;
  1268. _this.value = value;
  1269. return _this;
  1270. }
  1271. WriteVarExpr.prototype.isEquivalent = function (e) {
  1272. return e instanceof WriteVarExpr && this.name === e.name && this.value.isEquivalent(e.value);
  1273. };
  1274. WriteVarExpr.prototype.isConstant = function () { return false; };
  1275. WriteVarExpr.prototype.visitExpression = function (visitor, context) {
  1276. return visitor.visitWriteVarExpr(this, context);
  1277. };
  1278. WriteVarExpr.prototype.toDeclStmt = function (type, modifiers) {
  1279. return new DeclareVarStmt(this.name, this.value, type, modifiers, this.sourceSpan);
  1280. };
  1281. WriteVarExpr.prototype.toConstDecl = function () { return this.toDeclStmt(INFERRED_TYPE, [exports.StmtModifier.Final]); };
  1282. return WriteVarExpr;
  1283. }(Expression));
  1284. var WriteKeyExpr = /** @class */ (function (_super) {
  1285. __extends(WriteKeyExpr, _super);
  1286. function WriteKeyExpr(receiver, index, value, type, sourceSpan) {
  1287. var _this = _super.call(this, type || value.type, sourceSpan) || this;
  1288. _this.receiver = receiver;
  1289. _this.index = index;
  1290. _this.value = value;
  1291. return _this;
  1292. }
  1293. WriteKeyExpr.prototype.isEquivalent = function (e) {
  1294. return e instanceof WriteKeyExpr && this.receiver.isEquivalent(e.receiver) &&
  1295. this.index.isEquivalent(e.index) && this.value.isEquivalent(e.value);
  1296. };
  1297. WriteKeyExpr.prototype.isConstant = function () { return false; };
  1298. WriteKeyExpr.prototype.visitExpression = function (visitor, context) {
  1299. return visitor.visitWriteKeyExpr(this, context);
  1300. };
  1301. return WriteKeyExpr;
  1302. }(Expression));
  1303. var WritePropExpr = /** @class */ (function (_super) {
  1304. __extends(WritePropExpr, _super);
  1305. function WritePropExpr(receiver, name, value, type, sourceSpan) {
  1306. var _this = _super.call(this, type || value.type, sourceSpan) || this;
  1307. _this.receiver = receiver;
  1308. _this.name = name;
  1309. _this.value = value;
  1310. return _this;
  1311. }
  1312. WritePropExpr.prototype.isEquivalent = function (e) {
  1313. return e instanceof WritePropExpr && this.receiver.isEquivalent(e.receiver) &&
  1314. this.name === e.name && this.value.isEquivalent(e.value);
  1315. };
  1316. WritePropExpr.prototype.isConstant = function () { return false; };
  1317. WritePropExpr.prototype.visitExpression = function (visitor, context) {
  1318. return visitor.visitWritePropExpr(this, context);
  1319. };
  1320. return WritePropExpr;
  1321. }(Expression));
  1322. (function (BuiltinMethod) {
  1323. BuiltinMethod[BuiltinMethod["ConcatArray"] = 0] = "ConcatArray";
  1324. BuiltinMethod[BuiltinMethod["SubscribeObservable"] = 1] = "SubscribeObservable";
  1325. BuiltinMethod[BuiltinMethod["Bind"] = 2] = "Bind";
  1326. })(exports.BuiltinMethod || (exports.BuiltinMethod = {}));
  1327. var InvokeMethodExpr = /** @class */ (function (_super) {
  1328. __extends(InvokeMethodExpr, _super);
  1329. function InvokeMethodExpr(receiver, method, args, type, sourceSpan) {
  1330. var _this = _super.call(this, type, sourceSpan) || this;
  1331. _this.receiver = receiver;
  1332. _this.args = args;
  1333. if (typeof method === 'string') {
  1334. _this.name = method;
  1335. _this.builtin = null;
  1336. }
  1337. else {
  1338. _this.name = null;
  1339. _this.builtin = method;
  1340. }
  1341. return _this;
  1342. }
  1343. InvokeMethodExpr.prototype.isEquivalent = function (e) {
  1344. return e instanceof InvokeMethodExpr && this.receiver.isEquivalent(e.receiver) &&
  1345. this.name === e.name && this.builtin === e.builtin && areAllEquivalent(this.args, e.args);
  1346. };
  1347. InvokeMethodExpr.prototype.isConstant = function () { return false; };
  1348. InvokeMethodExpr.prototype.visitExpression = function (visitor, context) {
  1349. return visitor.visitInvokeMethodExpr(this, context);
  1350. };
  1351. return InvokeMethodExpr;
  1352. }(Expression));
  1353. var InvokeFunctionExpr = /** @class */ (function (_super) {
  1354. __extends(InvokeFunctionExpr, _super);
  1355. function InvokeFunctionExpr(fn, args, type, sourceSpan, pure) {
  1356. if (pure === void 0) { pure = false; }
  1357. var _this = _super.call(this, type, sourceSpan) || this;
  1358. _this.fn = fn;
  1359. _this.args = args;
  1360. _this.pure = pure;
  1361. return _this;
  1362. }
  1363. InvokeFunctionExpr.prototype.isEquivalent = function (e) {
  1364. return e instanceof InvokeFunctionExpr && this.fn.isEquivalent(e.fn) &&
  1365. areAllEquivalent(this.args, e.args) && this.pure === e.pure;
  1366. };
  1367. InvokeFunctionExpr.prototype.isConstant = function () { return false; };
  1368. InvokeFunctionExpr.prototype.visitExpression = function (visitor, context) {
  1369. return visitor.visitInvokeFunctionExpr(this, context);
  1370. };
  1371. return InvokeFunctionExpr;
  1372. }(Expression));
  1373. var InstantiateExpr = /** @class */ (function (_super) {
  1374. __extends(InstantiateExpr, _super);
  1375. function InstantiateExpr(classExpr, args, type, sourceSpan) {
  1376. var _this = _super.call(this, type, sourceSpan) || this;
  1377. _this.classExpr = classExpr;
  1378. _this.args = args;
  1379. return _this;
  1380. }
  1381. InstantiateExpr.prototype.isEquivalent = function (e) {
  1382. return e instanceof InstantiateExpr && this.classExpr.isEquivalent(e.classExpr) &&
  1383. areAllEquivalent(this.args, e.args);
  1384. };
  1385. InstantiateExpr.prototype.isConstant = function () { return false; };
  1386. InstantiateExpr.prototype.visitExpression = function (visitor, context) {
  1387. return visitor.visitInstantiateExpr(this, context);
  1388. };
  1389. return InstantiateExpr;
  1390. }(Expression));
  1391. var LiteralExpr = /** @class */ (function (_super) {
  1392. __extends(LiteralExpr, _super);
  1393. function LiteralExpr(value, type, sourceSpan) {
  1394. var _this = _super.call(this, type, sourceSpan) || this;
  1395. _this.value = value;
  1396. return _this;
  1397. }
  1398. LiteralExpr.prototype.isEquivalent = function (e) {
  1399. return e instanceof LiteralExpr && this.value === e.value;
  1400. };
  1401. LiteralExpr.prototype.isConstant = function () { return true; };
  1402. LiteralExpr.prototype.visitExpression = function (visitor, context) {
  1403. return visitor.visitLiteralExpr(this, context);
  1404. };
  1405. return LiteralExpr;
  1406. }(Expression));
  1407. var ExternalExpr = /** @class */ (function (_super) {
  1408. __extends(ExternalExpr, _super);
  1409. function ExternalExpr(value, type, typeParams, sourceSpan) {
  1410. if (typeParams === void 0) { typeParams = null; }
  1411. var _this = _super.call(this, type, sourceSpan) || this;
  1412. _this.value = value;
  1413. _this.typeParams = typeParams;
  1414. return _this;
  1415. }
  1416. ExternalExpr.prototype.isEquivalent = function (e) {
  1417. return e instanceof ExternalExpr && this.value.name === e.value.name &&
  1418. this.value.moduleName === e.value.moduleName && this.value.runtime === e.value.runtime;
  1419. };
  1420. ExternalExpr.prototype.isConstant = function () { return false; };
  1421. ExternalExpr.prototype.visitExpression = function (visitor, context) {
  1422. return visitor.visitExternalExpr(this, context);
  1423. };
  1424. return ExternalExpr;
  1425. }(Expression));
  1426. var ExternalReference = /** @class */ (function () {
  1427. function ExternalReference(moduleName, name, runtime) {
  1428. this.moduleName = moduleName;
  1429. this.name = name;
  1430. this.runtime = runtime;
  1431. }
  1432. return ExternalReference;
  1433. }());
  1434. var ConditionalExpr = /** @class */ (function (_super) {
  1435. __extends(ConditionalExpr, _super);
  1436. function ConditionalExpr(condition, trueCase, falseCase, type, sourceSpan) {
  1437. if (falseCase === void 0) { falseCase = null; }
  1438. var _this = _super.call(this, type || trueCase.type, sourceSpan) || this;
  1439. _this.condition = condition;
  1440. _this.falseCase = falseCase;
  1441. _this.trueCase = trueCase;
  1442. return _this;
  1443. }
  1444. ConditionalExpr.prototype.isEquivalent = function (e) {
  1445. return e instanceof ConditionalExpr && this.condition.isEquivalent(e.condition) &&
  1446. this.trueCase.isEquivalent(e.trueCase) && nullSafeIsEquivalent(this.falseCase, e.falseCase);
  1447. };
  1448. ConditionalExpr.prototype.isConstant = function () { return false; };
  1449. ConditionalExpr.prototype.visitExpression = function (visitor, context) {
  1450. return visitor.visitConditionalExpr(this, context);
  1451. };
  1452. return ConditionalExpr;
  1453. }(Expression));
  1454. var NotExpr = /** @class */ (function (_super) {
  1455. __extends(NotExpr, _super);
  1456. function NotExpr(condition, sourceSpan) {
  1457. var _this = _super.call(this, BOOL_TYPE, sourceSpan) || this;
  1458. _this.condition = condition;
  1459. return _this;
  1460. }
  1461. NotExpr.prototype.isEquivalent = function (e) {
  1462. return e instanceof NotExpr && this.condition.isEquivalent(e.condition);
  1463. };
  1464. NotExpr.prototype.isConstant = function () { return false; };
  1465. NotExpr.prototype.visitExpression = function (visitor, context) {
  1466. return visitor.visitNotExpr(this, context);
  1467. };
  1468. return NotExpr;
  1469. }(Expression));
  1470. var AssertNotNull = /** @class */ (function (_super) {
  1471. __extends(AssertNotNull, _super);
  1472. function AssertNotNull(condition, sourceSpan) {
  1473. var _this = _super.call(this, condition.type, sourceSpan) || this;
  1474. _this.condition = condition;
  1475. return _this;
  1476. }
  1477. AssertNotNull.prototype.isEquivalent = function (e) {
  1478. return e instanceof AssertNotNull && this.condition.isEquivalent(e.condition);
  1479. };
  1480. AssertNotNull.prototype.isConstant = function () { return false; };
  1481. AssertNotNull.prototype.visitExpression = function (visitor, context) {
  1482. return visitor.visitAssertNotNullExpr(this, context);
  1483. };
  1484. return AssertNotNull;
  1485. }(Expression));
  1486. var CastExpr = /** @class */ (function (_super) {
  1487. __extends(CastExpr, _super);
  1488. function CastExpr(value, type, sourceSpan) {
  1489. var _this = _super.call(this, type, sourceSpan) || this;
  1490. _this.value = value;
  1491. return _this;
  1492. }
  1493. CastExpr.prototype.isEquivalent = function (e) {
  1494. return e instanceof CastExpr && this.value.isEquivalent(e.value);
  1495. };
  1496. CastExpr.prototype.isConstant = function () { return false; };
  1497. CastExpr.prototype.visitExpression = function (visitor, context) {
  1498. return visitor.visitCastExpr(this, context);
  1499. };
  1500. return CastExpr;
  1501. }(Expression));
  1502. var FnParam = /** @class */ (function () {
  1503. function FnParam(name, type) {
  1504. if (type === void 0) { type = null; }
  1505. this.name = name;
  1506. this.type = type;
  1507. }
  1508. FnParam.prototype.isEquivalent = function (param) { return this.name === param.name; };
  1509. return FnParam;
  1510. }());
  1511. var FunctionExpr = /** @class */ (function (_super) {
  1512. __extends(FunctionExpr, _super);
  1513. function FunctionExpr(params, statements, type, sourceSpan, name) {
  1514. var _this = _super.call(this, type, sourceSpan) || this;
  1515. _this.params = params;
  1516. _this.statements = statements;
  1517. _this.name = name;
  1518. return _this;
  1519. }
  1520. FunctionExpr.prototype.isEquivalent = function (e) {
  1521. return e instanceof FunctionExpr && areAllEquivalent(this.params, e.params) &&
  1522. areAllEquivalent(this.statements, e.statements);
  1523. };
  1524. FunctionExpr.prototype.isConstant = function () { return false; };
  1525. FunctionExpr.prototype.visitExpression = function (visitor, context) {
  1526. return visitor.visitFunctionExpr(this, context);
  1527. };
  1528. FunctionExpr.prototype.toDeclStmt = function (name, modifiers) {
  1529. if (modifiers === void 0) { modifiers = null; }
  1530. return new DeclareFunctionStmt(name, this.params, this.statements, this.type, modifiers, this.sourceSpan);
  1531. };
  1532. return FunctionExpr;
  1533. }(Expression));
  1534. var BinaryOperatorExpr = /** @class */ (function (_super) {
  1535. __extends(BinaryOperatorExpr, _super);
  1536. function BinaryOperatorExpr(operator, lhs, rhs, type, sourceSpan, parens) {
  1537. if (parens === void 0) { parens = true; }
  1538. var _this = _super.call(this, type || lhs.type, sourceSpan) || this;
  1539. _this.operator = operator;
  1540. _this.rhs = rhs;
  1541. _this.parens = parens;
  1542. _this.lhs = lhs;
  1543. return _this;
  1544. }
  1545. BinaryOperatorExpr.prototype.isEquivalent = function (e) {
  1546. return e instanceof BinaryOperatorExpr && this.operator === e.operator &&
  1547. this.lhs.isEquivalent(e.lhs) && this.rhs.isEquivalent(e.rhs);
  1548. };
  1549. BinaryOperatorExpr.prototype.isConstant = function () { return false; };
  1550. BinaryOperatorExpr.prototype.visitExpression = function (visitor, context) {
  1551. return visitor.visitBinaryOperatorExpr(this, context);
  1552. };
  1553. return BinaryOperatorExpr;
  1554. }(Expression));
  1555. var ReadPropExpr = /** @class */ (function (_super) {
  1556. __extends(ReadPropExpr, _super);
  1557. function ReadPropExpr(receiver, name, type, sourceSpan) {
  1558. var _this = _super.call(this, type, sourceSpan) || this;
  1559. _this.receiver = receiver;
  1560. _this.name = name;
  1561. return _this;
  1562. }
  1563. ReadPropExpr.prototype.isEquivalent = function (e) {
  1564. return e instanceof ReadPropExpr && this.receiver.isEquivalent(e.receiver) &&
  1565. this.name === e.name;
  1566. };
  1567. ReadPropExpr.prototype.isConstant = function () { return false; };
  1568. ReadPropExpr.prototype.visitExpression = function (visitor, context) {
  1569. return visitor.visitReadPropExpr(this, context);
  1570. };
  1571. ReadPropExpr.prototype.set = function (value) {
  1572. return new WritePropExpr(this.receiver, this.name, value, null, this.sourceSpan);
  1573. };
  1574. return ReadPropExpr;
  1575. }(Expression));
  1576. var ReadKeyExpr = /** @class */ (function (_super) {
  1577. __extends(ReadKeyExpr, _super);
  1578. function ReadKeyExpr(receiver, index, type, sourceSpan) {
  1579. var _this = _super.call(this, type, sourceSpan) || this;
  1580. _this.receiver = receiver;
  1581. _this.index = index;
  1582. return _this;
  1583. }
  1584. ReadKeyExpr.prototype.isEquivalent = function (e) {
  1585. return e instanceof ReadKeyExpr && this.receiver.isEquivalent(e.receiver) &&
  1586. this.index.isEquivalent(e.index);
  1587. };
  1588. ReadKeyExpr.prototype.isConstant = function () { return false; };
  1589. ReadKeyExpr.prototype.visitExpression = function (visitor, context) {
  1590. return visitor.visitReadKeyExpr(this, context);
  1591. };
  1592. ReadKeyExpr.prototype.set = function (value) {
  1593. return new WriteKeyExpr(this.receiver, this.index, value, null, this.sourceSpan);
  1594. };
  1595. return ReadKeyExpr;
  1596. }(Expression));
  1597. var LiteralArrayExpr = /** @class */ (function (_super) {
  1598. __extends(LiteralArrayExpr, _super);
  1599. function LiteralArrayExpr(entries, type, sourceSpan) {
  1600. var _this = _super.call(this, type, sourceSpan) || this;
  1601. _this.entries = entries;
  1602. return _this;
  1603. }
  1604. LiteralArrayExpr.prototype.isConstant = function () { return this.entries.every(function (e) { return e.isConstant(); }); };
  1605. LiteralArrayExpr.prototype.isEquivalent = function (e) {
  1606. return e instanceof LiteralArrayExpr && areAllEquivalent(this.entries, e.entries);
  1607. };
  1608. LiteralArrayExpr.prototype.visitExpression = function (visitor, context) {
  1609. return visitor.visitLiteralArrayExpr(this, context);
  1610. };
  1611. return LiteralArrayExpr;
  1612. }(Expression));
  1613. var LiteralMapEntry = /** @class */ (function () {
  1614. function LiteralMapEntry(key, value, quoted) {
  1615. this.key = key;
  1616. this.value = value;
  1617. this.quoted = quoted;
  1618. }
  1619. LiteralMapEntry.prototype.isEquivalent = function (e) {
  1620. return this.key === e.key && this.value.isEquivalent(e.value);
  1621. };
  1622. return LiteralMapEntry;
  1623. }());
  1624. var LiteralMapExpr = /** @class */ (function (_super) {
  1625. __extends(LiteralMapExpr, _super);
  1626. function LiteralMapExpr(entries, type, sourceSpan) {
  1627. var _this = _super.call(this, type, sourceSpan) || this;
  1628. _this.entries = entries;
  1629. _this.valueType = null;
  1630. if (type) {
  1631. _this.valueType = type.valueType;
  1632. }
  1633. return _this;
  1634. }
  1635. LiteralMapExpr.prototype.isEquivalent = function (e) {
  1636. return e instanceof LiteralMapExpr && areAllEquivalent(this.entries, e.entries);
  1637. };
  1638. LiteralMapExpr.prototype.isConstant = function () { return this.entries.every(function (e) { return e.value.isConstant(); }); };
  1639. LiteralMapExpr.prototype.visitExpression = function (visitor, context) {
  1640. return visitor.visitLiteralMapExpr(this, context);
  1641. };
  1642. return LiteralMapExpr;
  1643. }(Expression));
  1644. var CommaExpr = /** @class */ (function (_super) {
  1645. __extends(CommaExpr, _super);
  1646. function CommaExpr(parts, sourceSpan) {
  1647. var _this = _super.call(this, parts[parts.length - 1].type, sourceSpan) || this;
  1648. _this.parts = parts;
  1649. return _this;
  1650. }
  1651. CommaExpr.prototype.isEquivalent = function (e) {
  1652. return e instanceof CommaExpr && areAllEquivalent(this.parts, e.parts);
  1653. };
  1654. CommaExpr.prototype.isConstant = function () { return false; };
  1655. CommaExpr.prototype.visitExpression = function (visitor, context) {
  1656. return visitor.visitCommaExpr(this, context);
  1657. };
  1658. return CommaExpr;
  1659. }(Expression));
  1660. var THIS_EXPR = new ReadVarExpr(exports.BuiltinVar.This, null, null);
  1661. var SUPER_EXPR = new ReadVarExpr(exports.BuiltinVar.Super, null, null);
  1662. var CATCH_ERROR_VAR = new ReadVarExpr(exports.BuiltinVar.CatchError, null, null);
  1663. var CATCH_STACK_VAR = new ReadVarExpr(exports.BuiltinVar.CatchStack, null, null);
  1664. var NULL_EXPR = new LiteralExpr(null, null, null);
  1665. var TYPED_NULL_EXPR = new LiteralExpr(null, INFERRED_TYPE, null);
  1666. (function (StmtModifier) {
  1667. StmtModifier[StmtModifier["Final"] = 0] = "Final";
  1668. StmtModifier[StmtModifier["Private"] = 1] = "Private";
  1669. StmtModifier[StmtModifier["Exported"] = 2] = "Exported";
  1670. StmtModifier[StmtModifier["Static"] = 3] = "Static";
  1671. })(exports.StmtModifier || (exports.StmtModifier = {}));
  1672. var Statement = /** @class */ (function () {
  1673. function Statement(modifiers, sourceSpan) {
  1674. this.modifiers = modifiers || [];
  1675. this.sourceSpan = sourceSpan || null;
  1676. }
  1677. Statement.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; };
  1678. return Statement;
  1679. }());
  1680. var DeclareVarStmt = /** @class */ (function (_super) {
  1681. __extends(DeclareVarStmt, _super);
  1682. function DeclareVarStmt(name, value, type, modifiers, sourceSpan) {
  1683. if (modifiers === void 0) { modifiers = null; }
  1684. var _this = _super.call(this, modifiers, sourceSpan) || this;
  1685. _this.name = name;
  1686. _this.value = value;
  1687. _this.type = type || (value && value.type) || null;
  1688. return _this;
  1689. }
  1690. DeclareVarStmt.prototype.isEquivalent = function (stmt) {
  1691. return stmt instanceof DeclareVarStmt && this.name === stmt.name &&
  1692. (this.value ? !!stmt.value && this.value.isEquivalent(stmt.value) : !stmt.value);
  1693. };
  1694. DeclareVarStmt.prototype.visitStatement = function (visitor, context) {
  1695. return visitor.visitDeclareVarStmt(this, context);
  1696. };
  1697. return DeclareVarStmt;
  1698. }(Statement));
  1699. var DeclareFunctionStmt = /** @class */ (function (_super) {
  1700. __extends(DeclareFunctionStmt, _super);
  1701. function DeclareFunctionStmt(name, params, statements, type, modifiers, sourceSpan) {
  1702. if (modifiers === void 0) { modifiers = null; }
  1703. var _this = _super.call(this, modifiers, sourceSpan) || this;
  1704. _this.name = name;
  1705. _this.params = params;
  1706. _this.statements = statements;
  1707. _this.type = type || null;
  1708. return _this;
  1709. }
  1710. DeclareFunctionStmt.prototype.isEquivalent = function (stmt) {
  1711. return stmt instanceof DeclareFunctionStmt && areAllEquivalent(this.params, stmt.params) &&
  1712. areAllEquivalent(this.statements, stmt.statements);
  1713. };
  1714. DeclareFunctionStmt.prototype.visitStatement = function (visitor, context) {
  1715. return visitor.visitDeclareFunctionStmt(this, context);
  1716. };
  1717. return DeclareFunctionStmt;
  1718. }(Statement));
  1719. var ExpressionStatement = /** @class */ (function (_super) {
  1720. __extends(ExpressionStatement, _super);
  1721. function ExpressionStatement(expr, sourceSpan) {
  1722. var _this = _super.call(this, null, sourceSpan) || this;
  1723. _this.expr = expr;
  1724. return _this;
  1725. }
  1726. ExpressionStatement.prototype.isEquivalent = function (stmt) {
  1727. return stmt instanceof ExpressionStatement && this.expr.isEquivalent(stmt.expr);
  1728. };
  1729. ExpressionStatement.prototype.visitStatement = function (visitor, context) {
  1730. return visitor.visitExpressionStmt(this, context);
  1731. };
  1732. return ExpressionStatement;
  1733. }(Statement));
  1734. var ReturnStatement = /** @class */ (function (_super) {
  1735. __extends(ReturnStatement, _super);
  1736. function ReturnStatement(value, sourceSpan) {
  1737. var _this = _super.call(this, null, sourceSpan) || this;
  1738. _this.value = value;
  1739. return _this;
  1740. }
  1741. ReturnStatement.prototype.isEquivalent = function (stmt) {
  1742. return stmt instanceof ReturnStatement && this.value.isEquivalent(stmt.value);
  1743. };
  1744. ReturnStatement.prototype.visitStatement = function (visitor, context) {
  1745. return visitor.visitReturnStmt(this, context);
  1746. };
  1747. return ReturnStatement;
  1748. }(Statement));
  1749. var AbstractClassPart = /** @class */ (function () {
  1750. function AbstractClassPart(type, modifiers) {
  1751. this.modifiers = modifiers;
  1752. if (!modifiers) {
  1753. this.modifiers = [];
  1754. }
  1755. this.type = type || null;
  1756. }
  1757. AbstractClassPart.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; };
  1758. return AbstractClassPart;
  1759. }());
  1760. var ClassField = /** @class */ (function (_super) {
  1761. __extends(ClassField, _super);
  1762. function ClassField(name, type, modifiers, initializer) {
  1763. if (modifiers === void 0) { modifiers = null; }
  1764. var _this = _super.call(this, type, modifiers) || this;
  1765. _this.name = name;
  1766. _this.initializer = initializer;
  1767. return _this;
  1768. }
  1769. ClassField.prototype.isEquivalent = function (f) { return this.name === f.name; };
  1770. return ClassField;
  1771. }(AbstractClassPart));
  1772. var ClassMethod = /** @class */ (function (_super) {
  1773. __extends(ClassMethod, _super);
  1774. function ClassMethod(name, params, body, type, modifiers) {
  1775. if (modifiers === void 0) { modifiers = null; }
  1776. var _this = _super.call(this, type, modifiers) || this;
  1777. _this.name = name;
  1778. _this.params = params;
  1779. _this.body = body;
  1780. return _this;
  1781. }
  1782. ClassMethod.prototype.isEquivalent = function (m) {
  1783. return this.name === m.name && areAllEquivalent(this.body, m.body);
  1784. };
  1785. return ClassMethod;
  1786. }(AbstractClassPart));
  1787. var ClassGetter = /** @class */ (function (_super) {
  1788. __extends(ClassGetter, _super);
  1789. function ClassGetter(name, body, type, modifiers) {
  1790. if (modifiers === void 0) { modifiers = null; }
  1791. var _this = _super.call(this, type, modifiers) || this;
  1792. _this.name = name;
  1793. _this.body = body;
  1794. return _this;
  1795. }
  1796. ClassGetter.prototype.isEquivalent = function (m) {
  1797. return this.name === m.name && areAllEquivalent(this.body, m.body);
  1798. };
  1799. return ClassGetter;
  1800. }(AbstractClassPart));
  1801. var ClassStmt = /** @class */ (function (_super) {
  1802. __extends(ClassStmt, _super);
  1803. function ClassStmt(name, parent, fields, getters, constructorMethod, methods, modifiers, sourceSpan) {
  1804. if (modifiers === void 0) { modifiers = null; }
  1805. var _this = _super.call(this, modifiers, sourceSpan) || this;
  1806. _this.name = name;
  1807. _this.parent = parent;
  1808. _this.fields = fields;
  1809. _this.getters = getters;
  1810. _this.constructorMethod = constructorMethod;
  1811. _this.methods = methods;
  1812. return _this;
  1813. }
  1814. ClassStmt.prototype.isEquivalent = function (stmt) {
  1815. return stmt instanceof ClassStmt && this.name === stmt.name &&
  1816. nullSafeIsEquivalent(this.parent, stmt.parent) &&
  1817. areAllEquivalent(this.fields, stmt.fields) &&
  1818. areAllEquivalent(this.getters, stmt.getters) &&
  1819. this.constructorMethod.isEquivalent(stmt.constructorMethod) &&
  1820. areAllEquivalent(this.methods, stmt.methods);
  1821. };
  1822. ClassStmt.prototype.visitStatement = function (visitor, context) {
  1823. return visitor.visitDeclareClassStmt(this, context);
  1824. };
  1825. return ClassStmt;
  1826. }(Statement));
  1827. var IfStmt = /** @class */ (function (_super) {
  1828. __extends(IfStmt, _super);
  1829. function IfStmt(condition, trueCase, falseCase, sourceSpan) {
  1830. if (falseCase === void 0) { falseCase = []; }
  1831. var _this = _super.call(this, null, sourceSpan) || this;
  1832. _this.condition = condition;
  1833. _this.trueCase = trueCase;
  1834. _this.falseCase = falseCase;
  1835. return _this;
  1836. }
  1837. IfStmt.prototype.isEquivalent = function (stmt) {
  1838. return stmt instanceof IfStmt && this.condition.isEquivalent(stmt.condition) &&
  1839. areAllEquivalent(this.trueCase, stmt.trueCase) &&
  1840. areAllEquivalent(this.falseCase, stmt.falseCase);
  1841. };
  1842. IfStmt.prototype.visitStatement = function (visitor, context) {
  1843. return visitor.visitIfStmt(this, context);
  1844. };
  1845. return IfStmt;
  1846. }(Statement));
  1847. var CommentStmt = /** @class */ (function (_super) {
  1848. __extends(CommentStmt, _super);
  1849. function CommentStmt(comment, multiline, sourceSpan) {
  1850. if (multiline === void 0) { multiline = false; }
  1851. var _this = _super.call(this, null, sourceSpan) || this;
  1852. _this.comment = comment;
  1853. _this.multiline = multiline;
  1854. return _this;
  1855. }
  1856. CommentStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof CommentStmt; };
  1857. CommentStmt.prototype.visitStatement = function (visitor, context) {
  1858. return visitor.visitCommentStmt(this, context);
  1859. };
  1860. return CommentStmt;
  1861. }(Statement));
  1862. var JSDocCommentStmt = /** @class */ (function (_super) {
  1863. __extends(JSDocCommentStmt, _super);
  1864. function JSDocCommentStmt(tags, sourceSpan) {
  1865. if (tags === void 0) { tags = []; }
  1866. var _this = _super.call(this, null, sourceSpan) || this;
  1867. _this.tags = tags;
  1868. return _this;
  1869. }
  1870. JSDocCommentStmt.prototype.isEquivalent = function (stmt) {
  1871. return stmt instanceof JSDocCommentStmt && this.toString() === stmt.toString();
  1872. };
  1873. JSDocCommentStmt.prototype.visitStatement = function (visitor, context) {
  1874. return visitor.visitJSDocCommentStmt(this, context);
  1875. };
  1876. JSDocCommentStmt.prototype.toString = function () { return serializeTags(this.tags); };
  1877. return JSDocCommentStmt;
  1878. }(Statement));
  1879. var TryCatchStmt = /** @class */ (function (_super) {
  1880. __extends(TryCatchStmt, _super);
  1881. function TryCatchStmt(bodyStmts, catchStmts, sourceSpan) {
  1882. var _this = _super.call(this, null, sourceSpan) || this;
  1883. _this.bodyStmts = bodyStmts;
  1884. _this.catchStmts = catchStmts;
  1885. return _this;
  1886. }
  1887. TryCatchStmt.prototype.isEquivalent = function (stmt) {
  1888. return stmt instanceof TryCatchStmt && areAllEquivalent(this.bodyStmts, stmt.bodyStmts) &&
  1889. areAllEquivalent(this.catchStmts, stmt.catchStmts);
  1890. };
  1891. TryCatchStmt.prototype.visitStatement = function (visitor, context) {
  1892. return visitor.visitTryCatchStmt(this, context);
  1893. };
  1894. return TryCatchStmt;
  1895. }(Statement));
  1896. var ThrowStmt = /** @class */ (function (_super) {
  1897. __extends(ThrowStmt, _super);
  1898. function ThrowStmt(error, sourceSpan) {
  1899. var _this = _super.call(this, null, sourceSpan) || this;
  1900. _this.error = error;
  1901. return _this;
  1902. }
  1903. ThrowStmt.prototype.isEquivalent = function (stmt) {
  1904. return stmt instanceof TryCatchStmt && this.error.isEquivalent(stmt.error);
  1905. };
  1906. ThrowStmt.prototype.visitStatement = function (visitor, context) {
  1907. return visitor.visitThrowStmt(this, context);
  1908. };
  1909. return ThrowStmt;
  1910. }(Statement));
  1911. var AstTransformer = /** @class */ (function () {
  1912. function AstTransformer() {
  1913. }
  1914. AstTransformer.prototype.transformExpr = function (expr, context) { return expr; };
  1915. AstTransformer.prototype.transformStmt = function (stmt, context) { return stmt; };
  1916. AstTransformer.prototype.visitReadVarExpr = function (ast, context) { return this.transformExpr(ast, context); };
  1917. AstTransformer.prototype.visitWrappedNodeExpr = function (ast, context) {
  1918. return this.transformExpr(ast, context);
  1919. };
  1920. AstTransformer.prototype.visitTypeofExpr = function (expr, context) {
  1921. return this.transformExpr(new TypeofExpr(expr.expr.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  1922. };
  1923. AstTransformer.prototype.visitWriteVarExpr = function (expr, context) {
  1924. return this.transformExpr(new WriteVarExpr(expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  1925. };
  1926. AstTransformer.prototype.visitWriteKeyExpr = function (expr, context) {
  1927. 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);
  1928. };
  1929. AstTransformer.prototype.visitWritePropExpr = function (expr, context) {
  1930. return this.transformExpr(new WritePropExpr(expr.receiver.visitExpression(this, context), expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  1931. };
  1932. AstTransformer.prototype.visitInvokeMethodExpr = function (ast, context) {
  1933. var method = ast.builtin || ast.name;
  1934. return this.transformExpr(new InvokeMethodExpr(ast.receiver.visitExpression(this, context), method, this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
  1935. };
  1936. AstTransformer.prototype.visitInvokeFunctionExpr = function (ast, context) {
  1937. return this.transformExpr(new InvokeFunctionExpr(ast.fn.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
  1938. };
  1939. AstTransformer.prototype.visitInstantiateExpr = function (ast, context) {
  1940. return this.transformExpr(new InstantiateExpr(ast.classExpr.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
  1941. };
  1942. AstTransformer.prototype.visitLiteralExpr = function (ast, context) { return this.transformExpr(ast, context); };
  1943. AstTransformer.prototype.visitExternalExpr = function (ast, context) {
  1944. return this.transformExpr(ast, context);
  1945. };
  1946. AstTransformer.prototype.visitConditionalExpr = function (ast, context) {
  1947. 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);
  1948. };
  1949. AstTransformer.prototype.visitNotExpr = function (ast, context) {
  1950. return this.transformExpr(new NotExpr(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
  1951. };
  1952. AstTransformer.prototype.visitAssertNotNullExpr = function (ast, context) {
  1953. return this.transformExpr(new AssertNotNull(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
  1954. };
  1955. AstTransformer.prototype.visitCastExpr = function (ast, context) {
  1956. return this.transformExpr(new CastExpr(ast.value.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  1957. };
  1958. AstTransformer.prototype.visitFunctionExpr = function (ast, context) {
  1959. return this.transformExpr(new FunctionExpr(ast.params, this.visitAllStatements(ast.statements, context), ast.type, ast.sourceSpan), context);
  1960. };
  1961. AstTransformer.prototype.visitBinaryOperatorExpr = function (ast, context) {
  1962. return this.transformExpr(new BinaryOperatorExpr(ast.operator, ast.lhs.visitExpression(this, context), ast.rhs.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  1963. };
  1964. AstTransformer.prototype.visitReadPropExpr = function (ast, context) {
  1965. return this.transformExpr(new ReadPropExpr(ast.receiver.visitExpression(this, context), ast.name, ast.type, ast.sourceSpan), context);
  1966. };
  1967. AstTransformer.prototype.visitReadKeyExpr = function (ast, context) {
  1968. return this.transformExpr(new ReadKeyExpr(ast.receiver.visitExpression(this, context), ast.index.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  1969. };
  1970. AstTransformer.prototype.visitLiteralArrayExpr = function (ast, context) {
  1971. return this.transformExpr(new LiteralArrayExpr(this.visitAllExpressions(ast.entries, context), ast.type, ast.sourceSpan), context);
  1972. };
  1973. AstTransformer.prototype.visitLiteralMapExpr = function (ast, context) {
  1974. var _this = this;
  1975. var entries = ast.entries.map(function (entry) { return new LiteralMapEntry(entry.key, entry.value.visitExpression(_this, context), entry.quoted); });
  1976. var mapType = new MapType(ast.valueType, null);
  1977. return this.transformExpr(new LiteralMapExpr(entries, mapType, ast.sourceSpan), context);
  1978. };
  1979. AstTransformer.prototype.visitCommaExpr = function (ast, context) {
  1980. return this.transformExpr(new CommaExpr(this.visitAllExpressions(ast.parts, context), ast.sourceSpan), context);
  1981. };
  1982. AstTransformer.prototype.visitAllExpressions = function (exprs, context) {
  1983. var _this = this;
  1984. return exprs.map(function (expr) { return expr.visitExpression(_this, context); });
  1985. };
  1986. AstTransformer.prototype.visitDeclareVarStmt = function (stmt, context) {
  1987. var value = stmt.value && stmt.value.visitExpression(this, context);
  1988. return this.transformStmt(new DeclareVarStmt(stmt.name, value, stmt.type, stmt.modifiers, stmt.sourceSpan), context);
  1989. };
  1990. AstTransformer.prototype.visitDeclareFunctionStmt = function (stmt, context) {
  1991. return this.transformStmt(new DeclareFunctionStmt(stmt.name, stmt.params, this.visitAllStatements(stmt.statements, context), stmt.type, stmt.modifiers, stmt.sourceSpan), context);
  1992. };
  1993. AstTransformer.prototype.visitExpressionStmt = function (stmt, context) {
  1994. return this.transformStmt(new ExpressionStatement(stmt.expr.visitExpression(this, context), stmt.sourceSpan), context);
  1995. };
  1996. AstTransformer.prototype.visitReturnStmt = function (stmt, context) {
  1997. return this.transformStmt(new ReturnStatement(stmt.value.visitExpression(this, context), stmt.sourceSpan), context);
  1998. };
  1999. AstTransformer.prototype.visitDeclareClassStmt = function (stmt, context) {
  2000. var _this = this;
  2001. var parent = stmt.parent.visitExpression(this, context);
  2002. var getters = stmt.getters.map(function (getter) { return new ClassGetter(getter.name, _this.visitAllStatements(getter.body, context), getter.type, getter.modifiers); });
  2003. var ctorMethod = stmt.constructorMethod &&
  2004. new ClassMethod(stmt.constructorMethod.name, stmt.constructorMethod.params, this.visitAllStatements(stmt.constructorMethod.body, context), stmt.constructorMethod.type, stmt.constructorMethod.modifiers);
  2005. var methods = stmt.methods.map(function (method) { return new ClassMethod(method.name, method.params, _this.visitAllStatements(method.body, context), method.type, method.modifiers); });
  2006. return this.transformStmt(new ClassStmt(stmt.name, parent, stmt.fields, getters, ctorMethod, methods, stmt.modifiers, stmt.sourceSpan), context);
  2007. };
  2008. AstTransformer.prototype.visitIfStmt = function (stmt, context) {
  2009. return this.transformStmt(new IfStmt(stmt.condition.visitExpression(this, context), this.visitAllStatements(stmt.trueCase, context), this.visitAllStatements(stmt.falseCase, context), stmt.sourceSpan), context);
  2010. };
  2011. AstTransformer.prototype.visitTryCatchStmt = function (stmt, context) {
  2012. return this.transformStmt(new TryCatchStmt(this.visitAllStatements(stmt.bodyStmts, context), this.visitAllStatements(stmt.catchStmts, context), stmt.sourceSpan), context);
  2013. };
  2014. AstTransformer.prototype.visitThrowStmt = function (stmt, context) {
  2015. return this.transformStmt(new ThrowStmt(stmt.error.visitExpression(this, context), stmt.sourceSpan), context);
  2016. };
  2017. AstTransformer.prototype.visitCommentStmt = function (stmt, context) {
  2018. return this.transformStmt(stmt, context);
  2019. };
  2020. AstTransformer.prototype.visitJSDocCommentStmt = function (stmt, context) {
  2021. return this.transformStmt(stmt, context);
  2022. };
  2023. AstTransformer.prototype.visitAllStatements = function (stmts, context) {
  2024. var _this = this;
  2025. return stmts.map(function (stmt) { return stmt.visitStatement(_this, context); });
  2026. };
  2027. return AstTransformer;
  2028. }());
  2029. var RecursiveAstVisitor = /** @class */ (function () {
  2030. function RecursiveAstVisitor() {
  2031. }
  2032. RecursiveAstVisitor.prototype.visitType = function (ast, context) { return ast; };
  2033. RecursiveAstVisitor.prototype.visitExpression = function (ast, context) {
  2034. if (ast.type) {
  2035. ast.type.visitType(this, context);
  2036. }
  2037. return ast;
  2038. };
  2039. RecursiveAstVisitor.prototype.visitBuiltinType = function (type, context) { return this.visitType(type, context); };
  2040. RecursiveAstVisitor.prototype.visitExpressionType = function (type, context) {
  2041. var _this = this;
  2042. type.value.visitExpression(this, context);
  2043. if (type.typeParams !== null) {
  2044. type.typeParams.forEach(function (param) { return _this.visitType(param, context); });
  2045. }
  2046. return this.visitType(type, context);
  2047. };
  2048. RecursiveAstVisitor.prototype.visitArrayType = function (type, context) { return this.visitType(type, context); };
  2049. RecursiveAstVisitor.prototype.visitMapType = function (type, context) { return this.visitType(type, context); };
  2050. RecursiveAstVisitor.prototype.visitWrappedNodeExpr = function (ast, context) { return ast; };
  2051. RecursiveAstVisitor.prototype.visitTypeofExpr = function (ast, context) { return this.visitExpression(ast, context); };
  2052. RecursiveAstVisitor.prototype.visitReadVarExpr = function (ast, context) {
  2053. return this.visitExpression(ast, context);
  2054. };
  2055. RecursiveAstVisitor.prototype.visitWriteVarExpr = function (ast, context) {
  2056. ast.value.visitExpression(this, context);
  2057. return this.visitExpression(ast, context);
  2058. };
  2059. RecursiveAstVisitor.prototype.visitWriteKeyExpr = function (ast, context) {
  2060. ast.receiver.visitExpression(this, context);
  2061. ast.index.visitExpression(this, context);
  2062. ast.value.visitExpression(this, context);
  2063. return this.visitExpression(ast, context);
  2064. };
  2065. RecursiveAstVisitor.prototype.visitWritePropExpr = function (ast, context) {
  2066. ast.receiver.visitExpression(this, context);
  2067. ast.value.visitExpression(this, context);
  2068. return this.visitExpression(ast, context);
  2069. };
  2070. RecursiveAstVisitor.prototype.visitInvokeMethodExpr = function (ast, context) {
  2071. ast.receiver.visitExpression(this, context);
  2072. this.visitAllExpressions(ast.args, context);
  2073. return this.visitExpression(ast, context);
  2074. };
  2075. RecursiveAstVisitor.prototype.visitInvokeFunctionExpr = function (ast, context) {
  2076. ast.fn.visitExpression(this, context);
  2077. this.visitAllExpressions(ast.args, context);
  2078. return this.visitExpression(ast, context);
  2079. };
  2080. RecursiveAstVisitor.prototype.visitInstantiateExpr = function (ast, context) {
  2081. ast.classExpr.visitExpression(this, context);
  2082. this.visitAllExpressions(ast.args, context);
  2083. return this.visitExpression(ast, context);
  2084. };
  2085. RecursiveAstVisitor.prototype.visitLiteralExpr = function (ast, context) {
  2086. return this.visitExpression(ast, context);
  2087. };
  2088. RecursiveAstVisitor.prototype.visitExternalExpr = function (ast, context) {
  2089. var _this = this;
  2090. if (ast.typeParams) {
  2091. ast.typeParams.forEach(function (type) { return type.visitType(_this, context); });
  2092. }
  2093. return this.visitExpression(ast, context);
  2094. };
  2095. RecursiveAstVisitor.prototype.visitConditionalExpr = function (ast, context) {
  2096. ast.condition.visitExpression(this, context);
  2097. ast.trueCase.visitExpression(this, context);
  2098. ast.falseCase.visitExpression(this, context);
  2099. return this.visitExpression(ast, context);
  2100. };
  2101. RecursiveAstVisitor.prototype.visitNotExpr = function (ast, context) {
  2102. ast.condition.visitExpression(this, context);
  2103. return this.visitExpression(ast, context);
  2104. };
  2105. RecursiveAstVisitor.prototype.visitAssertNotNullExpr = function (ast, context) {
  2106. ast.condition.visitExpression(this, context);
  2107. return this.visitExpression(ast, context);
  2108. };
  2109. RecursiveAstVisitor.prototype.visitCastExpr = function (ast, context) {
  2110. ast.value.visitExpression(this, context);
  2111. return this.visitExpression(ast, context);
  2112. };
  2113. RecursiveAstVisitor.prototype.visitFunctionExpr = function (ast, context) {
  2114. this.visitAllStatements(ast.statements, context);
  2115. return this.visitExpression(ast, context);
  2116. };
  2117. RecursiveAstVisitor.prototype.visitBinaryOperatorExpr = function (ast, context) {
  2118. ast.lhs.visitExpression(this, context);
  2119. ast.rhs.visitExpression(this, context);
  2120. return this.visitExpression(ast, context);
  2121. };
  2122. RecursiveAstVisitor.prototype.visitReadPropExpr = function (ast, context) {
  2123. ast.receiver.visitExpression(this, context);
  2124. return this.visitExpression(ast, context);
  2125. };
  2126. RecursiveAstVisitor.prototype.visitReadKeyExpr = function (ast, context) {
  2127. ast.receiver.visitExpression(this, context);
  2128. ast.index.visitExpression(this, context);
  2129. return this.visitExpression(ast, context);
  2130. };
  2131. RecursiveAstVisitor.prototype.visitLiteralArrayExpr = function (ast, context) {
  2132. this.visitAllExpressions(ast.entries, context);
  2133. return this.visitExpression(ast, context);
  2134. };
  2135. RecursiveAstVisitor.prototype.visitLiteralMapExpr = function (ast, context) {
  2136. var _this = this;
  2137. ast.entries.forEach(function (entry) { return entry.value.visitExpression(_this, context); });
  2138. return this.visitExpression(ast, context);
  2139. };
  2140. RecursiveAstVisitor.prototype.visitCommaExpr = function (ast, context) {
  2141. this.visitAllExpressions(ast.parts, context);
  2142. return this.visitExpression(ast, context);
  2143. };
  2144. RecursiveAstVisitor.prototype.visitAllExpressions = function (exprs, context) {
  2145. var _this = this;
  2146. exprs.forEach(function (expr) { return expr.visitExpression(_this, context); });
  2147. };
  2148. RecursiveAstVisitor.prototype.visitDeclareVarStmt = function (stmt, context) {
  2149. if (stmt.value) {
  2150. stmt.value.visitExpression(this, context);
  2151. }
  2152. if (stmt.type) {
  2153. stmt.type.visitType(this, context);
  2154. }
  2155. return stmt;
  2156. };
  2157. RecursiveAstVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) {
  2158. this.visitAllStatements(stmt.statements, context);
  2159. if (stmt.type) {
  2160. stmt.type.visitType(this, context);
  2161. }
  2162. return stmt;
  2163. };
  2164. RecursiveAstVisitor.prototype.visitExpressionStmt = function (stmt, context) {
  2165. stmt.expr.visitExpression(this, context);
  2166. return stmt;
  2167. };
  2168. RecursiveAstVisitor.prototype.visitReturnStmt = function (stmt, context) {
  2169. stmt.value.visitExpression(this, context);
  2170. return stmt;
  2171. };
  2172. RecursiveAstVisitor.prototype.visitDeclareClassStmt = function (stmt, context) {
  2173. var _this = this;
  2174. stmt.parent.visitExpression(this, context);
  2175. stmt.getters.forEach(function (getter) { return _this.visitAllStatements(getter.body, context); });
  2176. if (stmt.constructorMethod) {
  2177. this.visitAllStatements(stmt.constructorMethod.body, context);
  2178. }
  2179. stmt.methods.forEach(function (method) { return _this.visitAllStatements(method.body, context); });
  2180. return stmt;
  2181. };
  2182. RecursiveAstVisitor.prototype.visitIfStmt = function (stmt, context) {
  2183. stmt.condition.visitExpression(this, context);
  2184. this.visitAllStatements(stmt.trueCase, context);
  2185. this.visitAllStatements(stmt.falseCase, context);
  2186. return stmt;
  2187. };
  2188. RecursiveAstVisitor.prototype.visitTryCatchStmt = function (stmt, context) {
  2189. this.visitAllStatements(stmt.bodyStmts, context);
  2190. this.visitAllStatements(stmt.catchStmts, context);
  2191. return stmt;
  2192. };
  2193. RecursiveAstVisitor.prototype.visitThrowStmt = function (stmt, context) {
  2194. stmt.error.visitExpression(this, context);
  2195. return stmt;
  2196. };
  2197. RecursiveAstVisitor.prototype.visitCommentStmt = function (stmt, context) { return stmt; };
  2198. RecursiveAstVisitor.prototype.visitJSDocCommentStmt = function (stmt, context) { return stmt; };
  2199. RecursiveAstVisitor.prototype.visitAllStatements = function (stmts, context) {
  2200. var _this = this;
  2201. stmts.forEach(function (stmt) { return stmt.visitStatement(_this, context); });
  2202. };
  2203. return RecursiveAstVisitor;
  2204. }());
  2205. function findReadVarNames(stmts) {
  2206. var visitor = new _ReadVarVisitor();
  2207. visitor.visitAllStatements(stmts, null);
  2208. return visitor.varNames;
  2209. }
  2210. var _ReadVarVisitor = /** @class */ (function (_super) {
  2211. __extends(_ReadVarVisitor, _super);
  2212. function _ReadVarVisitor() {
  2213. var _this = _super !== null && _super.apply(this, arguments) || this;
  2214. _this.varNames = new Set();
  2215. return _this;
  2216. }
  2217. _ReadVarVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) {
  2218. // Don't descend into nested functions
  2219. return stmt;
  2220. };
  2221. _ReadVarVisitor.prototype.visitDeclareClassStmt = function (stmt, context) {
  2222. // Don't descend into nested classes
  2223. return stmt;
  2224. };
  2225. _ReadVarVisitor.prototype.visitReadVarExpr = function (ast, context) {
  2226. if (ast.name) {
  2227. this.varNames.add(ast.name);
  2228. }
  2229. return null;
  2230. };
  2231. return _ReadVarVisitor;
  2232. }(RecursiveAstVisitor));
  2233. function collectExternalReferences(stmts) {
  2234. var visitor = new _FindExternalReferencesVisitor();
  2235. visitor.visitAllStatements(stmts, null);
  2236. return visitor.externalReferences;
  2237. }
  2238. var _FindExternalReferencesVisitor = /** @class */ (function (_super) {
  2239. __extends(_FindExternalReferencesVisitor, _super);
  2240. function _FindExternalReferencesVisitor() {
  2241. var _this = _super !== null && _super.apply(this, arguments) || this;
  2242. _this.externalReferences = [];
  2243. return _this;
  2244. }
  2245. _FindExternalReferencesVisitor.prototype.visitExternalExpr = function (e, context) {
  2246. this.externalReferences.push(e.value);
  2247. return _super.prototype.visitExternalExpr.call(this, e, context);
  2248. };
  2249. return _FindExternalReferencesVisitor;
  2250. }(RecursiveAstVisitor));
  2251. function applySourceSpanToStatementIfNeeded(stmt, sourceSpan) {
  2252. if (!sourceSpan) {
  2253. return stmt;
  2254. }
  2255. var transformer = new _ApplySourceSpanTransformer(sourceSpan);
  2256. return stmt.visitStatement(transformer, null);
  2257. }
  2258. function applySourceSpanToExpressionIfNeeded(expr, sourceSpan) {
  2259. if (!sourceSpan) {
  2260. return expr;
  2261. }
  2262. var transformer = new _ApplySourceSpanTransformer(sourceSpan);
  2263. return expr.visitExpression(transformer, null);
  2264. }
  2265. var _ApplySourceSpanTransformer = /** @class */ (function (_super) {
  2266. __extends(_ApplySourceSpanTransformer, _super);
  2267. function _ApplySourceSpanTransformer(sourceSpan) {
  2268. var _this = _super.call(this) || this;
  2269. _this.sourceSpan = sourceSpan;
  2270. return _this;
  2271. }
  2272. _ApplySourceSpanTransformer.prototype._clone = function (obj) {
  2273. var clone = Object.create(obj.constructor.prototype);
  2274. for (var prop in obj) {
  2275. clone[prop] = obj[prop];
  2276. }
  2277. return clone;
  2278. };
  2279. _ApplySourceSpanTransformer.prototype.transformExpr = function (expr, context) {
  2280. if (!expr.sourceSpan) {
  2281. expr = this._clone(expr);
  2282. expr.sourceSpan = this.sourceSpan;
  2283. }
  2284. return expr;
  2285. };
  2286. _ApplySourceSpanTransformer.prototype.transformStmt = function (stmt, context) {
  2287. if (!stmt.sourceSpan) {
  2288. stmt = this._clone(stmt);
  2289. stmt.sourceSpan = this.sourceSpan;
  2290. }
  2291. return stmt;
  2292. };
  2293. return _ApplySourceSpanTransformer;
  2294. }(AstTransformer));
  2295. function variable(name, type, sourceSpan) {
  2296. return new ReadVarExpr(name, type, sourceSpan);
  2297. }
  2298. function importExpr(id, typeParams, sourceSpan) {
  2299. if (typeParams === void 0) { typeParams = null; }
  2300. return new ExternalExpr(id, null, typeParams, sourceSpan);
  2301. }
  2302. function importType(id, typeParams, typeModifiers) {
  2303. if (typeParams === void 0) { typeParams = null; }
  2304. if (typeModifiers === void 0) { typeModifiers = null; }
  2305. return id != null ? expressionType(importExpr(id, typeParams, null), typeModifiers) : null;
  2306. }
  2307. function expressionType(expr, typeModifiers, typeParams) {
  2308. if (typeModifiers === void 0) { typeModifiers = null; }
  2309. if (typeParams === void 0) { typeParams = null; }
  2310. return new ExpressionType(expr, typeModifiers, typeParams);
  2311. }
  2312. function typeofExpr(expr) {
  2313. return new TypeofExpr(expr);
  2314. }
  2315. function literalArr(values, type, sourceSpan) {
  2316. return new LiteralArrayExpr(values, type, sourceSpan);
  2317. }
  2318. function literalMap(values, type) {
  2319. if (type === void 0) { type = null; }
  2320. return new LiteralMapExpr(values.map(function (e) { return new LiteralMapEntry(e.key, e.value, e.quoted); }), type, null);
  2321. }
  2322. function not(expr, sourceSpan) {
  2323. return new NotExpr(expr, sourceSpan);
  2324. }
  2325. function assertNotNull(expr, sourceSpan) {
  2326. return new AssertNotNull(expr, sourceSpan);
  2327. }
  2328. function fn(params, body, type, sourceSpan, name) {
  2329. return new FunctionExpr(params, body, type, sourceSpan, name);
  2330. }
  2331. function ifStmt(condition, thenClause, elseClause) {
  2332. return new IfStmt(condition, thenClause, elseClause);
  2333. }
  2334. function literal(value, type, sourceSpan) {
  2335. return new LiteralExpr(value, type, sourceSpan);
  2336. }
  2337. function isNull(exp) {
  2338. return exp instanceof LiteralExpr && exp.value === null;
  2339. }
  2340. /*
  2341. * Serializes a `Tag` into a string.
  2342. * Returns a string like " @foo {bar} baz" (note the leading whitespace before `@foo`).
  2343. */
  2344. function tagToString(tag) {
  2345. var out = '';
  2346. if (tag.tagName) {
  2347. out += " @" + tag.tagName;
  2348. }
  2349. if (tag.text) {
  2350. if (tag.text.match(/\/\*|\*\//)) {
  2351. throw new Error('JSDoc text cannot contain "/*" and "*/"');
  2352. }
  2353. out += ' ' + tag.text.replace(/@/g, '\\@');
  2354. }
  2355. return out;
  2356. }
  2357. function serializeTags(tags) {
  2358. var e_1, _a;
  2359. if (tags.length === 0)
  2360. return '';
  2361. var out = '*\n';
  2362. try {
  2363. for (var tags_1 = __values(tags), tags_1_1 = tags_1.next(); !tags_1_1.done; tags_1_1 = tags_1.next()) {
  2364. var tag = tags_1_1.value;
  2365. out += ' *';
  2366. // If the tagToString is multi-line, insert " * " prefixes on subsequent lines.
  2367. out += tagToString(tag).replace(/\n/g, '\n * ');
  2368. out += '\n';
  2369. }
  2370. }
  2371. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  2372. finally {
  2373. try {
  2374. if (tags_1_1 && !tags_1_1.done && (_a = tags_1.return)) _a.call(tags_1);
  2375. }
  2376. finally { if (e_1) throw e_1.error; }
  2377. }
  2378. out += ' ';
  2379. return out;
  2380. }
  2381. /**
  2382. * @license
  2383. * Copyright Google Inc. All Rights Reserved.
  2384. *
  2385. * Use of this source code is governed by an MIT-style license that can be
  2386. * found in the LICENSE file at https://angular.io/license
  2387. */
  2388. var DASH_CASE_REGEXP = /-+([a-z0-9])/g;
  2389. function dashCaseToCamelCase(input) {
  2390. return input.replace(DASH_CASE_REGEXP, function () {
  2391. var m = [];
  2392. for (var _i = 0; _i < arguments.length; _i++) {
  2393. m[_i] = arguments[_i];
  2394. }
  2395. return m[1].toUpperCase();
  2396. });
  2397. }
  2398. function splitAtColon(input, defaultValues) {
  2399. return _splitAt(input, ':', defaultValues);
  2400. }
  2401. function splitAtPeriod(input, defaultValues) {
  2402. return _splitAt(input, '.', defaultValues);
  2403. }
  2404. function _splitAt(input, character, defaultValues) {
  2405. var characterIndex = input.indexOf(character);
  2406. if (characterIndex == -1)
  2407. return defaultValues;
  2408. return [input.slice(0, characterIndex).trim(), input.slice(characterIndex + 1).trim()];
  2409. }
  2410. function visitValue(value, visitor, context) {
  2411. if (Array.isArray(value)) {
  2412. return visitor.visitArray(value, context);
  2413. }
  2414. if (isStrictStringMap(value)) {
  2415. return visitor.visitStringMap(value, context);
  2416. }
  2417. if (value == null || typeof value == 'string' || typeof value == 'number' ||
  2418. typeof value == 'boolean') {
  2419. return visitor.visitPrimitive(value, context);
  2420. }
  2421. return visitor.visitOther(value, context);
  2422. }
  2423. function isDefined(val) {
  2424. return val !== null && val !== undefined;
  2425. }
  2426. function noUndefined(val) {
  2427. return val === undefined ? null : val;
  2428. }
  2429. var ValueTransformer = /** @class */ (function () {
  2430. function ValueTransformer() {
  2431. }
  2432. ValueTransformer.prototype.visitArray = function (arr, context) {
  2433. var _this = this;
  2434. return arr.map(function (value) { return visitValue(value, _this, context); });
  2435. };
  2436. ValueTransformer.prototype.visitStringMap = function (map, context) {
  2437. var _this = this;
  2438. var result = {};
  2439. Object.keys(map).forEach(function (key) { result[key] = visitValue(map[key], _this, context); });
  2440. return result;
  2441. };
  2442. ValueTransformer.prototype.visitPrimitive = function (value, context) { return value; };
  2443. ValueTransformer.prototype.visitOther = function (value, context) { return value; };
  2444. return ValueTransformer;
  2445. }());
  2446. var SyncAsync = {
  2447. assertSync: function (value) {
  2448. if (isPromise(value)) {
  2449. throw new Error("Illegal state: value cannot be a promise");
  2450. }
  2451. return value;
  2452. },
  2453. then: function (value, cb) { return isPromise(value) ? value.then(cb) : cb(value); },
  2454. all: function (syncAsyncValues) {
  2455. return syncAsyncValues.some(isPromise) ? Promise.all(syncAsyncValues) : syncAsyncValues;
  2456. }
  2457. };
  2458. function error(msg) {
  2459. throw new Error("Internal Error: " + msg);
  2460. }
  2461. function syntaxError(msg, parseErrors) {
  2462. var error = Error(msg);
  2463. error[ERROR_SYNTAX_ERROR] = true;
  2464. if (parseErrors)
  2465. error[ERROR_PARSE_ERRORS] = parseErrors;
  2466. return error;
  2467. }
  2468. var ERROR_SYNTAX_ERROR = 'ngSyntaxError';
  2469. var ERROR_PARSE_ERRORS = 'ngParseErrors';
  2470. function isSyntaxError(error) {
  2471. return error[ERROR_SYNTAX_ERROR];
  2472. }
  2473. function getParseErrors(error) {
  2474. return error[ERROR_PARSE_ERRORS] || [];
  2475. }
  2476. // Escape characters that have a special meaning in Regular Expressions
  2477. function escapeRegExp(s) {
  2478. return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  2479. }
  2480. var STRING_MAP_PROTO = Object.getPrototypeOf({});
  2481. function isStrictStringMap(obj) {
  2482. return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === STRING_MAP_PROTO;
  2483. }
  2484. function utf8Encode(str) {
  2485. var encoded = '';
  2486. for (var index = 0; index < str.length; index++) {
  2487. var codePoint = str.charCodeAt(index);
  2488. // decode surrogate
  2489. // see https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  2490. if (codePoint >= 0xd800 && codePoint <= 0xdbff && str.length > (index + 1)) {
  2491. var low = str.charCodeAt(index + 1);
  2492. if (low >= 0xdc00 && low <= 0xdfff) {
  2493. index++;
  2494. codePoint = ((codePoint - 0xd800) << 10) + low - 0xdc00 + 0x10000;
  2495. }
  2496. }
  2497. if (codePoint <= 0x7f) {
  2498. encoded += String.fromCharCode(codePoint);
  2499. }
  2500. else if (codePoint <= 0x7ff) {
  2501. encoded += String.fromCharCode(((codePoint >> 6) & 0x1F) | 0xc0, (codePoint & 0x3f) | 0x80);
  2502. }
  2503. else if (codePoint <= 0xffff) {
  2504. encoded += String.fromCharCode((codePoint >> 12) | 0xe0, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80);
  2505. }
  2506. else if (codePoint <= 0x1fffff) {
  2507. encoded += String.fromCharCode(((codePoint >> 18) & 0x07) | 0xf0, ((codePoint >> 12) & 0x3f) | 0x80, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80);
  2508. }
  2509. }
  2510. return encoded;
  2511. }
  2512. function stringify(token) {
  2513. if (typeof token === 'string') {
  2514. return token;
  2515. }
  2516. if (token instanceof Array) {
  2517. return '[' + token.map(stringify).join(', ') + ']';
  2518. }
  2519. if (token == null) {
  2520. return '' + token;
  2521. }
  2522. if (token.overriddenName) {
  2523. return "" + token.overriddenName;
  2524. }
  2525. if (token.name) {
  2526. return "" + token.name;
  2527. }
  2528. if (!token.toString) {
  2529. return 'object';
  2530. }
  2531. // WARNING: do not try to `JSON.stringify(token)` here
  2532. // see https://github.com/angular/angular/issues/23440
  2533. var res = token.toString();
  2534. if (res == null) {
  2535. return '' + res;
  2536. }
  2537. var newLineIndex = res.indexOf('\n');
  2538. return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
  2539. }
  2540. /**
  2541. * Lazily retrieves the reference value from a forwardRef.
  2542. */
  2543. function resolveForwardRef(type) {
  2544. if (typeof type === 'function' && type.hasOwnProperty('__forward_ref__')) {
  2545. return type();
  2546. }
  2547. else {
  2548. return type;
  2549. }
  2550. }
  2551. /**
  2552. * Determine if the argument is shaped like a Promise
  2553. */
  2554. function isPromise(obj) {
  2555. // allow any Promise/A+ compliant thenable.
  2556. // It's up to the caller to ensure that obj.then conforms to the spec
  2557. return !!obj && typeof obj.then === 'function';
  2558. }
  2559. var Version = /** @class */ (function () {
  2560. function Version(full) {
  2561. this.full = full;
  2562. var splits = full.split('.');
  2563. this.major = splits[0];
  2564. this.minor = splits[1];
  2565. this.patch = splits.slice(2).join('.');
  2566. }
  2567. return Version;
  2568. }());
  2569. var __window = typeof window !== 'undefined' && window;
  2570. var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
  2571. self instanceof WorkerGlobalScope && self;
  2572. var __global = typeof global !== 'undefined' && global;
  2573. // Check __global first, because in Node tests both __global and __window may be defined and _global
  2574. // should be __global in that case.
  2575. var _global = __global || __window || __self;
  2576. /**
  2577. * @license
  2578. * Copyright Google Inc. All Rights Reserved.
  2579. *
  2580. * Use of this source code is governed by an MIT-style license that can be
  2581. * found in the LICENSE file at https://angular.io/license
  2582. */
  2583. var CONSTANT_PREFIX = '_c';
  2584. /**
  2585. * Context to use when producing a key.
  2586. *
  2587. * This ensures we see the constant not the reference variable when producing
  2588. * a key.
  2589. */
  2590. var KEY_CONTEXT = {};
  2591. /**
  2592. * A node that is a place-holder that allows the node to be replaced when the actual
  2593. * node is known.
  2594. *
  2595. * This allows the constant pool to change an expression from a direct reference to
  2596. * a constant to a shared constant. It returns a fix-up node that is later allowed to
  2597. * change the referenced expression.
  2598. */
  2599. var FixupExpression = /** @class */ (function (_super) {
  2600. __extends(FixupExpression, _super);
  2601. function FixupExpression(resolved) {
  2602. var _this = _super.call(this, resolved.type) || this;
  2603. _this.resolved = resolved;
  2604. _this.original = resolved;
  2605. return _this;
  2606. }
  2607. FixupExpression.prototype.visitExpression = function (visitor, context) {
  2608. if (context === KEY_CONTEXT) {
  2609. // When producing a key we want to traverse the constant not the
  2610. // variable used to refer to it.
  2611. return this.original.visitExpression(visitor, context);
  2612. }
  2613. else {
  2614. return this.resolved.visitExpression(visitor, context);
  2615. }
  2616. };
  2617. FixupExpression.prototype.isEquivalent = function (e) {
  2618. return e instanceof FixupExpression && this.resolved.isEquivalent(e.resolved);
  2619. };
  2620. FixupExpression.prototype.isConstant = function () { return true; };
  2621. FixupExpression.prototype.fixup = function (expression) {
  2622. this.resolved = expression;
  2623. this.shared = true;
  2624. };
  2625. return FixupExpression;
  2626. }(Expression));
  2627. /**
  2628. * A constant pool allows a code emitter to share constant in an output context.
  2629. *
  2630. * The constant pool also supports sharing access to ivy definitions references.
  2631. */
  2632. var ConstantPool = /** @class */ (function () {
  2633. function ConstantPool() {
  2634. this.statements = [];
  2635. this.literals = new Map();
  2636. this.literalFactories = new Map();
  2637. this.injectorDefinitions = new Map();
  2638. this.directiveDefinitions = new Map();
  2639. this.componentDefinitions = new Map();
  2640. this.pipeDefinitions = new Map();
  2641. this.nextNameIndex = 0;
  2642. }
  2643. ConstantPool.prototype.getConstLiteral = function (literal, forceShared) {
  2644. if (literal instanceof LiteralExpr || literal instanceof FixupExpression) {
  2645. // Do no put simple literals into the constant pool or try to produce a constant for a
  2646. // reference to a constant.
  2647. return literal;
  2648. }
  2649. var key = this.keyOf(literal);
  2650. var fixup = this.literals.get(key);
  2651. var newValue = false;
  2652. if (!fixup) {
  2653. fixup = new FixupExpression(literal);
  2654. this.literals.set(key, fixup);
  2655. newValue = true;
  2656. }
  2657. if ((!newValue && !fixup.shared) || (newValue && forceShared)) {
  2658. // Replace the expression with a variable
  2659. var name_1 = this.freshName();
  2660. this.statements.push(variable(name_1).set(literal).toDeclStmt(INFERRED_TYPE, [exports.StmtModifier.Final]));
  2661. fixup.fixup(variable(name_1));
  2662. }
  2663. return fixup;
  2664. };
  2665. ConstantPool.prototype.getDefinition = function (type, kind, ctx, forceShared) {
  2666. if (forceShared === void 0) { forceShared = false; }
  2667. var definitions = this.definitionsOf(kind);
  2668. var fixup = definitions.get(type);
  2669. var newValue = false;
  2670. if (!fixup) {
  2671. var property = this.propertyNameOf(kind);
  2672. fixup = new FixupExpression(ctx.importExpr(type).prop(property));
  2673. definitions.set(type, fixup);
  2674. newValue = true;
  2675. }
  2676. if ((!newValue && !fixup.shared) || (newValue && forceShared)) {
  2677. var name_2 = this.freshName();
  2678. this.statements.push(variable(name_2).set(fixup.resolved).toDeclStmt(INFERRED_TYPE, [exports.StmtModifier.Final]));
  2679. fixup.fixup(variable(name_2));
  2680. }
  2681. return fixup;
  2682. };
  2683. ConstantPool.prototype.getLiteralFactory = function (literal$1) {
  2684. // Create a pure function that builds an array of a mix of constant and variable expressions
  2685. if (literal$1 instanceof LiteralArrayExpr) {
  2686. var argumentsForKey = literal$1.entries.map(function (e) { return e.isConstant() ? e : literal(null); });
  2687. var key = this.keyOf(literalArr(argumentsForKey));
  2688. return this._getLiteralFactory(key, literal$1.entries, function (entries) { return literalArr(entries); });
  2689. }
  2690. else {
  2691. var expressionForKey = literalMap(literal$1.entries.map(function (e) { return ({
  2692. key: e.key,
  2693. value: e.value.isConstant() ? e.value : literal(null),
  2694. quoted: e.quoted
  2695. }); }));
  2696. var key = this.keyOf(expressionForKey);
  2697. return this._getLiteralFactory(key, literal$1.entries.map(function (e) { return e.value; }), function (entries) { return literalMap(entries.map(function (value, index) { return ({
  2698. key: literal$1.entries[index].key,
  2699. value: value,
  2700. quoted: literal$1.entries[index].quoted
  2701. }); })); });
  2702. }
  2703. };
  2704. ConstantPool.prototype._getLiteralFactory = function (key, values, resultMap) {
  2705. var _this = this;
  2706. var literalFactory = this.literalFactories.get(key);
  2707. var literalFactoryArguments = values.filter((function (e) { return !e.isConstant(); }));
  2708. if (!literalFactory) {
  2709. var resultExpressions = values.map(function (e, index) { return e.isConstant() ? _this.getConstLiteral(e, true) : variable("a" + index); });
  2710. var parameters = resultExpressions.filter(isVariable).map(function (e) { return new FnParam(e.name, DYNAMIC_TYPE); });
  2711. var pureFunctionDeclaration = fn(parameters, [new ReturnStatement(resultMap(resultExpressions))], INFERRED_TYPE);
  2712. var name_3 = this.freshName();
  2713. this.statements.push(variable(name_3).set(pureFunctionDeclaration).toDeclStmt(INFERRED_TYPE, [
  2714. exports.StmtModifier.Final
  2715. ]));
  2716. literalFactory = variable(name_3);
  2717. this.literalFactories.set(key, literalFactory);
  2718. }
  2719. return { literalFactory: literalFactory, literalFactoryArguments: literalFactoryArguments };
  2720. };
  2721. /**
  2722. * Produce a unique name.
  2723. *
  2724. * The name might be unique among different prefixes if any of the prefixes end in
  2725. * a digit so the prefix should be a constant string (not based on user input) and
  2726. * must not end in a digit.
  2727. */
  2728. ConstantPool.prototype.uniqueName = function (prefix) { return "" + prefix + this.nextNameIndex++; };
  2729. ConstantPool.prototype.definitionsOf = function (kind) {
  2730. switch (kind) {
  2731. case 2 /* Component */:
  2732. return this.componentDefinitions;
  2733. case 1 /* Directive */:
  2734. return this.directiveDefinitions;
  2735. case 0 /* Injector */:
  2736. return this.injectorDefinitions;
  2737. case 3 /* Pipe */:
  2738. return this.pipeDefinitions;
  2739. }
  2740. error("Unknown definition kind " + kind);
  2741. return this.componentDefinitions;
  2742. };
  2743. ConstantPool.prototype.propertyNameOf = function (kind) {
  2744. switch (kind) {
  2745. case 2 /* Component */:
  2746. return 'ngComponentDef';
  2747. case 1 /* Directive */:
  2748. return 'ngDirectiveDef';
  2749. case 0 /* Injector */:
  2750. return 'ngInjectorDef';
  2751. case 3 /* Pipe */:
  2752. return 'ngPipeDef';
  2753. }
  2754. error("Unknown definition kind " + kind);
  2755. return '<unknown>';
  2756. };
  2757. ConstantPool.prototype.freshName = function () { return this.uniqueName(CONSTANT_PREFIX); };
  2758. ConstantPool.prototype.keyOf = function (expression) {
  2759. return expression.visitExpression(new KeyVisitor(), KEY_CONTEXT);
  2760. };
  2761. return ConstantPool;
  2762. }());
  2763. /**
  2764. * Visitor used to determine if 2 expressions are equivalent and can be shared in the
  2765. * `ConstantPool`.
  2766. *
  2767. * When the id (string) generated by the visitor is equal, expressions are considered equivalent.
  2768. */
  2769. var KeyVisitor = /** @class */ (function () {
  2770. function KeyVisitor() {
  2771. this.visitWrappedNodeExpr = invalid;
  2772. this.visitWriteVarExpr = invalid;
  2773. this.visitWriteKeyExpr = invalid;
  2774. this.visitWritePropExpr = invalid;
  2775. this.visitInvokeMethodExpr = invalid;
  2776. this.visitInvokeFunctionExpr = invalid;
  2777. this.visitInstantiateExpr = invalid;
  2778. this.visitConditionalExpr = invalid;
  2779. this.visitNotExpr = invalid;
  2780. this.visitAssertNotNullExpr = invalid;
  2781. this.visitCastExpr = invalid;
  2782. this.visitFunctionExpr = invalid;
  2783. this.visitBinaryOperatorExpr = invalid;
  2784. this.visitReadPropExpr = invalid;
  2785. this.visitReadKeyExpr = invalid;
  2786. this.visitCommaExpr = invalid;
  2787. }
  2788. KeyVisitor.prototype.visitLiteralExpr = function (ast) {
  2789. return "" + (typeof ast.value === 'string' ? '"' + ast.value + '"' : ast.value);
  2790. };
  2791. KeyVisitor.prototype.visitLiteralArrayExpr = function (ast, context) {
  2792. var _this = this;
  2793. return "[" + ast.entries.map(function (entry) { return entry.visitExpression(_this, context); }).join(',') + "]";
  2794. };
  2795. KeyVisitor.prototype.visitLiteralMapExpr = function (ast, context) {
  2796. var _this = this;
  2797. var mapKey = function (entry) {
  2798. var quote = entry.quoted ? '"' : '';
  2799. return "" + quote + entry.key + quote;
  2800. };
  2801. var mapEntry = function (entry) {
  2802. return mapKey(entry) + ":" + entry.value.visitExpression(_this, context);
  2803. };
  2804. return "{" + ast.entries.map(mapEntry).join(',');
  2805. };
  2806. KeyVisitor.prototype.visitExternalExpr = function (ast) {
  2807. return ast.value.moduleName ? "EX:" + ast.value.moduleName + ":" + ast.value.name :
  2808. "EX:" + ast.value.runtime.name;
  2809. };
  2810. KeyVisitor.prototype.visitReadVarExpr = function (node) { return "VAR:" + node.name; };
  2811. KeyVisitor.prototype.visitTypeofExpr = function (node, context) {
  2812. return "TYPEOF:" + node.expr.visitExpression(this, context);
  2813. };
  2814. return KeyVisitor;
  2815. }());
  2816. function invalid(arg) {
  2817. throw new Error("Invalid state: Visitor " + this.constructor.name + " doesn't handle " + arg.constructor.name);
  2818. }
  2819. function isVariable(e) {
  2820. return e instanceof ReadVarExpr;
  2821. }
  2822. /**
  2823. * @license
  2824. * Copyright Google Inc. All Rights Reserved.
  2825. *
  2826. * Use of this source code is governed by an MIT-style license that can be
  2827. * found in the LICENSE file at https://angular.io/license
  2828. */
  2829. var CORE = '@angular/core';
  2830. var Identifiers = /** @class */ (function () {
  2831. function Identifiers() {
  2832. }
  2833. Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS = {
  2834. name: 'ANALYZE_FOR_ENTRY_COMPONENTS',
  2835. moduleName: CORE,
  2836. };
  2837. Identifiers.ElementRef = { name: 'ElementRef', moduleName: CORE };
  2838. Identifiers.NgModuleRef = { name: 'NgModuleRef', moduleName: CORE };
  2839. Identifiers.ViewContainerRef = { name: 'ViewContainerRef', moduleName: CORE };
  2840. Identifiers.ChangeDetectorRef = {
  2841. name: 'ChangeDetectorRef',
  2842. moduleName: CORE,
  2843. };
  2844. Identifiers.QueryList = { name: 'QueryList', moduleName: CORE };
  2845. Identifiers.TemplateRef = { name: 'TemplateRef', moduleName: CORE };
  2846. Identifiers.Renderer2 = { name: 'Renderer2', moduleName: CORE };
  2847. Identifiers.CodegenComponentFactoryResolver = {
  2848. name: 'ɵCodegenComponentFactoryResolver',
  2849. moduleName: CORE,
  2850. };
  2851. Identifiers.ComponentFactoryResolver = {
  2852. name: 'ComponentFactoryResolver',
  2853. moduleName: CORE,
  2854. };
  2855. Identifiers.ComponentFactory = { name: 'ComponentFactory', moduleName: CORE };
  2856. Identifiers.ComponentRef = { name: 'ComponentRef', moduleName: CORE };
  2857. Identifiers.NgModuleFactory = { name: 'NgModuleFactory', moduleName: CORE };
  2858. Identifiers.createModuleFactory = {
  2859. name: 'ɵcmf',
  2860. moduleName: CORE,
  2861. };
  2862. Identifiers.moduleDef = {
  2863. name: 'ɵmod',
  2864. moduleName: CORE,
  2865. };
  2866. Identifiers.moduleProviderDef = {
  2867. name: 'ɵmpd',
  2868. moduleName: CORE,
  2869. };
  2870. Identifiers.RegisterModuleFactoryFn = {
  2871. name: 'ɵregisterModuleFactory',
  2872. moduleName: CORE,
  2873. };
  2874. Identifiers.inject = { name: 'ɵɵinject', moduleName: CORE };
  2875. Identifiers.INJECTOR = { name: 'INJECTOR', moduleName: CORE };
  2876. Identifiers.Injector = { name: 'Injector', moduleName: CORE };
  2877. Identifiers.ɵɵdefineInjectable = { name: 'ɵɵdefineInjectable', moduleName: CORE };
  2878. Identifiers.InjectableDef = { name: 'ɵɵInjectableDef', moduleName: CORE };
  2879. Identifiers.ViewEncapsulation = {
  2880. name: 'ViewEncapsulation',
  2881. moduleName: CORE,
  2882. };
  2883. Identifiers.ChangeDetectionStrategy = {
  2884. name: 'ChangeDetectionStrategy',
  2885. moduleName: CORE,
  2886. };
  2887. Identifiers.SecurityContext = {
  2888. name: 'SecurityContext',
  2889. moduleName: CORE,
  2890. };
  2891. Identifiers.LOCALE_ID = { name: 'LOCALE_ID', moduleName: CORE };
  2892. Identifiers.TRANSLATIONS_FORMAT = {
  2893. name: 'TRANSLATIONS_FORMAT',
  2894. moduleName: CORE,
  2895. };
  2896. Identifiers.inlineInterpolate = {
  2897. name: 'ɵinlineInterpolate',
  2898. moduleName: CORE,
  2899. };
  2900. Identifiers.interpolate = { name: 'ɵinterpolate', moduleName: CORE };
  2901. Identifiers.EMPTY_ARRAY = { name: 'ɵEMPTY_ARRAY', moduleName: CORE };
  2902. Identifiers.EMPTY_MAP = { name: 'ɵEMPTY_MAP', moduleName: CORE };
  2903. Identifiers.Renderer = { name: 'Renderer', moduleName: CORE };
  2904. Identifiers.viewDef = { name: 'ɵvid', moduleName: CORE };
  2905. Identifiers.elementDef = { name: 'ɵeld', moduleName: CORE };
  2906. Identifiers.anchorDef = { name: 'ɵand', moduleName: CORE };
  2907. Identifiers.textDef = { name: 'ɵted', moduleName: CORE };
  2908. Identifiers.directiveDef = { name: 'ɵdid', moduleName: CORE };
  2909. Identifiers.providerDef = { name: 'ɵprd', moduleName: CORE };
  2910. Identifiers.queryDef = { name: 'ɵqud', moduleName: CORE };
  2911. Identifiers.pureArrayDef = { name: 'ɵpad', moduleName: CORE };
  2912. Identifiers.pureObjectDef = { name: 'ɵpod', moduleName: CORE };
  2913. Identifiers.purePipeDef = { name: 'ɵppd', moduleName: CORE };
  2914. Identifiers.pipeDef = { name: 'ɵpid', moduleName: CORE };
  2915. Identifiers.nodeValue = { name: 'ɵnov', moduleName: CORE };
  2916. Identifiers.ngContentDef = { name: 'ɵncd', moduleName: CORE };
  2917. Identifiers.unwrapValue = { name: 'ɵunv', moduleName: CORE };
  2918. Identifiers.createRendererType2 = { name: 'ɵcrt', moduleName: CORE };
  2919. // type only
  2920. Identifiers.RendererType2 = {
  2921. name: 'RendererType2',
  2922. moduleName: CORE,
  2923. };
  2924. // type only
  2925. Identifiers.ViewDefinition = {
  2926. name: 'ɵViewDefinition',
  2927. moduleName: CORE,
  2928. };
  2929. Identifiers.createComponentFactory = { name: 'ɵccf', moduleName: CORE };
  2930. Identifiers.setClassMetadata = { name: 'ɵsetClassMetadata', moduleName: CORE };
  2931. return Identifiers;
  2932. }());
  2933. function createTokenForReference(reference) {
  2934. return { identifier: { reference: reference } };
  2935. }
  2936. function createTokenForExternalReference(reflector, reference) {
  2937. return createTokenForReference(reflector.resolveExternalReference(reference));
  2938. }
  2939. /**
  2940. * @license
  2941. * Copyright Google Inc. All Rights Reserved.
  2942. *
  2943. * Use of this source code is governed by an MIT-style license that can be
  2944. * found in the LICENSE file at https://angular.io/license
  2945. */
  2946. /**
  2947. * A token representing the a reference to a static type.
  2948. *
  2949. * This token is unique for a filePath and name and can be used as a hash table key.
  2950. */
  2951. var StaticSymbol = /** @class */ (function () {
  2952. function StaticSymbol(filePath, name, members) {
  2953. this.filePath = filePath;
  2954. this.name = name;
  2955. this.members = members;
  2956. }
  2957. StaticSymbol.prototype.assertNoMembers = function () {
  2958. if (this.members.length) {
  2959. throw new Error("Illegal state: symbol without members expected, but got " + JSON.stringify(this) + ".");
  2960. }
  2961. };
  2962. return StaticSymbol;
  2963. }());
  2964. /**
  2965. * A cache of static symbol used by the StaticReflector to return the same symbol for the
  2966. * same symbol values.
  2967. */
  2968. var StaticSymbolCache = /** @class */ (function () {
  2969. function StaticSymbolCache() {
  2970. this.cache = new Map();
  2971. }
  2972. StaticSymbolCache.prototype.get = function (declarationFile, name, members) {
  2973. members = members || [];
  2974. var memberSuffix = members.length ? "." + members.join('.') : '';
  2975. var key = "\"" + declarationFile + "\"." + name + memberSuffix;
  2976. var result = this.cache.get(key);
  2977. if (!result) {
  2978. result = new StaticSymbol(declarationFile, name, members);
  2979. this.cache.set(key, result);
  2980. }
  2981. return result;
  2982. };
  2983. return StaticSymbolCache;
  2984. }());
  2985. /**
  2986. * @license
  2987. * Copyright Google Inc. All Rights Reserved.
  2988. *
  2989. * Use of this source code is governed by an MIT-style license that can be
  2990. * found in the LICENSE file at https://angular.io/license
  2991. */
  2992. // group 0: "[prop] or (event) or @trigger"
  2993. // group 1: "prop" from "[prop]"
  2994. // group 2: "event" from "(event)"
  2995. // group 3: "@trigger" from "@trigger"
  2996. var HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))|(\@[-\w]+)$/;
  2997. function sanitizeIdentifier(name) {
  2998. return name.replace(/\W/g, '_');
  2999. }
  3000. var _anonymousTypeIndex = 0;
  3001. function identifierName(compileIdentifier) {
  3002. if (!compileIdentifier || !compileIdentifier.reference) {
  3003. return null;
  3004. }
  3005. var ref = compileIdentifier.reference;
  3006. if (ref instanceof StaticSymbol) {
  3007. return ref.name;
  3008. }
  3009. if (ref['__anonymousType']) {
  3010. return ref['__anonymousType'];
  3011. }
  3012. var identifier = stringify(ref);
  3013. if (identifier.indexOf('(') >= 0) {
  3014. // case: anonymous functions!
  3015. identifier = "anonymous_" + _anonymousTypeIndex++;
  3016. ref['__anonymousType'] = identifier;
  3017. }
  3018. else {
  3019. identifier = sanitizeIdentifier(identifier);
  3020. }
  3021. return identifier;
  3022. }
  3023. function identifierModuleUrl(compileIdentifier) {
  3024. var ref = compileIdentifier.reference;
  3025. if (ref instanceof StaticSymbol) {
  3026. return ref.filePath;
  3027. }
  3028. // Runtime type
  3029. return "./" + stringify(ref);
  3030. }
  3031. function viewClassName(compType, embeddedTemplateIndex) {
  3032. return "View_" + identifierName({ reference: compType }) + "_" + embeddedTemplateIndex;
  3033. }
  3034. function rendererTypeName(compType) {
  3035. return "RenderType_" + identifierName({ reference: compType });
  3036. }
  3037. function hostViewClassName(compType) {
  3038. return "HostView_" + identifierName({ reference: compType });
  3039. }
  3040. function componentFactoryName(compType) {
  3041. return identifierName({ reference: compType }) + "NgFactory";
  3042. }
  3043. (function (CompileSummaryKind) {
  3044. CompileSummaryKind[CompileSummaryKind["Pipe"] = 0] = "Pipe";
  3045. CompileSummaryKind[CompileSummaryKind["Directive"] = 1] = "Directive";
  3046. CompileSummaryKind[CompileSummaryKind["NgModule"] = 2] = "NgModule";
  3047. CompileSummaryKind[CompileSummaryKind["Injectable"] = 3] = "Injectable";
  3048. })(exports.CompileSummaryKind || (exports.CompileSummaryKind = {}));
  3049. function tokenName(token) {
  3050. return token.value != null ? sanitizeIdentifier(token.value) : identifierName(token.identifier);
  3051. }
  3052. function tokenReference(token) {
  3053. if (token.identifier != null) {
  3054. return token.identifier.reference;
  3055. }
  3056. else {
  3057. return token.value;
  3058. }
  3059. }
  3060. /**
  3061. * Metadata about a stylesheet
  3062. */
  3063. var CompileStylesheetMetadata = /** @class */ (function () {
  3064. function CompileStylesheetMetadata(_a) {
  3065. var _b = _a === void 0 ? {} : _a, moduleUrl = _b.moduleUrl, styles = _b.styles, styleUrls = _b.styleUrls;
  3066. this.moduleUrl = moduleUrl || null;
  3067. this.styles = _normalizeArray(styles);
  3068. this.styleUrls = _normalizeArray(styleUrls);
  3069. }
  3070. return CompileStylesheetMetadata;
  3071. }());
  3072. /**
  3073. * Metadata regarding compilation of a template.
  3074. */
  3075. var CompileTemplateMetadata = /** @class */ (function () {
  3076. function CompileTemplateMetadata(_a) {
  3077. 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;
  3078. this.encapsulation = encapsulation;
  3079. this.template = template;
  3080. this.templateUrl = templateUrl;
  3081. this.htmlAst = htmlAst;
  3082. this.styles = _normalizeArray(styles);
  3083. this.styleUrls = _normalizeArray(styleUrls);
  3084. this.externalStylesheets = _normalizeArray(externalStylesheets);
  3085. this.animations = animations ? flatten(animations) : [];
  3086. this.ngContentSelectors = ngContentSelectors || [];
  3087. if (interpolation && interpolation.length != 2) {
  3088. throw new Error("'interpolation' should have a start and an end symbol.");
  3089. }
  3090. this.interpolation = interpolation;
  3091. this.isInline = isInline;
  3092. this.preserveWhitespaces = preserveWhitespaces;
  3093. }
  3094. CompileTemplateMetadata.prototype.toSummary = function () {
  3095. return {
  3096. ngContentSelectors: this.ngContentSelectors,
  3097. encapsulation: this.encapsulation,
  3098. styles: this.styles,
  3099. animations: this.animations
  3100. };
  3101. };
  3102. return CompileTemplateMetadata;
  3103. }());
  3104. /**
  3105. * Metadata regarding compilation of a directive.
  3106. */
  3107. var CompileDirectiveMetadata = /** @class */ (function () {
  3108. function CompileDirectiveMetadata(_a) {
  3109. 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;
  3110. this.isHost = !!isHost;
  3111. this.type = type;
  3112. this.isComponent = isComponent;
  3113. this.selector = selector;
  3114. this.exportAs = exportAs;
  3115. this.changeDetection = changeDetection;
  3116. this.inputs = inputs;
  3117. this.outputs = outputs;
  3118. this.hostListeners = hostListeners;
  3119. this.hostProperties = hostProperties;
  3120. this.hostAttributes = hostAttributes;
  3121. this.providers = _normalizeArray(providers);
  3122. this.viewProviders = _normalizeArray(viewProviders);
  3123. this.queries = _normalizeArray(queries);
  3124. this.guards = guards;
  3125. this.viewQueries = _normalizeArray(viewQueries);
  3126. this.entryComponents = _normalizeArray(entryComponents);
  3127. this.template = template;
  3128. this.componentViewType = componentViewType;
  3129. this.rendererType = rendererType;
  3130. this.componentFactory = componentFactory;
  3131. }
  3132. CompileDirectiveMetadata.create = function (_a) {
  3133. 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;
  3134. var hostListeners = {};
  3135. var hostProperties = {};
  3136. var hostAttributes = {};
  3137. if (host != null) {
  3138. Object.keys(host).forEach(function (key) {
  3139. var value = host[key];
  3140. var matches = key.match(HOST_REG_EXP);
  3141. if (matches === null) {
  3142. hostAttributes[key] = value;
  3143. }
  3144. else if (matches[1] != null) {
  3145. hostProperties[matches[1]] = value;
  3146. }
  3147. else if (matches[2] != null) {
  3148. hostListeners[matches[2]] = value;
  3149. }
  3150. });
  3151. }
  3152. var inputsMap = {};
  3153. if (inputs != null) {
  3154. inputs.forEach(function (bindConfig) {
  3155. // canonical syntax: `dirProp: elProp`
  3156. // if there is no `:`, use dirProp = elProp
  3157. var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
  3158. inputsMap[parts[0]] = parts[1];
  3159. });
  3160. }
  3161. var outputsMap = {};
  3162. if (outputs != null) {
  3163. outputs.forEach(function (bindConfig) {
  3164. // canonical syntax: `dirProp: elProp`
  3165. // if there is no `:`, use dirProp = elProp
  3166. var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
  3167. outputsMap[parts[0]] = parts[1];
  3168. });
  3169. }
  3170. return new CompileDirectiveMetadata({
  3171. isHost: isHost,
  3172. type: type,
  3173. isComponent: !!isComponent, selector: selector, exportAs: exportAs, changeDetection: changeDetection,
  3174. inputs: inputsMap,
  3175. outputs: outputsMap,
  3176. hostListeners: hostListeners,
  3177. hostProperties: hostProperties,
  3178. hostAttributes: hostAttributes,
  3179. providers: providers,
  3180. viewProviders: viewProviders,
  3181. queries: queries,
  3182. guards: guards,
  3183. viewQueries: viewQueries,
  3184. entryComponents: entryComponents,
  3185. template: template,
  3186. componentViewType: componentViewType,
  3187. rendererType: rendererType,
  3188. componentFactory: componentFactory,
  3189. });
  3190. };
  3191. CompileDirectiveMetadata.prototype.toSummary = function () {
  3192. return {
  3193. summaryKind: exports.CompileSummaryKind.Directive,
  3194. type: this.type,
  3195. isComponent: this.isComponent,
  3196. selector: this.selector,
  3197. exportAs: this.exportAs,
  3198. inputs: this.inputs,
  3199. outputs: this.outputs,
  3200. hostListeners: this.hostListeners,
  3201. hostProperties: this.hostProperties,
  3202. hostAttributes: this.hostAttributes,
  3203. providers: this.providers,
  3204. viewProviders: this.viewProviders,
  3205. queries: this.queries,
  3206. guards: this.guards,
  3207. viewQueries: this.viewQueries,
  3208. entryComponents: this.entryComponents,
  3209. changeDetection: this.changeDetection,
  3210. template: this.template && this.template.toSummary(),
  3211. componentViewType: this.componentViewType,
  3212. rendererType: this.rendererType,
  3213. componentFactory: this.componentFactory
  3214. };
  3215. };
  3216. return CompileDirectiveMetadata;
  3217. }());
  3218. var CompilePipeMetadata = /** @class */ (function () {
  3219. function CompilePipeMetadata(_a) {
  3220. var type = _a.type, name = _a.name, pure = _a.pure;
  3221. this.type = type;
  3222. this.name = name;
  3223. this.pure = !!pure;
  3224. }
  3225. CompilePipeMetadata.prototype.toSummary = function () {
  3226. return {
  3227. summaryKind: exports.CompileSummaryKind.Pipe,
  3228. type: this.type,
  3229. name: this.name,
  3230. pure: this.pure
  3231. };
  3232. };
  3233. return CompilePipeMetadata;
  3234. }());
  3235. var CompileShallowModuleMetadata = /** @class */ (function () {
  3236. function CompileShallowModuleMetadata() {
  3237. }
  3238. return CompileShallowModuleMetadata;
  3239. }());
  3240. /**
  3241. * Metadata regarding compilation of a module.
  3242. */
  3243. var CompileNgModuleMetadata = /** @class */ (function () {
  3244. function CompileNgModuleMetadata(_a) {
  3245. 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;
  3246. this.type = type || null;
  3247. this.declaredDirectives = _normalizeArray(declaredDirectives);
  3248. this.exportedDirectives = _normalizeArray(exportedDirectives);
  3249. this.declaredPipes = _normalizeArray(declaredPipes);
  3250. this.exportedPipes = _normalizeArray(exportedPipes);
  3251. this.providers = _normalizeArray(providers);
  3252. this.entryComponents = _normalizeArray(entryComponents);
  3253. this.bootstrapComponents = _normalizeArray(bootstrapComponents);
  3254. this.importedModules = _normalizeArray(importedModules);
  3255. this.exportedModules = _normalizeArray(exportedModules);
  3256. this.schemas = _normalizeArray(schemas);
  3257. this.id = id || null;
  3258. this.transitiveModule = transitiveModule || null;
  3259. }
  3260. CompileNgModuleMetadata.prototype.toSummary = function () {
  3261. var module = this.transitiveModule;
  3262. return {
  3263. summaryKind: exports.CompileSummaryKind.NgModule,
  3264. type: this.type,
  3265. entryComponents: module.entryComponents,
  3266. providers: module.providers,
  3267. modules: module.modules,
  3268. exportedDirectives: module.exportedDirectives,
  3269. exportedPipes: module.exportedPipes
  3270. };
  3271. };
  3272. return CompileNgModuleMetadata;
  3273. }());
  3274. var TransitiveCompileNgModuleMetadata = /** @class */ (function () {
  3275. function TransitiveCompileNgModuleMetadata() {
  3276. this.directivesSet = new Set();
  3277. this.directives = [];
  3278. this.exportedDirectivesSet = new Set();
  3279. this.exportedDirectives = [];
  3280. this.pipesSet = new Set();
  3281. this.pipes = [];
  3282. this.exportedPipesSet = new Set();
  3283. this.exportedPipes = [];
  3284. this.modulesSet = new Set();
  3285. this.modules = [];
  3286. this.entryComponentsSet = new Set();
  3287. this.entryComponents = [];
  3288. this.providers = [];
  3289. }
  3290. TransitiveCompileNgModuleMetadata.prototype.addProvider = function (provider, module) {
  3291. this.providers.push({ provider: provider, module: module });
  3292. };
  3293. TransitiveCompileNgModuleMetadata.prototype.addDirective = function (id) {
  3294. if (!this.directivesSet.has(id.reference)) {
  3295. this.directivesSet.add(id.reference);
  3296. this.directives.push(id);
  3297. }
  3298. };
  3299. TransitiveCompileNgModuleMetadata.prototype.addExportedDirective = function (id) {
  3300. if (!this.exportedDirectivesSet.has(id.reference)) {
  3301. this.exportedDirectivesSet.add(id.reference);
  3302. this.exportedDirectives.push(id);
  3303. }
  3304. };
  3305. TransitiveCompileNgModuleMetadata.prototype.addPipe = function (id) {
  3306. if (!this.pipesSet.has(id.reference)) {
  3307. this.pipesSet.add(id.reference);
  3308. this.pipes.push(id);
  3309. }
  3310. };
  3311. TransitiveCompileNgModuleMetadata.prototype.addExportedPipe = function (id) {
  3312. if (!this.exportedPipesSet.has(id.reference)) {
  3313. this.exportedPipesSet.add(id.reference);
  3314. this.exportedPipes.push(id);
  3315. }
  3316. };
  3317. TransitiveCompileNgModuleMetadata.prototype.addModule = function (id) {
  3318. if (!this.modulesSet.has(id.reference)) {
  3319. this.modulesSet.add(id.reference);
  3320. this.modules.push(id);
  3321. }
  3322. };
  3323. TransitiveCompileNgModuleMetadata.prototype.addEntryComponent = function (ec) {
  3324. if (!this.entryComponentsSet.has(ec.componentType)) {
  3325. this.entryComponentsSet.add(ec.componentType);
  3326. this.entryComponents.push(ec);
  3327. }
  3328. };
  3329. return TransitiveCompileNgModuleMetadata;
  3330. }());
  3331. function _normalizeArray(obj) {
  3332. return obj || [];
  3333. }
  3334. var ProviderMeta = /** @class */ (function () {
  3335. function ProviderMeta(token, _a) {
  3336. var useClass = _a.useClass, useValue = _a.useValue, useExisting = _a.useExisting, useFactory = _a.useFactory, deps = _a.deps, multi = _a.multi;
  3337. this.token = token;
  3338. this.useClass = useClass || null;
  3339. this.useValue = useValue;
  3340. this.useExisting = useExisting;
  3341. this.useFactory = useFactory || null;
  3342. this.dependencies = deps || null;
  3343. this.multi = !!multi;
  3344. }
  3345. return ProviderMeta;
  3346. }());
  3347. function flatten(list) {
  3348. return list.reduce(function (flat, item) {
  3349. var flatItem = Array.isArray(item) ? flatten(item) : item;
  3350. return flat.concat(flatItem);
  3351. }, []);
  3352. }
  3353. function jitSourceUrl(url) {
  3354. // Note: We need 3 "/" so that ng shows up as a separate domain
  3355. // in the chrome dev tools.
  3356. return url.replace(/(\w+:\/\/[\w:-]+)?(\/+)?/, 'ng:///');
  3357. }
  3358. function templateSourceUrl(ngModuleType, compMeta, templateMeta) {
  3359. var url;
  3360. if (templateMeta.isInline) {
  3361. if (compMeta.type.reference instanceof StaticSymbol) {
  3362. // Note: a .ts file might contain multiple components with inline templates,
  3363. // so we need to give them unique urls, as these will be used for sourcemaps.
  3364. url = compMeta.type.reference.filePath + "." + compMeta.type.reference.name + ".html";
  3365. }
  3366. else {
  3367. url = identifierName(ngModuleType) + "/" + identifierName(compMeta.type) + ".html";
  3368. }
  3369. }
  3370. else {
  3371. url = templateMeta.templateUrl;
  3372. }
  3373. return compMeta.type.reference instanceof StaticSymbol ? url : jitSourceUrl(url);
  3374. }
  3375. function sharedStylesheetJitUrl(meta, id) {
  3376. var pathParts = meta.moduleUrl.split(/\/\\/g);
  3377. var baseName = pathParts[pathParts.length - 1];
  3378. return jitSourceUrl("css/" + id + baseName + ".ngstyle.js");
  3379. }
  3380. function ngModuleJitUrl(moduleMeta) {
  3381. return jitSourceUrl(identifierName(moduleMeta.type) + "/module.ngfactory.js");
  3382. }
  3383. function templateJitUrl(ngModuleType, compMeta) {
  3384. return jitSourceUrl(identifierName(ngModuleType) + "/" + identifierName(compMeta.type) + ".ngfactory.js");
  3385. }
  3386. /**
  3387. * @license
  3388. * Copyright Google Inc. All Rights Reserved.
  3389. *
  3390. * Use of this source code is governed by an MIT-style license that can be
  3391. * found in the LICENSE file at https://angular.io/license
  3392. */
  3393. var CORE$1 = '@angular/core';
  3394. var Identifiers$1 = /** @class */ (function () {
  3395. function Identifiers() {
  3396. }
  3397. /* Methods */
  3398. Identifiers.NEW_METHOD = 'factory';
  3399. Identifiers.TRANSFORM_METHOD = 'transform';
  3400. Identifiers.PATCH_DEPS = 'patchedDeps';
  3401. /* Instructions */
  3402. Identifiers.namespaceHTML = { name: 'ɵɵnamespaceHTML', moduleName: CORE$1 };
  3403. Identifiers.namespaceMathML = { name: 'ɵɵnamespaceMathML', moduleName: CORE$1 };
  3404. Identifiers.namespaceSVG = { name: 'ɵɵnamespaceSVG', moduleName: CORE$1 };
  3405. Identifiers.element = { name: 'ɵɵelement', moduleName: CORE$1 };
  3406. Identifiers.elementStart = { name: 'ɵɵelementStart', moduleName: CORE$1 };
  3407. Identifiers.elementEnd = { name: 'ɵɵelementEnd', moduleName: CORE$1 };
  3408. Identifiers.select = { name: 'ɵɵselect', moduleName: CORE$1 };
  3409. Identifiers.updateSyntheticHostBinding = { name: 'ɵɵupdateSyntheticHostBinding', moduleName: CORE$1 };
  3410. Identifiers.componentHostSyntheticListener = { name: 'ɵɵcomponentHostSyntheticListener', moduleName: CORE$1 };
  3411. Identifiers.attribute = { name: 'ɵɵattribute', moduleName: CORE$1 };
  3412. Identifiers.attributeInterpolate1 = { name: 'ɵɵattributeInterpolate1', moduleName: CORE$1 };
  3413. Identifiers.attributeInterpolate2 = { name: 'ɵɵattributeInterpolate2', moduleName: CORE$1 };
  3414. Identifiers.attributeInterpolate3 = { name: 'ɵɵattributeInterpolate3', moduleName: CORE$1 };
  3415. Identifiers.attributeInterpolate4 = { name: 'ɵɵattributeInterpolate4', moduleName: CORE$1 };
  3416. Identifiers.attributeInterpolate5 = { name: 'ɵɵattributeInterpolate5', moduleName: CORE$1 };
  3417. Identifiers.attributeInterpolate6 = { name: 'ɵɵattributeInterpolate6', moduleName: CORE$1 };
  3418. Identifiers.attributeInterpolate7 = { name: 'ɵɵattributeInterpolate7', moduleName: CORE$1 };
  3419. Identifiers.attributeInterpolate8 = { name: 'ɵɵattributeInterpolate8', moduleName: CORE$1 };
  3420. Identifiers.attributeInterpolateV = { name: 'ɵɵattributeInterpolateV', moduleName: CORE$1 };
  3421. Identifiers.classProp = { name: 'ɵɵclassProp', moduleName: CORE$1 };
  3422. Identifiers.elementContainerStart = { name: 'ɵɵelementContainerStart', moduleName: CORE$1 };
  3423. Identifiers.elementContainerEnd = { name: 'ɵɵelementContainerEnd', moduleName: CORE$1 };
  3424. Identifiers.styling = { name: 'ɵɵstyling', moduleName: CORE$1 };
  3425. Identifiers.styleMap = { name: 'ɵɵstyleMap', moduleName: CORE$1 };
  3426. Identifiers.classMap = { name: 'ɵɵclassMap', moduleName: CORE$1 };
  3427. Identifiers.styleProp = { name: 'ɵɵstyleProp', moduleName: CORE$1 };
  3428. Identifiers.stylingApply = { name: 'ɵɵstylingApply', moduleName: CORE$1 };
  3429. Identifiers.styleSanitizer = { name: 'ɵɵstyleSanitizer', moduleName: CORE$1 };
  3430. Identifiers.elementHostAttrs = { name: 'ɵɵelementHostAttrs', moduleName: CORE$1 };
  3431. Identifiers.containerCreate = { name: 'ɵɵcontainer', moduleName: CORE$1 };
  3432. Identifiers.nextContext = { name: 'ɵɵnextContext', moduleName: CORE$1 };
  3433. Identifiers.templateCreate = { name: 'ɵɵtemplate', moduleName: CORE$1 };
  3434. Identifiers.text = { name: 'ɵɵtext', moduleName: CORE$1 };
  3435. Identifiers.textBinding = { name: 'ɵɵtextBinding', moduleName: CORE$1 };
  3436. Identifiers.enableBindings = { name: 'ɵɵenableBindings', moduleName: CORE$1 };
  3437. Identifiers.disableBindings = { name: 'ɵɵdisableBindings', moduleName: CORE$1 };
  3438. Identifiers.allocHostVars = { name: 'ɵɵallocHostVars', moduleName: CORE$1 };
  3439. Identifiers.getCurrentView = { name: 'ɵɵgetCurrentView', moduleName: CORE$1 };
  3440. Identifiers.textInterpolate = { name: 'ɵɵtextInterpolate', moduleName: CORE$1 };
  3441. Identifiers.textInterpolate1 = { name: 'ɵɵtextInterpolate1', moduleName: CORE$1 };
  3442. Identifiers.textInterpolate2 = { name: 'ɵɵtextInterpolate2', moduleName: CORE$1 };
  3443. Identifiers.textInterpolate3 = { name: 'ɵɵtextInterpolate3', moduleName: CORE$1 };
  3444. Identifiers.textInterpolate4 = { name: 'ɵɵtextInterpolate4', moduleName: CORE$1 };
  3445. Identifiers.textInterpolate5 = { name: 'ɵɵtextInterpolate5', moduleName: CORE$1 };
  3446. Identifiers.textInterpolate6 = { name: 'ɵɵtextInterpolate6', moduleName: CORE$1 };
  3447. Identifiers.textInterpolate7 = { name: 'ɵɵtextInterpolate7', moduleName: CORE$1 };
  3448. Identifiers.textInterpolate8 = { name: 'ɵɵtextInterpolate8', moduleName: CORE$1 };
  3449. Identifiers.textInterpolateV = { name: 'ɵɵtextInterpolateV', moduleName: CORE$1 };
  3450. Identifiers.restoreView = { name: 'ɵɵrestoreView', moduleName: CORE$1 };
  3451. Identifiers.interpolation1 = { name: 'ɵɵinterpolation1', moduleName: CORE$1 };
  3452. Identifiers.interpolation2 = { name: 'ɵɵinterpolation2', moduleName: CORE$1 };
  3453. Identifiers.interpolation3 = { name: 'ɵɵinterpolation3', moduleName: CORE$1 };
  3454. Identifiers.interpolation4 = { name: 'ɵɵinterpolation4', moduleName: CORE$1 };
  3455. Identifiers.interpolation5 = { name: 'ɵɵinterpolation5', moduleName: CORE$1 };
  3456. Identifiers.interpolation6 = { name: 'ɵɵinterpolation6', moduleName: CORE$1 };
  3457. Identifiers.interpolation7 = { name: 'ɵɵinterpolation7', moduleName: CORE$1 };
  3458. Identifiers.interpolation8 = { name: 'ɵɵinterpolation8', moduleName: CORE$1 };
  3459. Identifiers.interpolationV = { name: 'ɵɵinterpolationV', moduleName: CORE$1 };
  3460. Identifiers.pureFunction0 = { name: 'ɵɵpureFunction0', moduleName: CORE$1 };
  3461. Identifiers.pureFunction1 = { name: 'ɵɵpureFunction1', moduleName: CORE$1 };
  3462. Identifiers.pureFunction2 = { name: 'ɵɵpureFunction2', moduleName: CORE$1 };
  3463. Identifiers.pureFunction3 = { name: 'ɵɵpureFunction3', moduleName: CORE$1 };
  3464. Identifiers.pureFunction4 = { name: 'ɵɵpureFunction4', moduleName: CORE$1 };
  3465. Identifiers.pureFunction5 = { name: 'ɵɵpureFunction5', moduleName: CORE$1 };
  3466. Identifiers.pureFunction6 = { name: 'ɵɵpureFunction6', moduleName: CORE$1 };
  3467. Identifiers.pureFunction7 = { name: 'ɵɵpureFunction7', moduleName: CORE$1 };
  3468. Identifiers.pureFunction8 = { name: 'ɵɵpureFunction8', moduleName: CORE$1 };
  3469. Identifiers.pureFunctionV = { name: 'ɵɵpureFunctionV', moduleName: CORE$1 };
  3470. Identifiers.pipeBind1 = { name: 'ɵɵpipeBind1', moduleName: CORE$1 };
  3471. Identifiers.pipeBind2 = { name: 'ɵɵpipeBind2', moduleName: CORE$1 };
  3472. Identifiers.pipeBind3 = { name: 'ɵɵpipeBind3', moduleName: CORE$1 };
  3473. Identifiers.pipeBind4 = { name: 'ɵɵpipeBind4', moduleName: CORE$1 };
  3474. Identifiers.pipeBindV = { name: 'ɵɵpipeBindV', moduleName: CORE$1 };
  3475. Identifiers.property = { name: 'ɵɵproperty', moduleName: CORE$1 };
  3476. Identifiers.propertyInterpolate = { name: 'ɵɵpropertyInterpolate', moduleName: CORE$1 };
  3477. Identifiers.propertyInterpolate1 = { name: 'ɵɵpropertyInterpolate1', moduleName: CORE$1 };
  3478. Identifiers.propertyInterpolate2 = { name: 'ɵɵpropertyInterpolate2', moduleName: CORE$1 };
  3479. Identifiers.propertyInterpolate3 = { name: 'ɵɵpropertyInterpolate3', moduleName: CORE$1 };
  3480. Identifiers.propertyInterpolate4 = { name: 'ɵɵpropertyInterpolate4', moduleName: CORE$1 };
  3481. Identifiers.propertyInterpolate5 = { name: 'ɵɵpropertyInterpolate5', moduleName: CORE$1 };
  3482. Identifiers.propertyInterpolate6 = { name: 'ɵɵpropertyInterpolate6', moduleName: CORE$1 };
  3483. Identifiers.propertyInterpolate7 = { name: 'ɵɵpropertyInterpolate7', moduleName: CORE$1 };
  3484. Identifiers.propertyInterpolate8 = { name: 'ɵɵpropertyInterpolate8', moduleName: CORE$1 };
  3485. Identifiers.propertyInterpolateV = { name: 'ɵɵpropertyInterpolateV', moduleName: CORE$1 };
  3486. Identifiers.i18n = { name: 'ɵɵi18n', moduleName: CORE$1 };
  3487. Identifiers.i18nAttributes = { name: 'ɵɵi18nAttributes', moduleName: CORE$1 };
  3488. Identifiers.i18nExp = { name: 'ɵɵi18nExp', moduleName: CORE$1 };
  3489. Identifiers.i18nStart = { name: 'ɵɵi18nStart', moduleName: CORE$1 };
  3490. Identifiers.i18nEnd = { name: 'ɵɵi18nEnd', moduleName: CORE$1 };
  3491. Identifiers.i18nApply = { name: 'ɵɵi18nApply', moduleName: CORE$1 };
  3492. Identifiers.i18nPostprocess = { name: 'ɵɵi18nPostprocess', moduleName: CORE$1 };
  3493. Identifiers.i18nLocalize = { name: 'ɵɵi18nLocalize', moduleName: CORE$1 };
  3494. Identifiers.load = { name: 'ɵɵload', moduleName: CORE$1 };
  3495. Identifiers.pipe = { name: 'ɵɵpipe', moduleName: CORE$1 };
  3496. Identifiers.projection = { name: 'ɵɵprojection', moduleName: CORE$1 };
  3497. Identifiers.projectionDef = { name: 'ɵɵprojectionDef', moduleName: CORE$1 };
  3498. Identifiers.reference = { name: 'ɵɵreference', moduleName: CORE$1 };
  3499. Identifiers.inject = { name: 'ɵɵinject', moduleName: CORE$1 };
  3500. Identifiers.injectAttribute = { name: 'ɵɵinjectAttribute', moduleName: CORE$1 };
  3501. Identifiers.directiveInject = { name: 'ɵɵdirectiveInject', moduleName: CORE$1 };
  3502. Identifiers.templateRefExtractor = { name: 'ɵɵtemplateRefExtractor', moduleName: CORE$1 };
  3503. Identifiers.resolveWindow = { name: 'ɵɵresolveWindow', moduleName: CORE$1 };
  3504. Identifiers.resolveDocument = { name: 'ɵɵresolveDocument', moduleName: CORE$1 };
  3505. Identifiers.resolveBody = { name: 'ɵɵresolveBody', moduleName: CORE$1 };
  3506. Identifiers.defineBase = { name: 'ɵɵdefineBase', moduleName: CORE$1 };
  3507. Identifiers.BaseDef = {
  3508. name: 'ɵɵBaseDef',
  3509. moduleName: CORE$1,
  3510. };
  3511. Identifiers.defineComponent = { name: 'ɵɵdefineComponent', moduleName: CORE$1 };
  3512. Identifiers.setComponentScope = { name: 'ɵɵsetComponentScope', moduleName: CORE$1 };
  3513. Identifiers.ComponentDefWithMeta = {
  3514. name: 'ɵɵComponentDefWithMeta',
  3515. moduleName: CORE$1,
  3516. };
  3517. Identifiers.defineDirective = {
  3518. name: 'ɵɵdefineDirective',
  3519. moduleName: CORE$1,
  3520. };
  3521. Identifiers.DirectiveDefWithMeta = {
  3522. name: 'ɵɵDirectiveDefWithMeta',
  3523. moduleName: CORE$1,
  3524. };
  3525. Identifiers.InjectorDef = {
  3526. name: 'ɵɵInjectorDef',
  3527. moduleName: CORE$1,
  3528. };
  3529. Identifiers.defineInjector = {
  3530. name: 'ɵɵdefineInjector',
  3531. moduleName: CORE$1,
  3532. };
  3533. Identifiers.NgModuleDefWithMeta = {
  3534. name: 'ɵɵNgModuleDefWithMeta',
  3535. moduleName: CORE$1,
  3536. };
  3537. Identifiers.defineNgModule = { name: 'ɵɵdefineNgModule', moduleName: CORE$1 };
  3538. Identifiers.setNgModuleScope = { name: 'ɵɵsetNgModuleScope', moduleName: CORE$1 };
  3539. Identifiers.PipeDefWithMeta = { name: 'ɵɵPipeDefWithMeta', moduleName: CORE$1 };
  3540. Identifiers.definePipe = { name: 'ɵɵdefinePipe', moduleName: CORE$1 };
  3541. Identifiers.queryRefresh = { name: 'ɵɵqueryRefresh', moduleName: CORE$1 };
  3542. Identifiers.viewQuery = { name: 'ɵɵviewQuery', moduleName: CORE$1 };
  3543. Identifiers.staticViewQuery = { name: 'ɵɵstaticViewQuery', moduleName: CORE$1 };
  3544. Identifiers.staticContentQuery = { name: 'ɵɵstaticContentQuery', moduleName: CORE$1 };
  3545. Identifiers.loadViewQuery = { name: 'ɵɵloadViewQuery', moduleName: CORE$1 };
  3546. Identifiers.contentQuery = { name: 'ɵɵcontentQuery', moduleName: CORE$1 };
  3547. Identifiers.loadContentQuery = { name: 'ɵɵloadContentQuery', moduleName: CORE$1 };
  3548. Identifiers.NgOnChangesFeature = { name: 'ɵɵNgOnChangesFeature', moduleName: CORE$1 };
  3549. Identifiers.InheritDefinitionFeature = { name: 'ɵɵInheritDefinitionFeature', moduleName: CORE$1 };
  3550. Identifiers.ProvidersFeature = { name: 'ɵɵProvidersFeature', moduleName: CORE$1 };
  3551. Identifiers.listener = { name: 'ɵɵlistener', moduleName: CORE$1 };
  3552. Identifiers.getFactoryOf = {
  3553. name: 'ɵɵgetFactoryOf',
  3554. moduleName: CORE$1,
  3555. };
  3556. Identifiers.getInheritedFactory = {
  3557. name: 'ɵɵgetInheritedFactory',
  3558. moduleName: CORE$1,
  3559. };
  3560. // sanitization-related functions
  3561. Identifiers.sanitizeHtml = { name: 'ɵɵsanitizeHtml', moduleName: CORE$1 };
  3562. Identifiers.sanitizeStyle = { name: 'ɵɵsanitizeStyle', moduleName: CORE$1 };
  3563. Identifiers.defaultStyleSanitizer = { name: 'ɵɵdefaultStyleSanitizer', moduleName: CORE$1 };
  3564. Identifiers.sanitizeResourceUrl = { name: 'ɵɵsanitizeResourceUrl', moduleName: CORE$1 };
  3565. Identifiers.sanitizeScript = { name: 'ɵɵsanitizeScript', moduleName: CORE$1 };
  3566. Identifiers.sanitizeUrl = { name: 'ɵɵsanitizeUrl', moduleName: CORE$1 };
  3567. Identifiers.sanitizeUrlOrResourceUrl = { name: 'ɵɵsanitizeUrlOrResourceUrl', moduleName: CORE$1 };
  3568. return Identifiers;
  3569. }());
  3570. /**
  3571. * @license
  3572. * Copyright Google Inc. All Rights Reserved.
  3573. *
  3574. * Use of this source code is governed by an MIT-style license that can be
  3575. * found in the LICENSE file at https://angular.io/license
  3576. */
  3577. var $EOF = 0;
  3578. var $BSPACE = 8;
  3579. var $TAB = 9;
  3580. var $LF = 10;
  3581. var $VTAB = 11;
  3582. var $FF = 12;
  3583. var $CR = 13;
  3584. var $SPACE = 32;
  3585. var $BANG = 33;
  3586. var $DQ = 34;
  3587. var $HASH = 35;
  3588. var $$ = 36;
  3589. var $PERCENT = 37;
  3590. var $AMPERSAND = 38;
  3591. var $SQ = 39;
  3592. var $LPAREN = 40;
  3593. var $RPAREN = 41;
  3594. var $STAR = 42;
  3595. var $PLUS = 43;
  3596. var $COMMA = 44;
  3597. var $MINUS = 45;
  3598. var $PERIOD = 46;
  3599. var $SLASH = 47;
  3600. var $COLON = 58;
  3601. var $SEMICOLON = 59;
  3602. var $LT = 60;
  3603. var $EQ = 61;
  3604. var $GT = 62;
  3605. var $QUESTION = 63;
  3606. var $0 = 48;
  3607. var $7 = 55;
  3608. var $9 = 57;
  3609. var $A = 65;
  3610. var $E = 69;
  3611. var $F = 70;
  3612. var $X = 88;
  3613. var $Z = 90;
  3614. var $LBRACKET = 91;
  3615. var $BACKSLASH = 92;
  3616. var $RBRACKET = 93;
  3617. var $CARET = 94;
  3618. var $_ = 95;
  3619. var $a = 97;
  3620. var $b = 98;
  3621. var $e = 101;
  3622. var $f = 102;
  3623. var $n = 110;
  3624. var $r = 114;
  3625. var $t = 116;
  3626. var $u = 117;
  3627. var $v = 118;
  3628. var $x = 120;
  3629. var $z = 122;
  3630. var $LBRACE = 123;
  3631. var $BAR = 124;
  3632. var $RBRACE = 125;
  3633. var $NBSP = 160;
  3634. var $BT = 96;
  3635. function isWhitespace(code) {
  3636. return (code >= $TAB && code <= $SPACE) || (code == $NBSP);
  3637. }
  3638. function isDigit(code) {
  3639. return $0 <= code && code <= $9;
  3640. }
  3641. function isAsciiLetter(code) {
  3642. return code >= $a && code <= $z || code >= $A && code <= $Z;
  3643. }
  3644. function isAsciiHexDigit(code) {
  3645. return code >= $a && code <= $f || code >= $A && code <= $F || isDigit(code);
  3646. }
  3647. function isNewLine(code) {
  3648. return code === $LF || code === $CR;
  3649. }
  3650. function isOctalDigit(code) {
  3651. return $0 <= code && code <= $7;
  3652. }
  3653. /**
  3654. * @license
  3655. * Copyright Google Inc. All Rights Reserved.
  3656. *
  3657. * Use of this source code is governed by an MIT-style license that can be
  3658. * found in the LICENSE file at https://angular.io/license
  3659. */
  3660. var ParseLocation = /** @class */ (function () {
  3661. function ParseLocation(file, offset, line, col) {
  3662. this.file = file;
  3663. this.offset = offset;
  3664. this.line = line;
  3665. this.col = col;
  3666. }
  3667. ParseLocation.prototype.toString = function () {
  3668. return this.offset != null ? this.file.url + "@" + this.line + ":" + this.col : this.file.url;
  3669. };
  3670. ParseLocation.prototype.moveBy = function (delta) {
  3671. var source = this.file.content;
  3672. var len = source.length;
  3673. var offset = this.offset;
  3674. var line = this.line;
  3675. var col = this.col;
  3676. while (offset > 0 && delta < 0) {
  3677. offset--;
  3678. delta++;
  3679. var ch = source.charCodeAt(offset);
  3680. if (ch == $LF) {
  3681. line--;
  3682. var priorLine = source.substr(0, offset - 1).lastIndexOf(String.fromCharCode($LF));
  3683. col = priorLine > 0 ? offset - priorLine : offset;
  3684. }
  3685. else {
  3686. col--;
  3687. }
  3688. }
  3689. while (offset < len && delta > 0) {
  3690. var ch = source.charCodeAt(offset);
  3691. offset++;
  3692. delta--;
  3693. if (ch == $LF) {
  3694. line++;
  3695. col = 0;
  3696. }
  3697. else {
  3698. col++;
  3699. }
  3700. }
  3701. return new ParseLocation(this.file, offset, line, col);
  3702. };
  3703. // Return the source around the location
  3704. // Up to `maxChars` or `maxLines` on each side of the location
  3705. ParseLocation.prototype.getContext = function (maxChars, maxLines) {
  3706. var content = this.file.content;
  3707. var startOffset = this.offset;
  3708. if (startOffset != null) {
  3709. if (startOffset > content.length - 1) {
  3710. startOffset = content.length - 1;
  3711. }
  3712. var endOffset = startOffset;
  3713. var ctxChars = 0;
  3714. var ctxLines = 0;
  3715. while (ctxChars < maxChars && startOffset > 0) {
  3716. startOffset--;
  3717. ctxChars++;
  3718. if (content[startOffset] == '\n') {
  3719. if (++ctxLines == maxLines) {
  3720. break;
  3721. }
  3722. }
  3723. }
  3724. ctxChars = 0;
  3725. ctxLines = 0;
  3726. while (ctxChars < maxChars && endOffset < content.length - 1) {
  3727. endOffset++;
  3728. ctxChars++;
  3729. if (content[endOffset] == '\n') {
  3730. if (++ctxLines == maxLines) {
  3731. break;
  3732. }
  3733. }
  3734. }
  3735. return {
  3736. before: content.substring(startOffset, this.offset),
  3737. after: content.substring(this.offset, endOffset + 1),
  3738. };
  3739. }
  3740. return null;
  3741. };
  3742. return ParseLocation;
  3743. }());
  3744. var ParseSourceFile = /** @class */ (function () {
  3745. function ParseSourceFile(content, url) {
  3746. this.content = content;
  3747. this.url = url;
  3748. }
  3749. return ParseSourceFile;
  3750. }());
  3751. var ParseSourceSpan = /** @class */ (function () {
  3752. function ParseSourceSpan(start, end, details) {
  3753. if (details === void 0) { details = null; }
  3754. this.start = start;
  3755. this.end = end;
  3756. this.details = details;
  3757. }
  3758. ParseSourceSpan.prototype.toString = function () {
  3759. return this.start.file.content.substring(this.start.offset, this.end.offset);
  3760. };
  3761. return ParseSourceSpan;
  3762. }());
  3763. (function (ParseErrorLevel) {
  3764. ParseErrorLevel[ParseErrorLevel["WARNING"] = 0] = "WARNING";
  3765. ParseErrorLevel[ParseErrorLevel["ERROR"] = 1] = "ERROR";
  3766. })(exports.ParseErrorLevel || (exports.ParseErrorLevel = {}));
  3767. var ParseError = /** @class */ (function () {
  3768. function ParseError(span, msg, level) {
  3769. if (level === void 0) { level = exports.ParseErrorLevel.ERROR; }
  3770. this.span = span;
  3771. this.msg = msg;
  3772. this.level = level;
  3773. }
  3774. ParseError.prototype.contextualMessage = function () {
  3775. var ctx = this.span.start.getContext(100, 3);
  3776. return ctx ? this.msg + " (\"" + ctx.before + "[" + exports.ParseErrorLevel[this.level] + " ->]" + ctx.after + "\")" :
  3777. this.msg;
  3778. };
  3779. ParseError.prototype.toString = function () {
  3780. var details = this.span.details ? ", " + this.span.details : '';
  3781. return this.contextualMessage() + ": " + this.span.start + details;
  3782. };
  3783. return ParseError;
  3784. }());
  3785. function typeSourceSpan(kind, type) {
  3786. var moduleUrl = identifierModuleUrl(type);
  3787. var sourceFileName = moduleUrl != null ? "in " + kind + " " + identifierName(type) + " in " + moduleUrl :
  3788. "in " + kind + " " + identifierName(type);
  3789. var sourceFile = new ParseSourceFile('', sourceFileName);
  3790. return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
  3791. }
  3792. /**
  3793. * Generates Source Span object for a given R3 Type for JIT mode.
  3794. *
  3795. * @param kind Component or Directive.
  3796. * @param typeName name of the Component or Directive.
  3797. * @param sourceUrl reference to Component or Directive source.
  3798. * @returns instance of ParseSourceSpan that represent a given Component or Directive.
  3799. */
  3800. function r3JitTypeSourceSpan(kind, typeName, sourceUrl) {
  3801. var sourceFileName = "in " + kind + " " + typeName + " in " + sourceUrl;
  3802. var sourceFile = new ParseSourceFile('', sourceFileName);
  3803. return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
  3804. }
  3805. /**
  3806. * @license
  3807. * Copyright Google Inc. All Rights Reserved.
  3808. *
  3809. * Use of this source code is governed by an MIT-style license that can be
  3810. * found in the LICENSE file at https://angular.io/license
  3811. */
  3812. var Text = /** @class */ (function () {
  3813. function Text(value, sourceSpan) {
  3814. this.value = value;
  3815. this.sourceSpan = sourceSpan;
  3816. }
  3817. Text.prototype.visit = function (visitor) { return visitor.visitText(this); };
  3818. return Text;
  3819. }());
  3820. var BoundText = /** @class */ (function () {
  3821. function BoundText(value, sourceSpan, i18n) {
  3822. this.value = value;
  3823. this.sourceSpan = sourceSpan;
  3824. this.i18n = i18n;
  3825. }
  3826. BoundText.prototype.visit = function (visitor) { return visitor.visitBoundText(this); };
  3827. return BoundText;
  3828. }());
  3829. var TextAttribute = /** @class */ (function () {
  3830. function TextAttribute(name, value, sourceSpan, valueSpan, i18n) {
  3831. this.name = name;
  3832. this.value = value;
  3833. this.sourceSpan = sourceSpan;
  3834. this.valueSpan = valueSpan;
  3835. this.i18n = i18n;
  3836. }
  3837. TextAttribute.prototype.visit = function (visitor) { return visitor.visitTextAttribute(this); };
  3838. return TextAttribute;
  3839. }());
  3840. var BoundAttribute = /** @class */ (function () {
  3841. function BoundAttribute(name, type, securityContext, value, unit, sourceSpan, i18n) {
  3842. this.name = name;
  3843. this.type = type;
  3844. this.securityContext = securityContext;
  3845. this.value = value;
  3846. this.unit = unit;
  3847. this.sourceSpan = sourceSpan;
  3848. this.i18n = i18n;
  3849. }
  3850. BoundAttribute.fromBoundElementProperty = function (prop, i18n) {
  3851. return new BoundAttribute(prop.name, prop.type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan, i18n);
  3852. };
  3853. BoundAttribute.prototype.visit = function (visitor) { return visitor.visitBoundAttribute(this); };
  3854. return BoundAttribute;
  3855. }());
  3856. var BoundEvent = /** @class */ (function () {
  3857. function BoundEvent(name, type, handler, target, phase, sourceSpan, handlerSpan) {
  3858. this.name = name;
  3859. this.type = type;
  3860. this.handler = handler;
  3861. this.target = target;
  3862. this.phase = phase;
  3863. this.sourceSpan = sourceSpan;
  3864. this.handlerSpan = handlerSpan;
  3865. }
  3866. BoundEvent.fromParsedEvent = function (event) {
  3867. var target = event.type === 0 /* Regular */ ? event.targetOrPhase : null;
  3868. var phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null;
  3869. return new BoundEvent(event.name, event.type, event.handler, target, phase, event.sourceSpan, event.handlerSpan);
  3870. };
  3871. BoundEvent.prototype.visit = function (visitor) { return visitor.visitBoundEvent(this); };
  3872. return BoundEvent;
  3873. }());
  3874. var Element = /** @class */ (function () {
  3875. function Element(name, attributes, inputs, outputs, children, references, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
  3876. this.name = name;
  3877. this.attributes = attributes;
  3878. this.inputs = inputs;
  3879. this.outputs = outputs;
  3880. this.children = children;
  3881. this.references = references;
  3882. this.sourceSpan = sourceSpan;
  3883. this.startSourceSpan = startSourceSpan;
  3884. this.endSourceSpan = endSourceSpan;
  3885. this.i18n = i18n;
  3886. // If the element is empty then the source span should include any closing tag
  3887. if (children.length === 0 && startSourceSpan && endSourceSpan) {
  3888. this.sourceSpan = new ParseSourceSpan(sourceSpan.start, endSourceSpan.end);
  3889. }
  3890. }
  3891. Element.prototype.visit = function (visitor) { return visitor.visitElement(this); };
  3892. return Element;
  3893. }());
  3894. var Template = /** @class */ (function () {
  3895. function Template(tagName, attributes, inputs, outputs, templateAttrs, children, references, variables, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
  3896. this.tagName = tagName;
  3897. this.attributes = attributes;
  3898. this.inputs = inputs;
  3899. this.outputs = outputs;
  3900. this.templateAttrs = templateAttrs;
  3901. this.children = children;
  3902. this.references = references;
  3903. this.variables = variables;
  3904. this.sourceSpan = sourceSpan;
  3905. this.startSourceSpan = startSourceSpan;
  3906. this.endSourceSpan = endSourceSpan;
  3907. this.i18n = i18n;
  3908. }
  3909. Template.prototype.visit = function (visitor) { return visitor.visitTemplate(this); };
  3910. return Template;
  3911. }());
  3912. var Content = /** @class */ (function () {
  3913. function Content(selector, attributes, sourceSpan, i18n) {
  3914. this.selector = selector;
  3915. this.attributes = attributes;
  3916. this.sourceSpan = sourceSpan;
  3917. this.i18n = i18n;
  3918. }
  3919. Content.prototype.visit = function (visitor) { return visitor.visitContent(this); };
  3920. return Content;
  3921. }());
  3922. var Variable = /** @class */ (function () {
  3923. function Variable(name, value, sourceSpan) {
  3924. this.name = name;
  3925. this.value = value;
  3926. this.sourceSpan = sourceSpan;
  3927. }
  3928. Variable.prototype.visit = function (visitor) { return visitor.visitVariable(this); };
  3929. return Variable;
  3930. }());
  3931. var Reference = /** @class */ (function () {
  3932. function Reference(name, value, sourceSpan) {
  3933. this.name = name;
  3934. this.value = value;
  3935. this.sourceSpan = sourceSpan;
  3936. }
  3937. Reference.prototype.visit = function (visitor) { return visitor.visitReference(this); };
  3938. return Reference;
  3939. }());
  3940. var Icu = /** @class */ (function () {
  3941. function Icu(vars, placeholders, sourceSpan, i18n) {
  3942. this.vars = vars;
  3943. this.placeholders = placeholders;
  3944. this.sourceSpan = sourceSpan;
  3945. this.i18n = i18n;
  3946. }
  3947. Icu.prototype.visit = function (visitor) { return visitor.visitIcu(this); };
  3948. return Icu;
  3949. }());
  3950. function visitAll(visitor, nodes) {
  3951. var e_1, _a, e_2, _b;
  3952. var result = [];
  3953. if (visitor.visit) {
  3954. try {
  3955. for (var nodes_1 = __values(nodes), nodes_1_1 = nodes_1.next(); !nodes_1_1.done; nodes_1_1 = nodes_1.next()) {
  3956. var node = nodes_1_1.value;
  3957. var newNode = visitor.visit(node) || node.visit(visitor);
  3958. }
  3959. }
  3960. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  3961. finally {
  3962. try {
  3963. if (nodes_1_1 && !nodes_1_1.done && (_a = nodes_1.return)) _a.call(nodes_1);
  3964. }
  3965. finally { if (e_1) throw e_1.error; }
  3966. }
  3967. }
  3968. else {
  3969. try {
  3970. for (var nodes_2 = __values(nodes), nodes_2_1 = nodes_2.next(); !nodes_2_1.done; nodes_2_1 = nodes_2.next()) {
  3971. var node = nodes_2_1.value;
  3972. var newNode = node.visit(visitor);
  3973. if (newNode) {
  3974. result.push(newNode);
  3975. }
  3976. }
  3977. }
  3978. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  3979. finally {
  3980. try {
  3981. if (nodes_2_1 && !nodes_2_1.done && (_b = nodes_2.return)) _b.call(nodes_2);
  3982. }
  3983. finally { if (e_2) throw e_2.error; }
  3984. }
  3985. }
  3986. return result;
  3987. }
  3988. /**
  3989. * @license
  3990. * Copyright Google Inc. All Rights Reserved.
  3991. *
  3992. * Use of this source code is governed by an MIT-style license that can be
  3993. * found in the LICENSE file at https://angular.io/license
  3994. */
  3995. var Message = /** @class */ (function () {
  3996. /**
  3997. * @param nodes message AST
  3998. * @param placeholders maps placeholder names to static content
  3999. * @param placeholderToMessage maps placeholder names to messages (used for nested ICU messages)
  4000. * @param meaning
  4001. * @param description
  4002. * @param id
  4003. */
  4004. function Message(nodes, placeholders, placeholderToMessage, meaning, description, id) {
  4005. this.nodes = nodes;
  4006. this.placeholders = placeholders;
  4007. this.placeholderToMessage = placeholderToMessage;
  4008. this.meaning = meaning;
  4009. this.description = description;
  4010. this.id = id;
  4011. if (nodes.length) {
  4012. this.sources = [{
  4013. filePath: nodes[0].sourceSpan.start.file.url,
  4014. startLine: nodes[0].sourceSpan.start.line + 1,
  4015. startCol: nodes[0].sourceSpan.start.col + 1,
  4016. endLine: nodes[nodes.length - 1].sourceSpan.end.line + 1,
  4017. endCol: nodes[0].sourceSpan.start.col + 1
  4018. }];
  4019. }
  4020. else {
  4021. this.sources = [];
  4022. }
  4023. }
  4024. return Message;
  4025. }());
  4026. var Text$1 = /** @class */ (function () {
  4027. function Text(value, sourceSpan) {
  4028. this.value = value;
  4029. this.sourceSpan = sourceSpan;
  4030. }
  4031. Text.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
  4032. return Text;
  4033. }());
  4034. // TODO(vicb): do we really need this node (vs an array) ?
  4035. var Container = /** @class */ (function () {
  4036. function Container(children, sourceSpan) {
  4037. this.children = children;
  4038. this.sourceSpan = sourceSpan;
  4039. }
  4040. Container.prototype.visit = function (visitor, context) { return visitor.visitContainer(this, context); };
  4041. return Container;
  4042. }());
  4043. var Icu$1 = /** @class */ (function () {
  4044. function Icu(expression, type, cases, sourceSpan) {
  4045. this.expression = expression;
  4046. this.type = type;
  4047. this.cases = cases;
  4048. this.sourceSpan = sourceSpan;
  4049. }
  4050. Icu.prototype.visit = function (visitor, context) { return visitor.visitIcu(this, context); };
  4051. return Icu;
  4052. }());
  4053. var TagPlaceholder = /** @class */ (function () {
  4054. function TagPlaceholder(tag, attrs, startName, closeName, children, isVoid, sourceSpan) {
  4055. this.tag = tag;
  4056. this.attrs = attrs;
  4057. this.startName = startName;
  4058. this.closeName = closeName;
  4059. this.children = children;
  4060. this.isVoid = isVoid;
  4061. this.sourceSpan = sourceSpan;
  4062. }
  4063. TagPlaceholder.prototype.visit = function (visitor, context) { return visitor.visitTagPlaceholder(this, context); };
  4064. return TagPlaceholder;
  4065. }());
  4066. var Placeholder = /** @class */ (function () {
  4067. function Placeholder(value, name, sourceSpan) {
  4068. this.value = value;
  4069. this.name = name;
  4070. this.sourceSpan = sourceSpan;
  4071. }
  4072. Placeholder.prototype.visit = function (visitor, context) { return visitor.visitPlaceholder(this, context); };
  4073. return Placeholder;
  4074. }());
  4075. var IcuPlaceholder = /** @class */ (function () {
  4076. function IcuPlaceholder(value, name, sourceSpan) {
  4077. this.value = value;
  4078. this.name = name;
  4079. this.sourceSpan = sourceSpan;
  4080. }
  4081. IcuPlaceholder.prototype.visit = function (visitor, context) { return visitor.visitIcuPlaceholder(this, context); };
  4082. return IcuPlaceholder;
  4083. }());
  4084. // Clone the AST
  4085. var CloneVisitor = /** @class */ (function () {
  4086. function CloneVisitor() {
  4087. }
  4088. CloneVisitor.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
  4089. CloneVisitor.prototype.visitContainer = function (container, context) {
  4090. var _this = this;
  4091. var children = container.children.map(function (n) { return n.visit(_this, context); });
  4092. return new Container(children, container.sourceSpan);
  4093. };
  4094. CloneVisitor.prototype.visitIcu = function (icu, context) {
  4095. var _this = this;
  4096. var cases = {};
  4097. Object.keys(icu.cases).forEach(function (key) { return cases[key] = icu.cases[key].visit(_this, context); });
  4098. var msg = new Icu$1(icu.expression, icu.type, cases, icu.sourceSpan);
  4099. msg.expressionPlaceholder = icu.expressionPlaceholder;
  4100. return msg;
  4101. };
  4102. CloneVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  4103. var _this = this;
  4104. var children = ph.children.map(function (n) { return n.visit(_this, context); });
  4105. return new TagPlaceholder(ph.tag, ph.attrs, ph.startName, ph.closeName, children, ph.isVoid, ph.sourceSpan);
  4106. };
  4107. CloneVisitor.prototype.visitPlaceholder = function (ph, context) {
  4108. return new Placeholder(ph.value, ph.name, ph.sourceSpan);
  4109. };
  4110. CloneVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  4111. return new IcuPlaceholder(ph.value, ph.name, ph.sourceSpan);
  4112. };
  4113. return CloneVisitor;
  4114. }());
  4115. // Visit all the nodes recursively
  4116. var RecurseVisitor = /** @class */ (function () {
  4117. function RecurseVisitor() {
  4118. }
  4119. RecurseVisitor.prototype.visitText = function (text, context) { };
  4120. RecurseVisitor.prototype.visitContainer = function (container, context) {
  4121. var _this = this;
  4122. container.children.forEach(function (child) { return child.visit(_this); });
  4123. };
  4124. RecurseVisitor.prototype.visitIcu = function (icu, context) {
  4125. var _this = this;
  4126. Object.keys(icu.cases).forEach(function (k) { icu.cases[k].visit(_this); });
  4127. };
  4128. RecurseVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  4129. var _this = this;
  4130. ph.children.forEach(function (child) { return child.visit(_this); });
  4131. };
  4132. RecurseVisitor.prototype.visitPlaceholder = function (ph, context) { };
  4133. RecurseVisitor.prototype.visitIcuPlaceholder = function (ph, context) { };
  4134. return RecurseVisitor;
  4135. }());
  4136. /**
  4137. * @license
  4138. * Copyright Google Inc. All Rights Reserved.
  4139. *
  4140. * Use of this source code is governed by an MIT-style license that can be
  4141. * found in the LICENSE file at https://angular.io/license
  4142. */
  4143. function digest(message) {
  4144. return message.id || sha1(serializeNodes(message.nodes).join('') + ("[" + message.meaning + "]"));
  4145. }
  4146. function decimalDigest(message) {
  4147. if (message.id) {
  4148. return message.id;
  4149. }
  4150. var visitor = new _SerializerIgnoreIcuExpVisitor();
  4151. var parts = message.nodes.map(function (a) { return a.visit(visitor, null); });
  4152. return computeMsgId(parts.join(''), message.meaning);
  4153. }
  4154. /**
  4155. * Serialize the i18n ast to something xml-like in order to generate an UID.
  4156. *
  4157. * The visitor is also used in the i18n parser tests
  4158. *
  4159. * @internal
  4160. */
  4161. var _SerializerVisitor = /** @class */ (function () {
  4162. function _SerializerVisitor() {
  4163. }
  4164. _SerializerVisitor.prototype.visitText = function (text, context) { return text.value; };
  4165. _SerializerVisitor.prototype.visitContainer = function (container, context) {
  4166. var _this = this;
  4167. return "[" + container.children.map(function (child) { return child.visit(_this); }).join(', ') + "]";
  4168. };
  4169. _SerializerVisitor.prototype.visitIcu = function (icu, context) {
  4170. var _this = this;
  4171. var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
  4172. return "{" + icu.expression + ", " + icu.type + ", " + strCases.join(', ') + "}";
  4173. };
  4174. _SerializerVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  4175. var _this = this;
  4176. return ph.isVoid ?
  4177. "<ph tag name=\"" + ph.startName + "\"/>" :
  4178. "<ph tag name=\"" + ph.startName + "\">" + ph.children.map(function (child) { return child.visit(_this); }).join(', ') + "</ph name=\"" + ph.closeName + "\">";
  4179. };
  4180. _SerializerVisitor.prototype.visitPlaceholder = function (ph, context) {
  4181. return ph.value ? "<ph name=\"" + ph.name + "\">" + ph.value + "</ph>" : "<ph name=\"" + ph.name + "\"/>";
  4182. };
  4183. _SerializerVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  4184. return "<ph icu name=\"" + ph.name + "\">" + ph.value.visit(this) + "</ph>";
  4185. };
  4186. return _SerializerVisitor;
  4187. }());
  4188. var serializerVisitor = new _SerializerVisitor();
  4189. function serializeNodes(nodes) {
  4190. return nodes.map(function (a) { return a.visit(serializerVisitor, null); });
  4191. }
  4192. /**
  4193. * Serialize the i18n ast to something xml-like in order to generate an UID.
  4194. *
  4195. * Ignore the ICU expressions so that message IDs stays identical if only the expression changes.
  4196. *
  4197. * @internal
  4198. */
  4199. var _SerializerIgnoreIcuExpVisitor = /** @class */ (function (_super) {
  4200. __extends(_SerializerIgnoreIcuExpVisitor, _super);
  4201. function _SerializerIgnoreIcuExpVisitor() {
  4202. return _super !== null && _super.apply(this, arguments) || this;
  4203. }
  4204. _SerializerIgnoreIcuExpVisitor.prototype.visitIcu = function (icu, context) {
  4205. var _this = this;
  4206. var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
  4207. // Do not take the expression into account
  4208. return "{" + icu.type + ", " + strCases.join(', ') + "}";
  4209. };
  4210. return _SerializerIgnoreIcuExpVisitor;
  4211. }(_SerializerVisitor));
  4212. /**
  4213. * Compute the SHA1 of the given string
  4214. *
  4215. * see http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
  4216. *
  4217. * WARNING: this function has not been designed not tested with security in mind.
  4218. * DO NOT USE IT IN A SECURITY SENSITIVE CONTEXT.
  4219. */
  4220. function sha1(str) {
  4221. var _a, _b;
  4222. var utf8 = utf8Encode(str);
  4223. var words32 = stringToWords32(utf8, Endian.Big);
  4224. var len = utf8.length * 8;
  4225. var w = new Array(80);
  4226. var _c = __read([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0], 5), a = _c[0], b = _c[1], c = _c[2], d = _c[3], e = _c[4];
  4227. words32[len >> 5] |= 0x80 << (24 - len % 32);
  4228. words32[((len + 64 >> 9) << 4) + 15] = len;
  4229. for (var i = 0; i < words32.length; i += 16) {
  4230. var _d = __read([a, b, c, d, e], 5), h0 = _d[0], h1 = _d[1], h2 = _d[2], h3 = _d[3], h4 = _d[4];
  4231. for (var j = 0; j < 80; j++) {
  4232. if (j < 16) {
  4233. w[j] = words32[i + j];
  4234. }
  4235. else {
  4236. w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
  4237. }
  4238. var _e = __read(fk(j, b, c, d), 2), f = _e[0], k = _e[1];
  4239. var temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32);
  4240. _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];
  4241. }
  4242. _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];
  4243. }
  4244. return byteStringToHexString(words32ToByteString([a, b, c, d, e]));
  4245. }
  4246. function fk(index, b, c, d) {
  4247. if (index < 20) {
  4248. return [(b & c) | (~b & d), 0x5a827999];
  4249. }
  4250. if (index < 40) {
  4251. return [b ^ c ^ d, 0x6ed9eba1];
  4252. }
  4253. if (index < 60) {
  4254. return [(b & c) | (b & d) | (c & d), 0x8f1bbcdc];
  4255. }
  4256. return [b ^ c ^ d, 0xca62c1d6];
  4257. }
  4258. /**
  4259. * Compute the fingerprint of the given string
  4260. *
  4261. * The output is 64 bit number encoded as a decimal string
  4262. *
  4263. * based on:
  4264. * https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java
  4265. */
  4266. function fingerprint(str) {
  4267. var utf8 = utf8Encode(str);
  4268. var _a = __read([hash32(utf8, 0), hash32(utf8, 102072)], 2), hi = _a[0], lo = _a[1];
  4269. if (hi == 0 && (lo == 0 || lo == 1)) {
  4270. hi = hi ^ 0x130f9bef;
  4271. lo = lo ^ -0x6b5f56d8;
  4272. }
  4273. return [hi, lo];
  4274. }
  4275. function computeMsgId(msg, meaning) {
  4276. var _a;
  4277. var _b = __read(fingerprint(msg), 2), hi = _b[0], lo = _b[1];
  4278. if (meaning) {
  4279. var _c = __read(fingerprint(meaning), 2), him = _c[0], lom = _c[1];
  4280. _a = __read(add64(rol64([hi, lo], 1), [him, lom]), 2), hi = _a[0], lo = _a[1];
  4281. }
  4282. return byteStringToDecString(words32ToByteString([hi & 0x7fffffff, lo]));
  4283. }
  4284. function hash32(str, c) {
  4285. var _a;
  4286. var _b = __read([0x9e3779b9, 0x9e3779b9], 2), a = _b[0], b = _b[1];
  4287. var i;
  4288. var len = str.length;
  4289. for (i = 0; i + 12 <= len; i += 12) {
  4290. a = add32(a, wordAt(str, i, Endian.Little));
  4291. b = add32(b, wordAt(str, i + 4, Endian.Little));
  4292. c = add32(c, wordAt(str, i + 8, Endian.Little));
  4293. _a = __read(mix([a, b, c]), 3), a = _a[0], b = _a[1], c = _a[2];
  4294. }
  4295. a = add32(a, wordAt(str, i, Endian.Little));
  4296. b = add32(b, wordAt(str, i + 4, Endian.Little));
  4297. // the first byte of c is reserved for the length
  4298. c = add32(c, len);
  4299. c = add32(c, wordAt(str, i + 8, Endian.Little) << 8);
  4300. return mix([a, b, c])[2];
  4301. }
  4302. // clang-format off
  4303. function mix(_a) {
  4304. var _b = __read(_a, 3), a = _b[0], b = _b[1], c = _b[2];
  4305. a = sub32(a, b);
  4306. a = sub32(a, c);
  4307. a ^= c >>> 13;
  4308. b = sub32(b, c);
  4309. b = sub32(b, a);
  4310. b ^= a << 8;
  4311. c = sub32(c, a);
  4312. c = sub32(c, b);
  4313. c ^= b >>> 13;
  4314. a = sub32(a, b);
  4315. a = sub32(a, c);
  4316. a ^= c >>> 12;
  4317. b = sub32(b, c);
  4318. b = sub32(b, a);
  4319. b ^= a << 16;
  4320. c = sub32(c, a);
  4321. c = sub32(c, b);
  4322. c ^= b >>> 5;
  4323. a = sub32(a, b);
  4324. a = sub32(a, c);
  4325. a ^= c >>> 3;
  4326. b = sub32(b, c);
  4327. b = sub32(b, a);
  4328. b ^= a << 10;
  4329. c = sub32(c, a);
  4330. c = sub32(c, b);
  4331. c ^= b >>> 15;
  4332. return [a, b, c];
  4333. }
  4334. // clang-format on
  4335. // Utils
  4336. var Endian;
  4337. (function (Endian) {
  4338. Endian[Endian["Little"] = 0] = "Little";
  4339. Endian[Endian["Big"] = 1] = "Big";
  4340. })(Endian || (Endian = {}));
  4341. function add32(a, b) {
  4342. return add32to64(a, b)[1];
  4343. }
  4344. function add32to64(a, b) {
  4345. var low = (a & 0xffff) + (b & 0xffff);
  4346. var high = (a >>> 16) + (b >>> 16) + (low >>> 16);
  4347. return [high >>> 16, (high << 16) | (low & 0xffff)];
  4348. }
  4349. function add64(_a, _b) {
  4350. var _c = __read(_a, 2), ah = _c[0], al = _c[1];
  4351. var _d = __read(_b, 2), bh = _d[0], bl = _d[1];
  4352. var _e = __read(add32to64(al, bl), 2), carry = _e[0], l = _e[1];
  4353. var h = add32(add32(ah, bh), carry);
  4354. return [h, l];
  4355. }
  4356. function sub32(a, b) {
  4357. var low = (a & 0xffff) - (b & 0xffff);
  4358. var high = (a >> 16) - (b >> 16) + (low >> 16);
  4359. return (high << 16) | (low & 0xffff);
  4360. }
  4361. // Rotate a 32b number left `count` position
  4362. function rol32(a, count) {
  4363. return (a << count) | (a >>> (32 - count));
  4364. }
  4365. // Rotate a 64b number left `count` position
  4366. function rol64(_a, count) {
  4367. var _b = __read(_a, 2), hi = _b[0], lo = _b[1];
  4368. var h = (hi << count) | (lo >>> (32 - count));
  4369. var l = (lo << count) | (hi >>> (32 - count));
  4370. return [h, l];
  4371. }
  4372. function stringToWords32(str, endian) {
  4373. var words32 = Array((str.length + 3) >>> 2);
  4374. for (var i = 0; i < words32.length; i++) {
  4375. words32[i] = wordAt(str, i * 4, endian);
  4376. }
  4377. return words32;
  4378. }
  4379. function byteAt(str, index) {
  4380. return index >= str.length ? 0 : str.charCodeAt(index) & 0xff;
  4381. }
  4382. function wordAt(str, index, endian) {
  4383. var word = 0;
  4384. if (endian === Endian.Big) {
  4385. for (var i = 0; i < 4; i++) {
  4386. word += byteAt(str, index + i) << (24 - 8 * i);
  4387. }
  4388. }
  4389. else {
  4390. for (var i = 0; i < 4; i++) {
  4391. word += byteAt(str, index + i) << 8 * i;
  4392. }
  4393. }
  4394. return word;
  4395. }
  4396. function words32ToByteString(words32) {
  4397. return words32.reduce(function (str, word) { return str + word32ToByteString(word); }, '');
  4398. }
  4399. function word32ToByteString(word) {
  4400. var str = '';
  4401. for (var i = 0; i < 4; i++) {
  4402. str += String.fromCharCode((word >>> 8 * (3 - i)) & 0xff);
  4403. }
  4404. return str;
  4405. }
  4406. function byteStringToHexString(str) {
  4407. var hex = '';
  4408. for (var i = 0; i < str.length; i++) {
  4409. var b = byteAt(str, i);
  4410. hex += (b >>> 4).toString(16) + (b & 0x0f).toString(16);
  4411. }
  4412. return hex.toLowerCase();
  4413. }
  4414. // based on http://www.danvk.org/hex2dec.html (JS can not handle more than 56b)
  4415. function byteStringToDecString(str) {
  4416. var decimal = '';
  4417. var toThePower = '1';
  4418. for (var i = str.length - 1; i >= 0; i--) {
  4419. decimal = addBigInt(decimal, numberTimesBigInt(byteAt(str, i), toThePower));
  4420. toThePower = numberTimesBigInt(256, toThePower);
  4421. }
  4422. return decimal.split('').reverse().join('');
  4423. }
  4424. // x and y decimal, lowest significant digit first
  4425. function addBigInt(x, y) {
  4426. var sum = '';
  4427. var len = Math.max(x.length, y.length);
  4428. for (var i = 0, carry = 0; i < len || carry; i++) {
  4429. var tmpSum = carry + +(x[i] || 0) + +(y[i] || 0);
  4430. if (tmpSum >= 10) {
  4431. carry = 1;
  4432. sum += tmpSum - 10;
  4433. }
  4434. else {
  4435. carry = 0;
  4436. sum += tmpSum;
  4437. }
  4438. }
  4439. return sum;
  4440. }
  4441. function numberTimesBigInt(num, b) {
  4442. var product = '';
  4443. var bToThePower = b;
  4444. for (; num !== 0; num = num >>> 1) {
  4445. if (num & 1)
  4446. product = addBigInt(product, bToThePower);
  4447. bToThePower = addBigInt(bToThePower, bToThePower);
  4448. }
  4449. return product;
  4450. }
  4451. /**
  4452. * @license
  4453. * Copyright Google Inc. All Rights Reserved.
  4454. *
  4455. * Use of this source code is governed by an MIT-style license that can be
  4456. * found in the LICENSE file at https://angular.io/license
  4457. */
  4458. var Serializer = /** @class */ (function () {
  4459. function Serializer() {
  4460. }
  4461. // Creates a name mapper, see `PlaceholderMapper`
  4462. // Returning `null` means that no name mapping is used.
  4463. Serializer.prototype.createNameMapper = function (message) { return null; };
  4464. return Serializer;
  4465. }());
  4466. /**
  4467. * A simple mapper that take a function to transform an internal name to a public name
  4468. */
  4469. var SimplePlaceholderMapper = /** @class */ (function (_super) {
  4470. __extends(SimplePlaceholderMapper, _super);
  4471. // create a mapping from the message
  4472. function SimplePlaceholderMapper(message, mapName) {
  4473. var _this = _super.call(this) || this;
  4474. _this.mapName = mapName;
  4475. _this.internalToPublic = {};
  4476. _this.publicToNextId = {};
  4477. _this.publicToInternal = {};
  4478. message.nodes.forEach(function (node) { return node.visit(_this); });
  4479. return _this;
  4480. }
  4481. SimplePlaceholderMapper.prototype.toPublicName = function (internalName) {
  4482. return this.internalToPublic.hasOwnProperty(internalName) ?
  4483. this.internalToPublic[internalName] :
  4484. null;
  4485. };
  4486. SimplePlaceholderMapper.prototype.toInternalName = function (publicName) {
  4487. return this.publicToInternal.hasOwnProperty(publicName) ? this.publicToInternal[publicName] :
  4488. null;
  4489. };
  4490. SimplePlaceholderMapper.prototype.visitText = function (text, context) { return null; };
  4491. SimplePlaceholderMapper.prototype.visitTagPlaceholder = function (ph, context) {
  4492. this.visitPlaceholderName(ph.startName);
  4493. _super.prototype.visitTagPlaceholder.call(this, ph, context);
  4494. this.visitPlaceholderName(ph.closeName);
  4495. };
  4496. SimplePlaceholderMapper.prototype.visitPlaceholder = function (ph, context) { this.visitPlaceholderName(ph.name); };
  4497. SimplePlaceholderMapper.prototype.visitIcuPlaceholder = function (ph, context) {
  4498. this.visitPlaceholderName(ph.name);
  4499. };
  4500. // XMB placeholders could only contains A-Z, 0-9 and _
  4501. SimplePlaceholderMapper.prototype.visitPlaceholderName = function (internalName) {
  4502. if (!internalName || this.internalToPublic.hasOwnProperty(internalName)) {
  4503. return;
  4504. }
  4505. var publicName = this.mapName(internalName);
  4506. if (this.publicToInternal.hasOwnProperty(publicName)) {
  4507. // Create a new XMB when it has already been used
  4508. var nextId = this.publicToNextId[publicName];
  4509. this.publicToNextId[publicName] = nextId + 1;
  4510. publicName = publicName + "_" + nextId;
  4511. }
  4512. else {
  4513. this.publicToNextId[publicName] = 1;
  4514. }
  4515. this.internalToPublic[internalName] = publicName;
  4516. this.publicToInternal[publicName] = internalName;
  4517. };
  4518. return SimplePlaceholderMapper;
  4519. }(RecurseVisitor));
  4520. /**
  4521. * @license
  4522. * Copyright Google Inc. All Rights Reserved.
  4523. *
  4524. * Use of this source code is governed by an MIT-style license that can be
  4525. * found in the LICENSE file at https://angular.io/license
  4526. */
  4527. var _Visitor = /** @class */ (function () {
  4528. function _Visitor() {
  4529. }
  4530. _Visitor.prototype.visitTag = function (tag) {
  4531. var _this = this;
  4532. var strAttrs = this._serializeAttributes(tag.attrs);
  4533. if (tag.children.length == 0) {
  4534. return "<" + tag.name + strAttrs + "/>";
  4535. }
  4536. var strChildren = tag.children.map(function (node) { return node.visit(_this); });
  4537. return "<" + tag.name + strAttrs + ">" + strChildren.join('') + "</" + tag.name + ">";
  4538. };
  4539. _Visitor.prototype.visitText = function (text) { return text.value; };
  4540. _Visitor.prototype.visitDeclaration = function (decl) {
  4541. return "<?xml" + this._serializeAttributes(decl.attrs) + " ?>";
  4542. };
  4543. _Visitor.prototype._serializeAttributes = function (attrs) {
  4544. var strAttrs = Object.keys(attrs).map(function (name) { return name + "=\"" + attrs[name] + "\""; }).join(' ');
  4545. return strAttrs.length > 0 ? ' ' + strAttrs : '';
  4546. };
  4547. _Visitor.prototype.visitDoctype = function (doctype) {
  4548. return "<!DOCTYPE " + doctype.rootTag + " [\n" + doctype.dtd + "\n]>";
  4549. };
  4550. return _Visitor;
  4551. }());
  4552. var _visitor = new _Visitor();
  4553. function serialize(nodes) {
  4554. return nodes.map(function (node) { return node.visit(_visitor); }).join('');
  4555. }
  4556. var Declaration = /** @class */ (function () {
  4557. function Declaration(unescapedAttrs) {
  4558. var _this = this;
  4559. this.attrs = {};
  4560. Object.keys(unescapedAttrs).forEach(function (k) {
  4561. _this.attrs[k] = escapeXml(unescapedAttrs[k]);
  4562. });
  4563. }
  4564. Declaration.prototype.visit = function (visitor) { return visitor.visitDeclaration(this); };
  4565. return Declaration;
  4566. }());
  4567. var Doctype = /** @class */ (function () {
  4568. function Doctype(rootTag, dtd) {
  4569. this.rootTag = rootTag;
  4570. this.dtd = dtd;
  4571. }
  4572. Doctype.prototype.visit = function (visitor) { return visitor.visitDoctype(this); };
  4573. return Doctype;
  4574. }());
  4575. var Tag = /** @class */ (function () {
  4576. function Tag(name, unescapedAttrs, children) {
  4577. var _this = this;
  4578. if (unescapedAttrs === void 0) { unescapedAttrs = {}; }
  4579. if (children === void 0) { children = []; }
  4580. this.name = name;
  4581. this.children = children;
  4582. this.attrs = {};
  4583. Object.keys(unescapedAttrs).forEach(function (k) {
  4584. _this.attrs[k] = escapeXml(unescapedAttrs[k]);
  4585. });
  4586. }
  4587. Tag.prototype.visit = function (visitor) { return visitor.visitTag(this); };
  4588. return Tag;
  4589. }());
  4590. var Text$2 = /** @class */ (function () {
  4591. function Text(unescapedValue) {
  4592. this.value = escapeXml(unescapedValue);
  4593. }
  4594. Text.prototype.visit = function (visitor) { return visitor.visitText(this); };
  4595. return Text;
  4596. }());
  4597. var CR = /** @class */ (function (_super) {
  4598. __extends(CR, _super);
  4599. function CR(ws) {
  4600. if (ws === void 0) { ws = 0; }
  4601. return _super.call(this, "\n" + new Array(ws + 1).join(' ')) || this;
  4602. }
  4603. return CR;
  4604. }(Text$2));
  4605. var _ESCAPED_CHARS = [
  4606. [/&/g, '&amp;'],
  4607. [/"/g, '&quot;'],
  4608. [/'/g, '&apos;'],
  4609. [/</g, '&lt;'],
  4610. [/>/g, '&gt;'],
  4611. ];
  4612. // Escape `_ESCAPED_CHARS` characters in the given text with encoded entities
  4613. function escapeXml(text) {
  4614. return _ESCAPED_CHARS.reduce(function (text, entry) { return text.replace(entry[0], entry[1]); }, text);
  4615. }
  4616. /**
  4617. * @license
  4618. * Copyright Google Inc. All Rights Reserved.
  4619. *
  4620. * Use of this source code is governed by an MIT-style license that can be
  4621. * found in the LICENSE file at https://angular.io/license
  4622. */
  4623. var _MESSAGES_TAG = 'messagebundle';
  4624. var _MESSAGE_TAG = 'msg';
  4625. var _PLACEHOLDER_TAG = 'ph';
  4626. var _EXAMPLE_TAG = 'ex';
  4627. var _SOURCE_TAG = 'source';
  4628. 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)>";
  4629. var Xmb = /** @class */ (function (_super) {
  4630. __extends(Xmb, _super);
  4631. function Xmb() {
  4632. return _super !== null && _super.apply(this, arguments) || this;
  4633. }
  4634. Xmb.prototype.write = function (messages, locale) {
  4635. var exampleVisitor = new ExampleVisitor();
  4636. var visitor = new _Visitor$1();
  4637. var rootNode = new Tag(_MESSAGES_TAG);
  4638. messages.forEach(function (message) {
  4639. var attrs = { id: message.id };
  4640. if (message.description) {
  4641. attrs['desc'] = message.description;
  4642. }
  4643. if (message.meaning) {
  4644. attrs['meaning'] = message.meaning;
  4645. }
  4646. var sourceTags = [];
  4647. message.sources.forEach(function (source) {
  4648. sourceTags.push(new Tag(_SOURCE_TAG, {}, [
  4649. new Text$2(source.filePath + ":" + source.startLine + (source.endLine !== source.startLine ? ',' + source.endLine : ''))
  4650. ]));
  4651. });
  4652. rootNode.children.push(new CR(2), new Tag(_MESSAGE_TAG, attrs, __spread(sourceTags, visitor.serialize(message.nodes))));
  4653. });
  4654. rootNode.children.push(new CR());
  4655. return serialize([
  4656. new Declaration({ version: '1.0', encoding: 'UTF-8' }),
  4657. new CR(),
  4658. new Doctype(_MESSAGES_TAG, _DOCTYPE),
  4659. new CR(),
  4660. exampleVisitor.addDefaultExamples(rootNode),
  4661. new CR(),
  4662. ]);
  4663. };
  4664. Xmb.prototype.load = function (content, url) {
  4665. throw new Error('Unsupported');
  4666. };
  4667. Xmb.prototype.digest = function (message) { return digest$1(message); };
  4668. Xmb.prototype.createNameMapper = function (message) {
  4669. return new SimplePlaceholderMapper(message, toPublicName);
  4670. };
  4671. return Xmb;
  4672. }(Serializer));
  4673. var _Visitor$1 = /** @class */ (function () {
  4674. function _Visitor() {
  4675. }
  4676. _Visitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
  4677. _Visitor.prototype.visitContainer = function (container, context) {
  4678. var _this = this;
  4679. var nodes = [];
  4680. container.children.forEach(function (node) { return nodes.push.apply(nodes, __spread(node.visit(_this))); });
  4681. return nodes;
  4682. };
  4683. _Visitor.prototype.visitIcu = function (icu, context) {
  4684. var _this = this;
  4685. var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
  4686. Object.keys(icu.cases).forEach(function (c) {
  4687. nodes.push.apply(nodes, __spread([new Text$2(c + " {")], icu.cases[c].visit(_this), [new Text$2("} ")]));
  4688. });
  4689. nodes.push(new Text$2("}"));
  4690. return nodes;
  4691. };
  4692. _Visitor.prototype.visitTagPlaceholder = function (ph, context) {
  4693. var startTagAsText = new Text$2("<" + ph.tag + ">");
  4694. var startEx = new Tag(_EXAMPLE_TAG, {}, [startTagAsText]);
  4695. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  4696. var startTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.startName }, [startEx, startTagAsText]);
  4697. if (ph.isVoid) {
  4698. // void tags have no children nor closing tags
  4699. return [startTagPh];
  4700. }
  4701. var closeTagAsText = new Text$2("</" + ph.tag + ">");
  4702. var closeEx = new Tag(_EXAMPLE_TAG, {}, [closeTagAsText]);
  4703. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  4704. var closeTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.closeName }, [closeEx, closeTagAsText]);
  4705. return __spread([startTagPh], this.serialize(ph.children), [closeTagPh]);
  4706. };
  4707. _Visitor.prototype.visitPlaceholder = function (ph, context) {
  4708. var interpolationAsText = new Text$2("{{" + ph.value + "}}");
  4709. // Example tag needs to be not-empty for TC.
  4710. var exTag = new Tag(_EXAMPLE_TAG, {}, [interpolationAsText]);
  4711. return [
  4712. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  4713. new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, interpolationAsText])
  4714. ];
  4715. };
  4716. _Visitor.prototype.visitIcuPlaceholder = function (ph, context) {
  4717. var icuExpression = ph.value.expression;
  4718. var icuType = ph.value.type;
  4719. var icuCases = Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ');
  4720. var icuAsText = new Text$2("{" + icuExpression + ", " + icuType + ", " + icuCases + "}");
  4721. var exTag = new Tag(_EXAMPLE_TAG, {}, [icuAsText]);
  4722. return [
  4723. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  4724. new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, icuAsText])
  4725. ];
  4726. };
  4727. _Visitor.prototype.serialize = function (nodes) {
  4728. var _this = this;
  4729. return [].concat.apply([], __spread(nodes.map(function (node) { return node.visit(_this); })));
  4730. };
  4731. return _Visitor;
  4732. }());
  4733. function digest$1(message) {
  4734. return decimalDigest(message);
  4735. }
  4736. // TC requires at least one non-empty example on placeholders
  4737. var ExampleVisitor = /** @class */ (function () {
  4738. function ExampleVisitor() {
  4739. }
  4740. ExampleVisitor.prototype.addDefaultExamples = function (node) {
  4741. node.visit(this);
  4742. return node;
  4743. };
  4744. ExampleVisitor.prototype.visitTag = function (tag) {
  4745. var _this = this;
  4746. if (tag.name === _PLACEHOLDER_TAG) {
  4747. if (!tag.children || tag.children.length == 0) {
  4748. var exText = new Text$2(tag.attrs['name'] || '...');
  4749. tag.children = [new Tag(_EXAMPLE_TAG, {}, [exText])];
  4750. }
  4751. }
  4752. else if (tag.children) {
  4753. tag.children.forEach(function (node) { return node.visit(_this); });
  4754. }
  4755. };
  4756. ExampleVisitor.prototype.visitText = function (text) { };
  4757. ExampleVisitor.prototype.visitDeclaration = function (decl) { };
  4758. ExampleVisitor.prototype.visitDoctype = function (doctype) { };
  4759. return ExampleVisitor;
  4760. }());
  4761. // XMB/XTB placeholders can only contain A-Z, 0-9 and _
  4762. function toPublicName(internalName) {
  4763. return internalName.toUpperCase().replace(/[^A-Z0-9_]/g, '_');
  4764. }
  4765. /**
  4766. * @license
  4767. * Copyright Google Inc. All Rights Reserved.
  4768. *
  4769. * Use of this source code is governed by an MIT-style license that can be
  4770. * found in the LICENSE file at https://angular.io/license
  4771. */
  4772. function mapLiteral(obj, quoted) {
  4773. if (quoted === void 0) { quoted = false; }
  4774. return literalMap(Object.keys(obj).map(function (key) { return ({
  4775. key: key,
  4776. quoted: quoted,
  4777. value: obj[key],
  4778. }); }));
  4779. }
  4780. /**
  4781. * @license
  4782. * Copyright Google Inc. All Rights Reserved.
  4783. *
  4784. * Use of this source code is governed by an MIT-style license that can be
  4785. * found in the LICENSE file at https://angular.io/license
  4786. */
  4787. /* Closure variables holding messages must be named `MSG_[A-Z0-9]+` */
  4788. var CLOSURE_TRANSLATION_PREFIX = 'MSG_';
  4789. /* Prefix for non-`goog.getMsg` i18n-related vars */
  4790. var TRANSLATION_PREFIX = 'I18N_';
  4791. /** Closure uses `goog.getMsg(message)` to lookup translations */
  4792. var GOOG_GET_MSG = 'goog.getMsg';
  4793. /** Name of the global variable that is used to determine if we use Closure translations or not */
  4794. var NG_I18N_CLOSURE_MODE = 'ngI18nClosureMode';
  4795. /** I18n separators for metadata **/
  4796. var I18N_MEANING_SEPARATOR = '|';
  4797. var I18N_ID_SEPARATOR = '@@';
  4798. /** Name of the i18n attributes **/
  4799. var I18N_ATTR = 'i18n';
  4800. var I18N_ATTR_PREFIX = 'i18n-';
  4801. /** Prefix of var expressions used in ICUs */
  4802. var I18N_ICU_VAR_PREFIX = 'VAR_';
  4803. /** Prefix of ICU expressions for post processing */
  4804. var I18N_ICU_MAPPING_PREFIX = 'I18N_EXP_';
  4805. /** Placeholder wrapper for i18n expressions **/
  4806. var I18N_PLACEHOLDER_SYMBOL = '�';
  4807. function i18nTranslationToDeclStmt(variable$1, closureVar, message, meta, params) {
  4808. var statements = [];
  4809. // var I18N_X;
  4810. statements.push(new DeclareVarStmt(variable$1.name, undefined, INFERRED_TYPE, null, variable$1.sourceSpan));
  4811. var args = [literal(message)];
  4812. if (params && Object.keys(params).length) {
  4813. args.push(mapLiteral(params, true));
  4814. }
  4815. // Closure JSDoc comments
  4816. var docStatements = i18nMetaToDocStmt(meta);
  4817. var thenStatements = docStatements ? [docStatements] : [];
  4818. var googFnCall = variable(GOOG_GET_MSG).callFn(args);
  4819. // const MSG_... = goog.getMsg(..);
  4820. thenStatements.push(closureVar.set(googFnCall).toConstDecl());
  4821. // I18N_X = MSG_...;
  4822. thenStatements.push(new ExpressionStatement(variable$1.set(closureVar)));
  4823. var localizeFnCall = importExpr(Identifiers$1.i18nLocalize).callFn(args);
  4824. // I18N_X = i18nLocalize(...);
  4825. var elseStatements = [new ExpressionStatement(variable$1.set(localizeFnCall))];
  4826. // if(ngI18nClosureMode) { ... } else { ... }
  4827. statements.push(ifStmt(variable(NG_I18N_CLOSURE_MODE), thenStatements, elseStatements));
  4828. return statements;
  4829. }
  4830. // Converts i18n meta information for a message (id, description, meaning)
  4831. // to a JsDoc statement formatted as expected by the Closure compiler.
  4832. function i18nMetaToDocStmt(meta) {
  4833. var tags = [];
  4834. if (meta.description) {
  4835. tags.push({ tagName: "desc" /* Desc */, text: meta.description });
  4836. }
  4837. if (meta.meaning) {
  4838. tags.push({ tagName: "meaning" /* Meaning */, text: meta.meaning });
  4839. }
  4840. return tags.length == 0 ? null : new JSDocCommentStmt(tags);
  4841. }
  4842. function isI18nAttribute(name) {
  4843. return name === I18N_ATTR || name.startsWith(I18N_ATTR_PREFIX);
  4844. }
  4845. function isI18nRootNode(meta) {
  4846. return meta instanceof Message;
  4847. }
  4848. function isSingleI18nIcu(meta) {
  4849. return isI18nRootNode(meta) && meta.nodes.length === 1 && meta.nodes[0] instanceof Icu$1;
  4850. }
  4851. function hasI18nAttrs(element) {
  4852. return element.attrs.some(function (attr) { return isI18nAttribute(attr.name); });
  4853. }
  4854. function metaFromI18nMessage(message, id) {
  4855. if (id === void 0) { id = null; }
  4856. return {
  4857. id: typeof id === 'string' ? id : message.id || '',
  4858. meaning: message.meaning || '',
  4859. description: message.description || ''
  4860. };
  4861. }
  4862. function icuFromI18nMessage(message) {
  4863. return message.nodes[0];
  4864. }
  4865. function wrapI18nPlaceholder(content, contextId) {
  4866. if (contextId === void 0) { contextId = 0; }
  4867. var blockId = contextId > 0 ? ":" + contextId : '';
  4868. return "" + I18N_PLACEHOLDER_SYMBOL + content + blockId + I18N_PLACEHOLDER_SYMBOL;
  4869. }
  4870. function assembleI18nBoundString(strings, bindingStartIndex, contextId) {
  4871. if (bindingStartIndex === void 0) { bindingStartIndex = 0; }
  4872. if (contextId === void 0) { contextId = 0; }
  4873. if (!strings.length)
  4874. return '';
  4875. var acc = '';
  4876. var lastIdx = strings.length - 1;
  4877. for (var i = 0; i < lastIdx; i++) {
  4878. acc += "" + strings[i] + wrapI18nPlaceholder(bindingStartIndex + i, contextId);
  4879. }
  4880. acc += strings[lastIdx];
  4881. return acc;
  4882. }
  4883. function getSeqNumberGenerator(startsAt) {
  4884. if (startsAt === void 0) { startsAt = 0; }
  4885. var current = startsAt;
  4886. return function () { return current++; };
  4887. }
  4888. function placeholdersToParams(placeholders) {
  4889. var params = {};
  4890. placeholders.forEach(function (values, key) {
  4891. params[key] = literal(values.length > 1 ? "[" + values.join('|') + "]" : values[0]);
  4892. });
  4893. return params;
  4894. }
  4895. function updatePlaceholderMap(map, name) {
  4896. var values = [];
  4897. for (var _i = 2; _i < arguments.length; _i++) {
  4898. values[_i - 2] = arguments[_i];
  4899. }
  4900. var current = map.get(name) || [];
  4901. current.push.apply(current, __spread(values));
  4902. map.set(name, current);
  4903. }
  4904. function assembleBoundTextPlaceholders(meta, bindingStartIndex, contextId) {
  4905. if (bindingStartIndex === void 0) { bindingStartIndex = 0; }
  4906. if (contextId === void 0) { contextId = 0; }
  4907. var startIdx = bindingStartIndex;
  4908. var placeholders = new Map();
  4909. var node = meta instanceof Message ? meta.nodes.find(function (node) { return node instanceof Container; }) : meta;
  4910. if (node) {
  4911. node
  4912. .children.filter(function (child) { return child instanceof Placeholder; })
  4913. .forEach(function (child, idx) {
  4914. var content = wrapI18nPlaceholder(startIdx + idx, contextId);
  4915. updatePlaceholderMap(placeholders, child.name, content);
  4916. });
  4917. }
  4918. return placeholders;
  4919. }
  4920. function findIndex(items, callback) {
  4921. for (var i = 0; i < items.length; i++) {
  4922. if (callback(items[i])) {
  4923. return i;
  4924. }
  4925. }
  4926. return -1;
  4927. }
  4928. /**
  4929. * Parses i18n metas like:
  4930. * - "@@id",
  4931. * - "description[@@id]",
  4932. * - "meaning|description[@@id]"
  4933. * and returns an object with parsed output.
  4934. *
  4935. * @param meta String that represents i18n meta
  4936. * @returns Object with id, meaning and description fields
  4937. */
  4938. function parseI18nMeta(meta) {
  4939. var _a, _b;
  4940. var id;
  4941. var meaning;
  4942. var description;
  4943. if (meta) {
  4944. var idIndex = meta.indexOf(I18N_ID_SEPARATOR);
  4945. var descIndex = meta.indexOf(I18N_MEANING_SEPARATOR);
  4946. var meaningAndDesc = void 0;
  4947. _a = __read((idIndex > -1) ? [meta.slice(0, idIndex), meta.slice(idIndex + 2)] : [meta, ''], 2), meaningAndDesc = _a[0], id = _a[1];
  4948. _b = __read((descIndex > -1) ?
  4949. [meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] :
  4950. ['', meaningAndDesc], 2), meaning = _b[0], description = _b[1];
  4951. }
  4952. return { id: id, meaning: meaning, description: description };
  4953. }
  4954. /**
  4955. * Converts internal placeholder names to public-facing format
  4956. * (for example to use in goog.getMsg call).
  4957. * Example: `START_TAG_DIV_1` is converted to `startTagDiv_1`.
  4958. *
  4959. * @param name The placeholder name that should be formatted
  4960. * @returns Formatted placeholder name
  4961. */
  4962. function formatI18nPlaceholderName(name) {
  4963. var chunks = toPublicName(name).split('_');
  4964. if (chunks.length === 1) {
  4965. // if no "_" found - just lowercase the value
  4966. return name.toLowerCase();
  4967. }
  4968. var postfix;
  4969. // eject last element if it's a number
  4970. if (/^\d+$/.test(chunks[chunks.length - 1])) {
  4971. postfix = chunks.pop();
  4972. }
  4973. var raw = chunks.shift().toLowerCase();
  4974. if (chunks.length) {
  4975. raw += chunks.map(function (c) { return c.charAt(0).toUpperCase() + c.slice(1).toLowerCase(); }).join('');
  4976. }
  4977. return postfix ? raw + "_" + postfix : raw;
  4978. }
  4979. /**
  4980. * Generates a prefix for translation const name.
  4981. *
  4982. * @param extra Additional local prefix that should be injected into translation var name
  4983. * @returns Complete translation const prefix
  4984. */
  4985. function getTranslationConstPrefix(extra) {
  4986. return ("" + CLOSURE_TRANSLATION_PREFIX + extra).toUpperCase();
  4987. }
  4988. /**
  4989. * Generates translation declaration statements.
  4990. *
  4991. * @param variable Translation value reference
  4992. * @param closureVar Variable for Closure `goog.getMsg` calls
  4993. * @param message Text message to be translated
  4994. * @param meta Object that contains meta information (id, meaning and description)
  4995. * @param params Object with placeholders key-value pairs
  4996. * @param transformFn Optional transformation (post processing) function reference
  4997. * @returns Array of Statements that represent a given translation
  4998. */
  4999. function getTranslationDeclStmts(variable, closureVar, message, meta, params, transformFn) {
  5000. if (params === void 0) { params = {}; }
  5001. var statements = [];
  5002. statements.push.apply(statements, __spread(i18nTranslationToDeclStmt(variable, closureVar, message, meta, params)));
  5003. if (transformFn) {
  5004. statements.push(new ExpressionStatement(variable.set(transformFn(variable))));
  5005. }
  5006. return statements;
  5007. }
  5008. /**
  5009. * @license
  5010. * Copyright Google Inc. All Rights Reserved.
  5011. *
  5012. * Use of this source code is governed by an MIT-style license that can be
  5013. * found in the LICENSE file at https://angular.io/license
  5014. */
  5015. /**
  5016. * Checks whether an object key contains potentially unsafe chars, thus the key should be wrapped in
  5017. * quotes. Note: we do not wrap all keys into quotes, as it may have impact on minification and may
  5018. * bot work in some cases when object keys are mangled by minifier.
  5019. *
  5020. * TODO(FW-1136): this is a temporary solution, we need to come up with a better way of working with
  5021. * inputs that contain potentially unsafe chars.
  5022. */
  5023. var UNSAFE_OBJECT_KEY_NAME_REGEXP = /[-.]/;
  5024. /** Name of the temporary to use during data binding */
  5025. var TEMPORARY_NAME = '_t';
  5026. /** Name of the context parameter passed into a template function */
  5027. var CONTEXT_NAME = 'ctx';
  5028. /** Name of the RenderFlag passed into a template function */
  5029. var RENDER_FLAGS = 'rf';
  5030. /** The prefix reference variables */
  5031. var REFERENCE_PREFIX = '_r';
  5032. /** The name of the implicit context reference */
  5033. var IMPLICIT_REFERENCE = '$implicit';
  5034. /** Non bindable attribute name **/
  5035. var NON_BINDABLE_ATTR = 'ngNonBindable';
  5036. /**
  5037. * Creates an allocator for a temporary variable.
  5038. *
  5039. * A variable declaration is added to the statements the first time the allocator is invoked.
  5040. */
  5041. function temporaryAllocator(statements, name) {
  5042. var temp = null;
  5043. return function () {
  5044. if (!temp) {
  5045. statements.push(new DeclareVarStmt(TEMPORARY_NAME, undefined, DYNAMIC_TYPE));
  5046. temp = variable(name);
  5047. }
  5048. return temp;
  5049. };
  5050. }
  5051. function unsupported(feature) {
  5052. if (this) {
  5053. throw new Error("Builder " + this.constructor.name + " doesn't support " + feature + " yet");
  5054. }
  5055. throw new Error("Feature " + feature + " is not supported yet");
  5056. }
  5057. function invalid$1(arg) {
  5058. throw new Error("Invalid state: Visitor " + this.constructor.name + " doesn't handle " + arg.constructor.name);
  5059. }
  5060. function asLiteral(value) {
  5061. if (Array.isArray(value)) {
  5062. return literalArr(value.map(asLiteral));
  5063. }
  5064. return literal(value, INFERRED_TYPE);
  5065. }
  5066. function conditionallyCreateMapObjectLiteral(keys, keepDeclared) {
  5067. if (Object.getOwnPropertyNames(keys).length > 0) {
  5068. return mapToExpression(keys, keepDeclared);
  5069. }
  5070. return null;
  5071. }
  5072. function mapToExpression(map, keepDeclared) {
  5073. return literalMap(Object.getOwnPropertyNames(map).map(function (key) {
  5074. var _a, _b;
  5075. // canonical syntax: `dirProp: publicProp`
  5076. // if there is no `:`, use dirProp = elProp
  5077. var value = map[key];
  5078. var declaredName;
  5079. var publicName;
  5080. var minifiedName;
  5081. if (Array.isArray(value)) {
  5082. _a = __read(value, 2), publicName = _a[0], declaredName = _a[1];
  5083. }
  5084. else {
  5085. _b = __read(splitAtColon(key, [key, value]), 2), declaredName = _b[0], publicName = _b[1];
  5086. }
  5087. minifiedName = declaredName;
  5088. return {
  5089. key: minifiedName,
  5090. // put quotes around keys that contain potentially unsafe characters
  5091. quoted: UNSAFE_OBJECT_KEY_NAME_REGEXP.test(minifiedName),
  5092. value: (keepDeclared && publicName !== declaredName) ?
  5093. literalArr([asLiteral(publicName), asLiteral(declaredName)]) :
  5094. asLiteral(publicName)
  5095. };
  5096. }));
  5097. }
  5098. /**
  5099. * Remove trailing null nodes as they are implied.
  5100. */
  5101. function trimTrailingNulls(parameters) {
  5102. while (isNull(parameters[parameters.length - 1])) {
  5103. parameters.pop();
  5104. }
  5105. return parameters;
  5106. }
  5107. function getQueryPredicate(query, constantPool) {
  5108. if (Array.isArray(query.predicate)) {
  5109. var predicate_1 = [];
  5110. query.predicate.forEach(function (selector) {
  5111. // Each item in predicates array may contain strings with comma-separated refs
  5112. // (for ex. 'ref, ref1, ..., refN'), thus we extract individual refs and store them
  5113. // as separate array entities
  5114. var selectors = selector.split(',').map(function (token) { return literal(token.trim()); });
  5115. predicate_1.push.apply(predicate_1, __spread(selectors));
  5116. });
  5117. return constantPool.getConstLiteral(literalArr(predicate_1), true);
  5118. }
  5119. else {
  5120. return query.predicate;
  5121. }
  5122. }
  5123. var DefinitionMap = /** @class */ (function () {
  5124. function DefinitionMap() {
  5125. this.values = [];
  5126. }
  5127. DefinitionMap.prototype.set = function (key, value) {
  5128. if (value) {
  5129. this.values.push({ key: key, value: value, quoted: false });
  5130. }
  5131. };
  5132. DefinitionMap.prototype.toLiteralMap = function () { return literalMap(this.values); };
  5133. return DefinitionMap;
  5134. }());
  5135. /**
  5136. * Extract a map of properties to values for a given element or template node, which can be used
  5137. * by the directive matching machinery.
  5138. *
  5139. * @param elOrTpl the element or template in question
  5140. * @return an object set up for directive matching. For attributes on the element/template, this
  5141. * object maps a property name to its (static) value. For any bindings, this map simply maps the
  5142. * property name to an empty string.
  5143. */
  5144. function getAttrsForDirectiveMatching(elOrTpl) {
  5145. var attributesMap = {};
  5146. if (elOrTpl instanceof Template && elOrTpl.tagName !== 'ng-template') {
  5147. elOrTpl.templateAttrs.forEach(function (a) { return attributesMap[a.name] = ''; });
  5148. }
  5149. else {
  5150. elOrTpl.attributes.forEach(function (a) {
  5151. if (!isI18nAttribute(a.name)) {
  5152. attributesMap[a.name] = a.value;
  5153. }
  5154. });
  5155. elOrTpl.inputs.forEach(function (i) { attributesMap[i.name] = ''; });
  5156. elOrTpl.outputs.forEach(function (o) { attributesMap[o.name] = ''; });
  5157. }
  5158. return attributesMap;
  5159. }
  5160. /**
  5161. * @license
  5162. * Copyright Google Inc. All Rights Reserved.
  5163. *
  5164. * Use of this source code is governed by an MIT-style license that can be
  5165. * found in the LICENSE file at https://angular.io/license
  5166. */
  5167. var R3FactoryDelegateType;
  5168. (function (R3FactoryDelegateType) {
  5169. R3FactoryDelegateType[R3FactoryDelegateType["Class"] = 0] = "Class";
  5170. R3FactoryDelegateType[R3FactoryDelegateType["Function"] = 1] = "Function";
  5171. R3FactoryDelegateType[R3FactoryDelegateType["Factory"] = 2] = "Factory";
  5172. })(R3FactoryDelegateType || (R3FactoryDelegateType = {}));
  5173. (function (R3ResolvedDependencyType) {
  5174. /**
  5175. * A normal token dependency.
  5176. */
  5177. R3ResolvedDependencyType[R3ResolvedDependencyType["Token"] = 0] = "Token";
  5178. /**
  5179. * The dependency is for an attribute.
  5180. *
  5181. * The token expression is a string representing the attribute name.
  5182. */
  5183. R3ResolvedDependencyType[R3ResolvedDependencyType["Attribute"] = 1] = "Attribute";
  5184. })(exports.R3ResolvedDependencyType || (exports.R3ResolvedDependencyType = {}));
  5185. /**
  5186. * Construct a factory function expression for the given `R3FactoryMetadata`.
  5187. */
  5188. function compileFactoryFunction(meta) {
  5189. var t = variable('t');
  5190. var statements = [];
  5191. // The type to instantiate via constructor invocation. If there is no delegated factory, meaning
  5192. // this type is always created by constructor invocation, then this is the type-to-create
  5193. // parameter provided by the user (t) if specified, or the current type if not. If there is a
  5194. // delegated factory (which is used to create the current type) then this is only the type-to-
  5195. // create parameter (t).
  5196. var typeForCtor = !isDelegatedMetadata(meta) ? new BinaryOperatorExpr(exports.BinaryOperator.Or, t, meta.type) : t;
  5197. var ctorExpr = null;
  5198. if (meta.deps !== null) {
  5199. // There is a constructor (either explicitly or implicitly defined).
  5200. if (meta.deps !== 'invalid') {
  5201. ctorExpr = new InstantiateExpr(typeForCtor, injectDependencies(meta.deps, meta.injectFn));
  5202. }
  5203. }
  5204. else {
  5205. var baseFactory = variable("\u0275" + meta.name + "_BaseFactory");
  5206. var getInheritedFactory = importExpr(Identifiers$1.getInheritedFactory);
  5207. var baseFactoryStmt = baseFactory.set(getInheritedFactory.callFn([meta.type])).toDeclStmt(INFERRED_TYPE, [
  5208. exports.StmtModifier.Exported, exports.StmtModifier.Final
  5209. ]);
  5210. statements.push(baseFactoryStmt);
  5211. // There is no constructor, use the base class' factory to construct typeForCtor.
  5212. ctorExpr = baseFactory.callFn([typeForCtor]);
  5213. }
  5214. var ctorExprFinal = ctorExpr;
  5215. var body = [];
  5216. var retExpr = null;
  5217. function makeConditionalFactory(nonCtorExpr) {
  5218. var r = variable('r');
  5219. body.push(r.set(NULL_EXPR).toDeclStmt());
  5220. var ctorStmt = null;
  5221. if (ctorExprFinal !== null) {
  5222. ctorStmt = r.set(ctorExprFinal).toStmt();
  5223. }
  5224. else {
  5225. ctorStmt = makeErrorStmt(meta.name);
  5226. }
  5227. body.push(ifStmt(t, [ctorStmt], [r.set(nonCtorExpr).toStmt()]));
  5228. return r;
  5229. }
  5230. if (isDelegatedMetadata(meta) && meta.delegateType === R3FactoryDelegateType.Factory) {
  5231. var delegateFactory = variable("\u0275" + meta.name + "_BaseFactory");
  5232. var getFactoryOf = importExpr(Identifiers$1.getFactoryOf);
  5233. if (meta.delegate.isEquivalent(meta.type)) {
  5234. throw new Error("Illegal state: compiling factory that delegates to itself");
  5235. }
  5236. var delegateFactoryStmt = delegateFactory.set(getFactoryOf.callFn([meta.delegate])).toDeclStmt(INFERRED_TYPE, [
  5237. exports.StmtModifier.Exported, exports.StmtModifier.Final
  5238. ]);
  5239. statements.push(delegateFactoryStmt);
  5240. retExpr = makeConditionalFactory(delegateFactory.callFn([]));
  5241. }
  5242. else if (isDelegatedMetadata(meta)) {
  5243. // This type is created with a delegated factory. If a type parameter is not specified, call
  5244. // the factory instead.
  5245. var delegateArgs = injectDependencies(meta.delegateDeps, meta.injectFn);
  5246. // Either call `new delegate(...)` or `delegate(...)` depending on meta.useNewForDelegate.
  5247. var factoryExpr = new (meta.delegateType === R3FactoryDelegateType.Class ?
  5248. InstantiateExpr :
  5249. InvokeFunctionExpr)(meta.delegate, delegateArgs);
  5250. retExpr = makeConditionalFactory(factoryExpr);
  5251. }
  5252. else if (isExpressionFactoryMetadata(meta)) {
  5253. // TODO(alxhub): decide whether to lower the value here or in the caller
  5254. retExpr = makeConditionalFactory(meta.expression);
  5255. }
  5256. else {
  5257. retExpr = ctorExpr;
  5258. }
  5259. if (retExpr !== null) {
  5260. body.push(new ReturnStatement(retExpr));
  5261. }
  5262. else {
  5263. body.push(makeErrorStmt(meta.name));
  5264. }
  5265. return {
  5266. factory: fn([new FnParam('t', DYNAMIC_TYPE)], body, INFERRED_TYPE, undefined, meta.name + "_Factory"),
  5267. statements: statements,
  5268. };
  5269. }
  5270. function injectDependencies(deps, injectFn) {
  5271. return deps.map(function (dep) { return compileInjectDependency(dep, injectFn); });
  5272. }
  5273. function compileInjectDependency(dep, injectFn) {
  5274. // Interpret the dependency according to its resolved type.
  5275. switch (dep.resolved) {
  5276. case exports.R3ResolvedDependencyType.Token: {
  5277. // Build up the injection flags according to the metadata.
  5278. var flags = 0 /* Default */ | (dep.self ? 2 /* Self */ : 0) |
  5279. (dep.skipSelf ? 4 /* SkipSelf */ : 0) | (dep.host ? 1 /* Host */ : 0) |
  5280. (dep.optional ? 8 /* Optional */ : 0);
  5281. // Build up the arguments to the injectFn call.
  5282. var injectArgs = [dep.token];
  5283. // If this dependency is optional or otherwise has non-default flags, then additional
  5284. // parameters describing how to inject the dependency must be passed to the inject function
  5285. // that's being used.
  5286. if (flags !== 0 /* Default */ || dep.optional) {
  5287. injectArgs.push(literal(flags));
  5288. }
  5289. return importExpr(injectFn).callFn(injectArgs);
  5290. }
  5291. case exports.R3ResolvedDependencyType.Attribute:
  5292. // In the case of attributes, the attribute name in question is given as the token.
  5293. return importExpr(Identifiers$1.injectAttribute).callFn([dep.token]);
  5294. default:
  5295. return unsupported("Unknown R3ResolvedDependencyType: " + exports.R3ResolvedDependencyType[dep.resolved]);
  5296. }
  5297. }
  5298. /**
  5299. * A helper function useful for extracting `R3DependencyMetadata` from a Render2
  5300. * `CompileTypeMetadata` instance.
  5301. */
  5302. function dependenciesFromGlobalMetadata(type, outputCtx, reflector) {
  5303. var e_1, _a;
  5304. // Use the `CompileReflector` to look up references to some well-known Angular types. These will
  5305. // be compared with the token to statically determine whether the token has significance to
  5306. // Angular, and set the correct `R3ResolvedDependencyType` as a result.
  5307. var injectorRef = reflector.resolveExternalReference(Identifiers.Injector);
  5308. // Iterate through the type's DI dependencies and produce `R3DependencyMetadata` for each of them.
  5309. var deps = [];
  5310. try {
  5311. for (var _b = __values(type.diDeps), _c = _b.next(); !_c.done; _c = _b.next()) {
  5312. var dependency = _c.value;
  5313. if (dependency.token) {
  5314. var tokenRef = tokenReference(dependency.token);
  5315. var resolved = dependency.isAttribute ?
  5316. exports.R3ResolvedDependencyType.Attribute :
  5317. exports.R3ResolvedDependencyType.Token;
  5318. // In the case of most dependencies, the token will be a reference to a type. Sometimes,
  5319. // however, it can be a string, in the case of older Angular code or @Attribute injection.
  5320. var token = tokenRef instanceof StaticSymbol ? outputCtx.importExpr(tokenRef) : literal(tokenRef);
  5321. // Construct the dependency.
  5322. deps.push({
  5323. token: token,
  5324. resolved: resolved,
  5325. host: !!dependency.isHost,
  5326. optional: !!dependency.isOptional,
  5327. self: !!dependency.isSelf,
  5328. skipSelf: !!dependency.isSkipSelf,
  5329. });
  5330. }
  5331. else {
  5332. unsupported('dependency without a token');
  5333. }
  5334. }
  5335. }
  5336. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  5337. finally {
  5338. try {
  5339. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  5340. }
  5341. finally { if (e_1) throw e_1.error; }
  5342. }
  5343. return deps;
  5344. }
  5345. function makeErrorStmt(name) {
  5346. return new ThrowStmt(new InstantiateExpr(new ReadVarExpr('Error'), [
  5347. literal(name + " has a constructor which is not compatible with Dependency Injection. It should probably not be @Injectable().")
  5348. ]));
  5349. }
  5350. function isDelegatedMetadata(meta) {
  5351. return meta.delegateType !== undefined;
  5352. }
  5353. function isExpressionFactoryMetadata(meta) {
  5354. return meta.expression !== undefined;
  5355. }
  5356. /**
  5357. * @license
  5358. * Copyright Google Inc. All Rights Reserved.
  5359. *
  5360. * Use of this source code is governed by an MIT-style license that can be
  5361. * found in the LICENSE file at https://angular.io/license
  5362. */
  5363. /**
  5364. * Convert an object map with `Expression` values into a `LiteralMapExpr`.
  5365. */
  5366. function mapToMapExpression(map) {
  5367. var result = Object.keys(map).map(function (key) { return ({ key: key, value: map[key], quoted: false }); });
  5368. return literalMap(result);
  5369. }
  5370. /**
  5371. * Convert metadata into an `Expression` in the given `OutputContext`.
  5372. *
  5373. * This operation will handle arrays, references to symbols, or literal `null` or `undefined`.
  5374. */
  5375. function convertMetaToOutput(meta, ctx) {
  5376. if (Array.isArray(meta)) {
  5377. return literalArr(meta.map(function (entry) { return convertMetaToOutput(entry, ctx); }));
  5378. }
  5379. if (meta instanceof StaticSymbol) {
  5380. return ctx.importExpr(meta);
  5381. }
  5382. if (meta == null) {
  5383. return literal(meta);
  5384. }
  5385. throw new Error("Internal error: Unsupported or unknown metadata: " + meta);
  5386. }
  5387. function typeWithParameters(type, numParams) {
  5388. var params = null;
  5389. if (numParams > 0) {
  5390. params = [];
  5391. for (var i = 0; i < numParams; i++) {
  5392. params.push(DYNAMIC_TYPE);
  5393. }
  5394. }
  5395. return expressionType(type, null, params);
  5396. }
  5397. var ANIMATE_SYMBOL_PREFIX = '@';
  5398. function prepareSyntheticPropertyName(name) {
  5399. return "" + ANIMATE_SYMBOL_PREFIX + name;
  5400. }
  5401. function prepareSyntheticListenerName(name, phase) {
  5402. return "" + ANIMATE_SYMBOL_PREFIX + name + "." + phase;
  5403. }
  5404. function prepareSyntheticListenerFunctionName(name, phase) {
  5405. return "animation_" + name + "_" + phase;
  5406. }
  5407. /**
  5408. * @license
  5409. * Copyright Google Inc. All Rights Reserved.
  5410. *
  5411. * Use of this source code is governed by an MIT-style license that can be
  5412. * found in the LICENSE file at https://angular.io/license
  5413. */
  5414. function compileInjectable(meta) {
  5415. var result = null;
  5416. var factoryMeta = {
  5417. name: meta.name,
  5418. type: meta.type,
  5419. deps: meta.ctorDeps,
  5420. injectFn: Identifiers.inject,
  5421. };
  5422. if (meta.useClass !== undefined) {
  5423. // meta.useClass has two modes of operation. Either deps are specified, in which case `new` is
  5424. // used to instantiate the class with dependencies injected, or deps are not specified and
  5425. // the factory of the class is used to instantiate it.
  5426. //
  5427. // A special case exists for useClass: Type where Type is the injectable type itself and no
  5428. // deps are specified, in which case 'useClass' is effectively ignored.
  5429. var useClassOnSelf = meta.useClass.isEquivalent(meta.type);
  5430. var deps = undefined;
  5431. if (meta.userDeps !== undefined) {
  5432. deps = meta.userDeps;
  5433. }
  5434. if (deps !== undefined) {
  5435. // factory: () => new meta.useClass(...deps)
  5436. result = compileFactoryFunction(__assign({}, factoryMeta, { delegate: meta.useClass, delegateDeps: deps, delegateType: R3FactoryDelegateType.Class }));
  5437. }
  5438. else if (useClassOnSelf) {
  5439. result = compileFactoryFunction(factoryMeta);
  5440. }
  5441. else {
  5442. result = compileFactoryFunction(__assign({}, factoryMeta, { delegate: meta.useClass, delegateType: R3FactoryDelegateType.Factory }));
  5443. }
  5444. }
  5445. else if (meta.useFactory !== undefined) {
  5446. result = compileFactoryFunction(__assign({}, factoryMeta, { delegate: meta.useFactory, delegateDeps: meta.userDeps || [], delegateType: R3FactoryDelegateType.Function }));
  5447. }
  5448. else if (meta.useValue !== undefined) {
  5449. // Note: it's safe to use `meta.useValue` instead of the `USE_VALUE in meta` check used for
  5450. // client code because meta.useValue is an Expression which will be defined even if the actual
  5451. // value is undefined.
  5452. result = compileFactoryFunction(__assign({}, factoryMeta, { expression: meta.useValue }));
  5453. }
  5454. else if (meta.useExisting !== undefined) {
  5455. // useExisting is an `inject` call on the existing token.
  5456. result = compileFactoryFunction(__assign({}, factoryMeta, { expression: importExpr(Identifiers.inject).callFn([meta.useExisting]) }));
  5457. }
  5458. else {
  5459. result = compileFactoryFunction(factoryMeta);
  5460. }
  5461. var token = meta.type;
  5462. var providedIn = meta.providedIn;
  5463. var expression = importExpr(Identifiers.ɵɵdefineInjectable).callFn([mapToMapExpression({ token: token, factory: result.factory, providedIn: providedIn })]);
  5464. var type = new ExpressionType(importExpr(Identifiers.InjectableDef, [typeWithParameters(meta.type, meta.typeArgumentCount)]));
  5465. return {
  5466. expression: expression,
  5467. type: type,
  5468. statements: result.statements,
  5469. };
  5470. }
  5471. /**
  5472. * @license
  5473. * Copyright Google Inc. All Rights Reserved.
  5474. *
  5475. * Use of this source code is governed by an MIT-style license that can be
  5476. * found in the LICENSE file at https://angular.io/license
  5477. */
  5478. function assertArrayOfStrings(identifier, value) {
  5479. if (value == null) {
  5480. return;
  5481. }
  5482. if (!Array.isArray(value)) {
  5483. throw new Error("Expected '" + identifier + "' to be an array of strings.");
  5484. }
  5485. for (var i = 0; i < value.length; i += 1) {
  5486. if (typeof value[i] !== 'string') {
  5487. throw new Error("Expected '" + identifier + "' to be an array of strings.");
  5488. }
  5489. }
  5490. }
  5491. var UNUSABLE_INTERPOLATION_REGEXPS = [
  5492. /^\s*$/,
  5493. /[<>]/,
  5494. /^[{}]$/,
  5495. /&(#|[a-z])/i,
  5496. /^\/\//,
  5497. ];
  5498. function assertInterpolationSymbols(identifier, value) {
  5499. if (value != null && !(Array.isArray(value) && value.length == 2)) {
  5500. throw new Error("Expected '" + identifier + "' to be an array, [start, end].");
  5501. }
  5502. else if (value != null) {
  5503. var start_1 = value[0];
  5504. var end_1 = value[1];
  5505. // Check for unusable interpolation symbols
  5506. UNUSABLE_INTERPOLATION_REGEXPS.forEach(function (regexp) {
  5507. if (regexp.test(start_1) || regexp.test(end_1)) {
  5508. throw new Error("['" + start_1 + "', '" + end_1 + "'] contains unusable interpolation symbol.");
  5509. }
  5510. });
  5511. }
  5512. }
  5513. /**
  5514. * @license
  5515. * Copyright Google Inc. All Rights Reserved.
  5516. *
  5517. * Use of this source code is governed by an MIT-style license that can be
  5518. * found in the LICENSE file at https://angular.io/license
  5519. */
  5520. var InterpolationConfig = /** @class */ (function () {
  5521. function InterpolationConfig(start, end) {
  5522. this.start = start;
  5523. this.end = end;
  5524. }
  5525. InterpolationConfig.fromArray = function (markers) {
  5526. if (!markers) {
  5527. return DEFAULT_INTERPOLATION_CONFIG;
  5528. }
  5529. assertInterpolationSymbols('interpolation', markers);
  5530. return new InterpolationConfig(markers[0], markers[1]);
  5531. };
  5532. return InterpolationConfig;
  5533. }());
  5534. var DEFAULT_INTERPOLATION_CONFIG = new InterpolationConfig('{{', '}}');
  5535. /**
  5536. * @license
  5537. * Copyright Google Inc. All Rights Reserved.
  5538. *
  5539. * Use of this source code is governed by an MIT-style license that can be
  5540. * found in the LICENSE file at https://angular.io/license
  5541. */
  5542. // https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
  5543. var VERSION = 3;
  5544. var JS_B64_PREFIX = '# sourceMappingURL=data:application/json;base64,';
  5545. var SourceMapGenerator = /** @class */ (function () {
  5546. function SourceMapGenerator(file) {
  5547. if (file === void 0) { file = null; }
  5548. this.file = file;
  5549. this.sourcesContent = new Map();
  5550. this.lines = [];
  5551. this.lastCol0 = 0;
  5552. this.hasMappings = false;
  5553. }
  5554. // The content is `null` when the content is expected to be loaded using the URL
  5555. SourceMapGenerator.prototype.addSource = function (url, content) {
  5556. if (content === void 0) { content = null; }
  5557. if (!this.sourcesContent.has(url)) {
  5558. this.sourcesContent.set(url, content);
  5559. }
  5560. return this;
  5561. };
  5562. SourceMapGenerator.prototype.addLine = function () {
  5563. this.lines.push([]);
  5564. this.lastCol0 = 0;
  5565. return this;
  5566. };
  5567. SourceMapGenerator.prototype.addMapping = function (col0, sourceUrl, sourceLine0, sourceCol0) {
  5568. if (!this.currentLine) {
  5569. throw new Error("A line must be added before mappings can be added");
  5570. }
  5571. if (sourceUrl != null && !this.sourcesContent.has(sourceUrl)) {
  5572. throw new Error("Unknown source file \"" + sourceUrl + "\"");
  5573. }
  5574. if (col0 == null) {
  5575. throw new Error("The column in the generated code must be provided");
  5576. }
  5577. if (col0 < this.lastCol0) {
  5578. throw new Error("Mapping should be added in output order");
  5579. }
  5580. if (sourceUrl && (sourceLine0 == null || sourceCol0 == null)) {
  5581. throw new Error("The source location must be provided when a source url is provided");
  5582. }
  5583. this.hasMappings = true;
  5584. this.lastCol0 = col0;
  5585. this.currentLine.push({ col0: col0, sourceUrl: sourceUrl, sourceLine0: sourceLine0, sourceCol0: sourceCol0 });
  5586. return this;
  5587. };
  5588. Object.defineProperty(SourceMapGenerator.prototype, "currentLine", {
  5589. get: function () { return this.lines.slice(-1)[0]; },
  5590. enumerable: true,
  5591. configurable: true
  5592. });
  5593. SourceMapGenerator.prototype.toJSON = function () {
  5594. var _this = this;
  5595. if (!this.hasMappings) {
  5596. return null;
  5597. }
  5598. var sourcesIndex = new Map();
  5599. var sources = [];
  5600. var sourcesContent = [];
  5601. Array.from(this.sourcesContent.keys()).forEach(function (url, i) {
  5602. sourcesIndex.set(url, i);
  5603. sources.push(url);
  5604. sourcesContent.push(_this.sourcesContent.get(url) || null);
  5605. });
  5606. var mappings = '';
  5607. var lastCol0 = 0;
  5608. var lastSourceIndex = 0;
  5609. var lastSourceLine0 = 0;
  5610. var lastSourceCol0 = 0;
  5611. this.lines.forEach(function (segments) {
  5612. lastCol0 = 0;
  5613. mappings += segments
  5614. .map(function (segment) {
  5615. // zero-based starting column of the line in the generated code
  5616. var segAsStr = toBase64VLQ(segment.col0 - lastCol0);
  5617. lastCol0 = segment.col0;
  5618. if (segment.sourceUrl != null) {
  5619. // zero-based index into the “sources” list
  5620. segAsStr +=
  5621. toBase64VLQ(sourcesIndex.get(segment.sourceUrl) - lastSourceIndex);
  5622. lastSourceIndex = sourcesIndex.get(segment.sourceUrl);
  5623. // the zero-based starting line in the original source
  5624. segAsStr += toBase64VLQ(segment.sourceLine0 - lastSourceLine0);
  5625. lastSourceLine0 = segment.sourceLine0;
  5626. // the zero-based starting column in the original source
  5627. segAsStr += toBase64VLQ(segment.sourceCol0 - lastSourceCol0);
  5628. lastSourceCol0 = segment.sourceCol0;
  5629. }
  5630. return segAsStr;
  5631. })
  5632. .join(',');
  5633. mappings += ';';
  5634. });
  5635. mappings = mappings.slice(0, -1);
  5636. return {
  5637. 'file': this.file || '',
  5638. 'version': VERSION,
  5639. 'sourceRoot': '',
  5640. 'sources': sources,
  5641. 'sourcesContent': sourcesContent,
  5642. 'mappings': mappings,
  5643. };
  5644. };
  5645. SourceMapGenerator.prototype.toJsComment = function () {
  5646. return this.hasMappings ? '//' + JS_B64_PREFIX + toBase64String(JSON.stringify(this, null, 0)) :
  5647. '';
  5648. };
  5649. return SourceMapGenerator;
  5650. }());
  5651. function toBase64String(value) {
  5652. var b64 = '';
  5653. value = utf8Encode(value);
  5654. for (var i = 0; i < value.length;) {
  5655. var i1 = value.charCodeAt(i++);
  5656. var i2 = value.charCodeAt(i++);
  5657. var i3 = value.charCodeAt(i++);
  5658. b64 += toBase64Digit(i1 >> 2);
  5659. b64 += toBase64Digit(((i1 & 3) << 4) | (isNaN(i2) ? 0 : i2 >> 4));
  5660. b64 += isNaN(i2) ? '=' : toBase64Digit(((i2 & 15) << 2) | (i3 >> 6));
  5661. b64 += isNaN(i2) || isNaN(i3) ? '=' : toBase64Digit(i3 & 63);
  5662. }
  5663. return b64;
  5664. }
  5665. function toBase64VLQ(value) {
  5666. value = value < 0 ? ((-value) << 1) + 1 : value << 1;
  5667. var out = '';
  5668. do {
  5669. var digit = value & 31;
  5670. value = value >> 5;
  5671. if (value > 0) {
  5672. digit = digit | 32;
  5673. }
  5674. out += toBase64Digit(digit);
  5675. } while (value > 0);
  5676. return out;
  5677. }
  5678. var B64_DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  5679. function toBase64Digit(value) {
  5680. if (value < 0 || value >= 64) {
  5681. throw new Error("Can only encode value in the range [0, 63]");
  5682. }
  5683. return B64_DIGITS[value];
  5684. }
  5685. /**
  5686. * @license
  5687. * Copyright Google Inc. All Rights Reserved.
  5688. *
  5689. * Use of this source code is governed by an MIT-style license that can be
  5690. * found in the LICENSE file at https://angular.io/license
  5691. */
  5692. var _SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g;
  5693. var _LEGAL_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i;
  5694. var _INDENT_WITH = ' ';
  5695. var CATCH_ERROR_VAR$1 = variable('error', null, null);
  5696. var CATCH_STACK_VAR$1 = variable('stack', null, null);
  5697. var _EmittedLine = /** @class */ (function () {
  5698. function _EmittedLine(indent) {
  5699. this.indent = indent;
  5700. this.partsLength = 0;
  5701. this.parts = [];
  5702. this.srcSpans = [];
  5703. }
  5704. return _EmittedLine;
  5705. }());
  5706. var EmitterVisitorContext = /** @class */ (function () {
  5707. function EmitterVisitorContext(_indent) {
  5708. this._indent = _indent;
  5709. this._classes = [];
  5710. this._preambleLineCount = 0;
  5711. this._lines = [new _EmittedLine(_indent)];
  5712. }
  5713. EmitterVisitorContext.createRoot = function () { return new EmitterVisitorContext(0); };
  5714. Object.defineProperty(EmitterVisitorContext.prototype, "_currentLine", {
  5715. get: function () { return this._lines[this._lines.length - 1]; },
  5716. enumerable: true,
  5717. configurable: true
  5718. });
  5719. EmitterVisitorContext.prototype.println = function (from, lastPart) {
  5720. if (lastPart === void 0) { lastPart = ''; }
  5721. this.print(from || null, lastPart, true);
  5722. };
  5723. EmitterVisitorContext.prototype.lineIsEmpty = function () { return this._currentLine.parts.length === 0; };
  5724. EmitterVisitorContext.prototype.lineLength = function () {
  5725. return this._currentLine.indent * _INDENT_WITH.length + this._currentLine.partsLength;
  5726. };
  5727. EmitterVisitorContext.prototype.print = function (from, part, newLine) {
  5728. if (newLine === void 0) { newLine = false; }
  5729. if (part.length > 0) {
  5730. this._currentLine.parts.push(part);
  5731. this._currentLine.partsLength += part.length;
  5732. this._currentLine.srcSpans.push(from && from.sourceSpan || null);
  5733. }
  5734. if (newLine) {
  5735. this._lines.push(new _EmittedLine(this._indent));
  5736. }
  5737. };
  5738. EmitterVisitorContext.prototype.removeEmptyLastLine = function () {
  5739. if (this.lineIsEmpty()) {
  5740. this._lines.pop();
  5741. }
  5742. };
  5743. EmitterVisitorContext.prototype.incIndent = function () {
  5744. this._indent++;
  5745. if (this.lineIsEmpty()) {
  5746. this._currentLine.indent = this._indent;
  5747. }
  5748. };
  5749. EmitterVisitorContext.prototype.decIndent = function () {
  5750. this._indent--;
  5751. if (this.lineIsEmpty()) {
  5752. this._currentLine.indent = this._indent;
  5753. }
  5754. };
  5755. EmitterVisitorContext.prototype.pushClass = function (clazz) { this._classes.push(clazz); };
  5756. EmitterVisitorContext.prototype.popClass = function () { return this._classes.pop(); };
  5757. Object.defineProperty(EmitterVisitorContext.prototype, "currentClass", {
  5758. get: function () {
  5759. return this._classes.length > 0 ? this._classes[this._classes.length - 1] : null;
  5760. },
  5761. enumerable: true,
  5762. configurable: true
  5763. });
  5764. EmitterVisitorContext.prototype.toSource = function () {
  5765. return this.sourceLines
  5766. .map(function (l) { return l.parts.length > 0 ? _createIndent(l.indent) + l.parts.join('') : ''; })
  5767. .join('\n');
  5768. };
  5769. EmitterVisitorContext.prototype.toSourceMapGenerator = function (genFilePath, startsAtLine) {
  5770. if (startsAtLine === void 0) { startsAtLine = 0; }
  5771. var map = new SourceMapGenerator(genFilePath);
  5772. var firstOffsetMapped = false;
  5773. var mapFirstOffsetIfNeeded = function () {
  5774. if (!firstOffsetMapped) {
  5775. // Add a single space so that tools won't try to load the file from disk.
  5776. // Note: We are using virtual urls like `ng:///`, so we have to
  5777. // provide a content here.
  5778. map.addSource(genFilePath, ' ').addMapping(0, genFilePath, 0, 0);
  5779. firstOffsetMapped = true;
  5780. }
  5781. };
  5782. for (var i = 0; i < startsAtLine; i++) {
  5783. map.addLine();
  5784. mapFirstOffsetIfNeeded();
  5785. }
  5786. this.sourceLines.forEach(function (line, lineIdx) {
  5787. map.addLine();
  5788. var spans = line.srcSpans;
  5789. var parts = line.parts;
  5790. var col0 = line.indent * _INDENT_WITH.length;
  5791. var spanIdx = 0;
  5792. // skip leading parts without source spans
  5793. while (spanIdx < spans.length && !spans[spanIdx]) {
  5794. col0 += parts[spanIdx].length;
  5795. spanIdx++;
  5796. }
  5797. if (spanIdx < spans.length && lineIdx === 0 && col0 === 0) {
  5798. firstOffsetMapped = true;
  5799. }
  5800. else {
  5801. mapFirstOffsetIfNeeded();
  5802. }
  5803. while (spanIdx < spans.length) {
  5804. var span = spans[spanIdx];
  5805. var source = span.start.file;
  5806. var sourceLine = span.start.line;
  5807. var sourceCol = span.start.col;
  5808. map.addSource(source.url, source.content)
  5809. .addMapping(col0, source.url, sourceLine, sourceCol);
  5810. col0 += parts[spanIdx].length;
  5811. spanIdx++;
  5812. // assign parts without span or the same span to the previous segment
  5813. while (spanIdx < spans.length && (span === spans[spanIdx] || !spans[spanIdx])) {
  5814. col0 += parts[spanIdx].length;
  5815. spanIdx++;
  5816. }
  5817. }
  5818. });
  5819. return map;
  5820. };
  5821. EmitterVisitorContext.prototype.setPreambleLineCount = function (count) { return this._preambleLineCount = count; };
  5822. EmitterVisitorContext.prototype.spanOf = function (line, column) {
  5823. var emittedLine = this._lines[line - this._preambleLineCount];
  5824. if (emittedLine) {
  5825. var columnsLeft = column - _createIndent(emittedLine.indent).length;
  5826. for (var partIndex = 0; partIndex < emittedLine.parts.length; partIndex++) {
  5827. var part = emittedLine.parts[partIndex];
  5828. if (part.length > columnsLeft) {
  5829. return emittedLine.srcSpans[partIndex];
  5830. }
  5831. columnsLeft -= part.length;
  5832. }
  5833. }
  5834. return null;
  5835. };
  5836. Object.defineProperty(EmitterVisitorContext.prototype, "sourceLines", {
  5837. get: function () {
  5838. if (this._lines.length && this._lines[this._lines.length - 1].parts.length === 0) {
  5839. return this._lines.slice(0, -1);
  5840. }
  5841. return this._lines;
  5842. },
  5843. enumerable: true,
  5844. configurable: true
  5845. });
  5846. return EmitterVisitorContext;
  5847. }());
  5848. var AbstractEmitterVisitor = /** @class */ (function () {
  5849. function AbstractEmitterVisitor(_escapeDollarInStrings) {
  5850. this._escapeDollarInStrings = _escapeDollarInStrings;
  5851. }
  5852. AbstractEmitterVisitor.prototype.visitExpressionStmt = function (stmt, ctx) {
  5853. stmt.expr.visitExpression(this, ctx);
  5854. ctx.println(stmt, ';');
  5855. return null;
  5856. };
  5857. AbstractEmitterVisitor.prototype.visitReturnStmt = function (stmt, ctx) {
  5858. ctx.print(stmt, "return ");
  5859. stmt.value.visitExpression(this, ctx);
  5860. ctx.println(stmt, ';');
  5861. return null;
  5862. };
  5863. AbstractEmitterVisitor.prototype.visitIfStmt = function (stmt, ctx) {
  5864. ctx.print(stmt, "if (");
  5865. stmt.condition.visitExpression(this, ctx);
  5866. ctx.print(stmt, ") {");
  5867. var hasElseCase = stmt.falseCase != null && stmt.falseCase.length > 0;
  5868. if (stmt.trueCase.length <= 1 && !hasElseCase) {
  5869. ctx.print(stmt, " ");
  5870. this.visitAllStatements(stmt.trueCase, ctx);
  5871. ctx.removeEmptyLastLine();
  5872. ctx.print(stmt, " ");
  5873. }
  5874. else {
  5875. ctx.println();
  5876. ctx.incIndent();
  5877. this.visitAllStatements(stmt.trueCase, ctx);
  5878. ctx.decIndent();
  5879. if (hasElseCase) {
  5880. ctx.println(stmt, "} else {");
  5881. ctx.incIndent();
  5882. this.visitAllStatements(stmt.falseCase, ctx);
  5883. ctx.decIndent();
  5884. }
  5885. }
  5886. ctx.println(stmt, "}");
  5887. return null;
  5888. };
  5889. AbstractEmitterVisitor.prototype.visitThrowStmt = function (stmt, ctx) {
  5890. ctx.print(stmt, "throw ");
  5891. stmt.error.visitExpression(this, ctx);
  5892. ctx.println(stmt, ";");
  5893. return null;
  5894. };
  5895. AbstractEmitterVisitor.prototype.visitCommentStmt = function (stmt, ctx) {
  5896. if (stmt.multiline) {
  5897. ctx.println(stmt, "/* " + stmt.comment + " */");
  5898. }
  5899. else {
  5900. stmt.comment.split('\n').forEach(function (line) { ctx.println(stmt, "// " + line); });
  5901. }
  5902. return null;
  5903. };
  5904. AbstractEmitterVisitor.prototype.visitJSDocCommentStmt = function (stmt, ctx) {
  5905. ctx.println(stmt, "/*" + stmt.toString() + "*/");
  5906. return null;
  5907. };
  5908. AbstractEmitterVisitor.prototype.visitWriteVarExpr = function (expr, ctx) {
  5909. var lineWasEmpty = ctx.lineIsEmpty();
  5910. if (!lineWasEmpty) {
  5911. ctx.print(expr, '(');
  5912. }
  5913. ctx.print(expr, expr.name + " = ");
  5914. expr.value.visitExpression(this, ctx);
  5915. if (!lineWasEmpty) {
  5916. ctx.print(expr, ')');
  5917. }
  5918. return null;
  5919. };
  5920. AbstractEmitterVisitor.prototype.visitWriteKeyExpr = function (expr, ctx) {
  5921. var lineWasEmpty = ctx.lineIsEmpty();
  5922. if (!lineWasEmpty) {
  5923. ctx.print(expr, '(');
  5924. }
  5925. expr.receiver.visitExpression(this, ctx);
  5926. ctx.print(expr, "[");
  5927. expr.index.visitExpression(this, ctx);
  5928. ctx.print(expr, "] = ");
  5929. expr.value.visitExpression(this, ctx);
  5930. if (!lineWasEmpty) {
  5931. ctx.print(expr, ')');
  5932. }
  5933. return null;
  5934. };
  5935. AbstractEmitterVisitor.prototype.visitWritePropExpr = function (expr, ctx) {
  5936. var lineWasEmpty = ctx.lineIsEmpty();
  5937. if (!lineWasEmpty) {
  5938. ctx.print(expr, '(');
  5939. }
  5940. expr.receiver.visitExpression(this, ctx);
  5941. ctx.print(expr, "." + expr.name + " = ");
  5942. expr.value.visitExpression(this, ctx);
  5943. if (!lineWasEmpty) {
  5944. ctx.print(expr, ')');
  5945. }
  5946. return null;
  5947. };
  5948. AbstractEmitterVisitor.prototype.visitInvokeMethodExpr = function (expr, ctx) {
  5949. expr.receiver.visitExpression(this, ctx);
  5950. var name = expr.name;
  5951. if (expr.builtin != null) {
  5952. name = this.getBuiltinMethodName(expr.builtin);
  5953. if (name == null) {
  5954. // some builtins just mean to skip the call.
  5955. return null;
  5956. }
  5957. }
  5958. ctx.print(expr, "." + name + "(");
  5959. this.visitAllExpressions(expr.args, ctx, ",");
  5960. ctx.print(expr, ")");
  5961. return null;
  5962. };
  5963. AbstractEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) {
  5964. expr.fn.visitExpression(this, ctx);
  5965. ctx.print(expr, "(");
  5966. this.visitAllExpressions(expr.args, ctx, ',');
  5967. ctx.print(expr, ")");
  5968. return null;
  5969. };
  5970. AbstractEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  5971. throw new Error('Abstract emitter cannot visit WrappedNodeExpr.');
  5972. };
  5973. AbstractEmitterVisitor.prototype.visitTypeofExpr = function (expr, ctx) {
  5974. ctx.print(expr, 'typeof ');
  5975. expr.expr.visitExpression(this, ctx);
  5976. };
  5977. AbstractEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) {
  5978. var varName = ast.name;
  5979. if (ast.builtin != null) {
  5980. switch (ast.builtin) {
  5981. case exports.BuiltinVar.Super:
  5982. varName = 'super';
  5983. break;
  5984. case exports.BuiltinVar.This:
  5985. varName = 'this';
  5986. break;
  5987. case exports.BuiltinVar.CatchError:
  5988. varName = CATCH_ERROR_VAR$1.name;
  5989. break;
  5990. case exports.BuiltinVar.CatchStack:
  5991. varName = CATCH_STACK_VAR$1.name;
  5992. break;
  5993. default:
  5994. throw new Error("Unknown builtin variable " + ast.builtin);
  5995. }
  5996. }
  5997. ctx.print(ast, varName);
  5998. return null;
  5999. };
  6000. AbstractEmitterVisitor.prototype.visitInstantiateExpr = function (ast, ctx) {
  6001. ctx.print(ast, "new ");
  6002. ast.classExpr.visitExpression(this, ctx);
  6003. ctx.print(ast, "(");
  6004. this.visitAllExpressions(ast.args, ctx, ',');
  6005. ctx.print(ast, ")");
  6006. return null;
  6007. };
  6008. AbstractEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) {
  6009. var value = ast.value;
  6010. if (typeof value === 'string') {
  6011. ctx.print(ast, escapeIdentifier(value, this._escapeDollarInStrings));
  6012. }
  6013. else {
  6014. ctx.print(ast, "" + value);
  6015. }
  6016. return null;
  6017. };
  6018. AbstractEmitterVisitor.prototype.visitConditionalExpr = function (ast, ctx) {
  6019. ctx.print(ast, "(");
  6020. ast.condition.visitExpression(this, ctx);
  6021. ctx.print(ast, '? ');
  6022. ast.trueCase.visitExpression(this, ctx);
  6023. ctx.print(ast, ': ');
  6024. ast.falseCase.visitExpression(this, ctx);
  6025. ctx.print(ast, ")");
  6026. return null;
  6027. };
  6028. AbstractEmitterVisitor.prototype.visitNotExpr = function (ast, ctx) {
  6029. ctx.print(ast, '!');
  6030. ast.condition.visitExpression(this, ctx);
  6031. return null;
  6032. };
  6033. AbstractEmitterVisitor.prototype.visitAssertNotNullExpr = function (ast, ctx) {
  6034. ast.condition.visitExpression(this, ctx);
  6035. return null;
  6036. };
  6037. AbstractEmitterVisitor.prototype.visitBinaryOperatorExpr = function (ast, ctx) {
  6038. var opStr;
  6039. switch (ast.operator) {
  6040. case exports.BinaryOperator.Equals:
  6041. opStr = '==';
  6042. break;
  6043. case exports.BinaryOperator.Identical:
  6044. opStr = '===';
  6045. break;
  6046. case exports.BinaryOperator.NotEquals:
  6047. opStr = '!=';
  6048. break;
  6049. case exports.BinaryOperator.NotIdentical:
  6050. opStr = '!==';
  6051. break;
  6052. case exports.BinaryOperator.And:
  6053. opStr = '&&';
  6054. break;
  6055. case exports.BinaryOperator.BitwiseAnd:
  6056. opStr = '&';
  6057. break;
  6058. case exports.BinaryOperator.Or:
  6059. opStr = '||';
  6060. break;
  6061. case exports.BinaryOperator.Plus:
  6062. opStr = '+';
  6063. break;
  6064. case exports.BinaryOperator.Minus:
  6065. opStr = '-';
  6066. break;
  6067. case exports.BinaryOperator.Divide:
  6068. opStr = '/';
  6069. break;
  6070. case exports.BinaryOperator.Multiply:
  6071. opStr = '*';
  6072. break;
  6073. case exports.BinaryOperator.Modulo:
  6074. opStr = '%';
  6075. break;
  6076. case exports.BinaryOperator.Lower:
  6077. opStr = '<';
  6078. break;
  6079. case exports.BinaryOperator.LowerEquals:
  6080. opStr = '<=';
  6081. break;
  6082. case exports.BinaryOperator.Bigger:
  6083. opStr = '>';
  6084. break;
  6085. case exports.BinaryOperator.BiggerEquals:
  6086. opStr = '>=';
  6087. break;
  6088. default:
  6089. throw new Error("Unknown operator " + ast.operator);
  6090. }
  6091. if (ast.parens)
  6092. ctx.print(ast, "(");
  6093. ast.lhs.visitExpression(this, ctx);
  6094. ctx.print(ast, " " + opStr + " ");
  6095. ast.rhs.visitExpression(this, ctx);
  6096. if (ast.parens)
  6097. ctx.print(ast, ")");
  6098. return null;
  6099. };
  6100. AbstractEmitterVisitor.prototype.visitReadPropExpr = function (ast, ctx) {
  6101. ast.receiver.visitExpression(this, ctx);
  6102. ctx.print(ast, ".");
  6103. ctx.print(ast, ast.name);
  6104. return null;
  6105. };
  6106. AbstractEmitterVisitor.prototype.visitReadKeyExpr = function (ast, ctx) {
  6107. ast.receiver.visitExpression(this, ctx);
  6108. ctx.print(ast, "[");
  6109. ast.index.visitExpression(this, ctx);
  6110. ctx.print(ast, "]");
  6111. return null;
  6112. };
  6113. AbstractEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) {
  6114. ctx.print(ast, "[");
  6115. this.visitAllExpressions(ast.entries, ctx, ',');
  6116. ctx.print(ast, "]");
  6117. return null;
  6118. };
  6119. AbstractEmitterVisitor.prototype.visitLiteralMapExpr = function (ast, ctx) {
  6120. var _this = this;
  6121. ctx.print(ast, "{");
  6122. this.visitAllObjects(function (entry) {
  6123. ctx.print(ast, escapeIdentifier(entry.key, _this._escapeDollarInStrings, entry.quoted) + ":");
  6124. entry.value.visitExpression(_this, ctx);
  6125. }, ast.entries, ctx, ',');
  6126. ctx.print(ast, "}");
  6127. return null;
  6128. };
  6129. AbstractEmitterVisitor.prototype.visitCommaExpr = function (ast, ctx) {
  6130. ctx.print(ast, '(');
  6131. this.visitAllExpressions(ast.parts, ctx, ',');
  6132. ctx.print(ast, ')');
  6133. return null;
  6134. };
  6135. AbstractEmitterVisitor.prototype.visitAllExpressions = function (expressions, ctx, separator) {
  6136. var _this = this;
  6137. this.visitAllObjects(function (expr) { return expr.visitExpression(_this, ctx); }, expressions, ctx, separator);
  6138. };
  6139. AbstractEmitterVisitor.prototype.visitAllObjects = function (handler, expressions, ctx, separator) {
  6140. var incrementedIndent = false;
  6141. for (var i = 0; i < expressions.length; i++) {
  6142. if (i > 0) {
  6143. if (ctx.lineLength() > 80) {
  6144. ctx.print(null, separator, true);
  6145. if (!incrementedIndent) {
  6146. // continuation are marked with double indent.
  6147. ctx.incIndent();
  6148. ctx.incIndent();
  6149. incrementedIndent = true;
  6150. }
  6151. }
  6152. else {
  6153. ctx.print(null, separator, false);
  6154. }
  6155. }
  6156. handler(expressions[i]);
  6157. }
  6158. if (incrementedIndent) {
  6159. // continuation are marked with double indent.
  6160. ctx.decIndent();
  6161. ctx.decIndent();
  6162. }
  6163. };
  6164. AbstractEmitterVisitor.prototype.visitAllStatements = function (statements, ctx) {
  6165. var _this = this;
  6166. statements.forEach(function (stmt) { return stmt.visitStatement(_this, ctx); });
  6167. };
  6168. return AbstractEmitterVisitor;
  6169. }());
  6170. function escapeIdentifier(input, escapeDollar, alwaysQuote) {
  6171. if (alwaysQuote === void 0) { alwaysQuote = true; }
  6172. if (input == null) {
  6173. return null;
  6174. }
  6175. var body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, function () {
  6176. var match = [];
  6177. for (var _i = 0; _i < arguments.length; _i++) {
  6178. match[_i] = arguments[_i];
  6179. }
  6180. if (match[0] == '$') {
  6181. return escapeDollar ? '\\$' : '$';
  6182. }
  6183. else if (match[0] == '\n') {
  6184. return '\\n';
  6185. }
  6186. else if (match[0] == '\r') {
  6187. return '\\r';
  6188. }
  6189. else {
  6190. return "\\" + match[0];
  6191. }
  6192. });
  6193. var requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body);
  6194. return requiresQuotes ? "'" + body + "'" : body;
  6195. }
  6196. function _createIndent(count) {
  6197. var res = '';
  6198. for (var i = 0; i < count; i++) {
  6199. res += _INDENT_WITH;
  6200. }
  6201. return res;
  6202. }
  6203. /**
  6204. * @license
  6205. * Copyright Google Inc. All Rights Reserved.
  6206. *
  6207. * Use of this source code is governed by an MIT-style license that can be
  6208. * found in the LICENSE file at https://angular.io/license
  6209. */
  6210. var AbstractJsEmitterVisitor = /** @class */ (function (_super) {
  6211. __extends(AbstractJsEmitterVisitor, _super);
  6212. function AbstractJsEmitterVisitor() {
  6213. return _super.call(this, false) || this;
  6214. }
  6215. AbstractJsEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
  6216. var _this = this;
  6217. ctx.pushClass(stmt);
  6218. this._visitClassConstructor(stmt, ctx);
  6219. if (stmt.parent != null) {
  6220. ctx.print(stmt, stmt.name + ".prototype = Object.create(");
  6221. stmt.parent.visitExpression(this, ctx);
  6222. ctx.println(stmt, ".prototype);");
  6223. }
  6224. stmt.getters.forEach(function (getter) { return _this._visitClassGetter(stmt, getter, ctx); });
  6225. stmt.methods.forEach(function (method) { return _this._visitClassMethod(stmt, method, ctx); });
  6226. ctx.popClass();
  6227. return null;
  6228. };
  6229. AbstractJsEmitterVisitor.prototype._visitClassConstructor = function (stmt, ctx) {
  6230. ctx.print(stmt, "function " + stmt.name + "(");
  6231. if (stmt.constructorMethod != null) {
  6232. this._visitParams(stmt.constructorMethod.params, ctx);
  6233. }
  6234. ctx.println(stmt, ") {");
  6235. ctx.incIndent();
  6236. if (stmt.constructorMethod != null) {
  6237. if (stmt.constructorMethod.body.length > 0) {
  6238. ctx.println(stmt, "var self = this;");
  6239. this.visitAllStatements(stmt.constructorMethod.body, ctx);
  6240. }
  6241. }
  6242. ctx.decIndent();
  6243. ctx.println(stmt, "}");
  6244. };
  6245. AbstractJsEmitterVisitor.prototype._visitClassGetter = function (stmt, getter, ctx) {
  6246. ctx.println(stmt, "Object.defineProperty(" + stmt.name + ".prototype, '" + getter.name + "', { get: function() {");
  6247. ctx.incIndent();
  6248. if (getter.body.length > 0) {
  6249. ctx.println(stmt, "var self = this;");
  6250. this.visitAllStatements(getter.body, ctx);
  6251. }
  6252. ctx.decIndent();
  6253. ctx.println(stmt, "}});");
  6254. };
  6255. AbstractJsEmitterVisitor.prototype._visitClassMethod = function (stmt, method, ctx) {
  6256. ctx.print(stmt, stmt.name + ".prototype." + method.name + " = function(");
  6257. this._visitParams(method.params, ctx);
  6258. ctx.println(stmt, ") {");
  6259. ctx.incIndent();
  6260. if (method.body.length > 0) {
  6261. ctx.println(stmt, "var self = this;");
  6262. this.visitAllStatements(method.body, ctx);
  6263. }
  6264. ctx.decIndent();
  6265. ctx.println(stmt, "};");
  6266. };
  6267. AbstractJsEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  6268. throw new Error('Cannot emit a WrappedNodeExpr in Javascript.');
  6269. };
  6270. AbstractJsEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) {
  6271. if (ast.builtin === exports.BuiltinVar.This) {
  6272. ctx.print(ast, 'self');
  6273. }
  6274. else if (ast.builtin === exports.BuiltinVar.Super) {
  6275. throw new Error("'super' needs to be handled at a parent ast node, not at the variable level!");
  6276. }
  6277. else {
  6278. _super.prototype.visitReadVarExpr.call(this, ast, ctx);
  6279. }
  6280. return null;
  6281. };
  6282. AbstractJsEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
  6283. ctx.print(stmt, "var " + stmt.name);
  6284. if (stmt.value) {
  6285. ctx.print(stmt, ' = ');
  6286. stmt.value.visitExpression(this, ctx);
  6287. }
  6288. ctx.println(stmt, ";");
  6289. return null;
  6290. };
  6291. AbstractJsEmitterVisitor.prototype.visitCastExpr = function (ast, ctx) {
  6292. ast.value.visitExpression(this, ctx);
  6293. return null;
  6294. };
  6295. AbstractJsEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) {
  6296. var fnExpr = expr.fn;
  6297. if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === exports.BuiltinVar.Super) {
  6298. ctx.currentClass.parent.visitExpression(this, ctx);
  6299. ctx.print(expr, ".call(this");
  6300. if (expr.args.length > 0) {
  6301. ctx.print(expr, ", ");
  6302. this.visitAllExpressions(expr.args, ctx, ',');
  6303. }
  6304. ctx.print(expr, ")");
  6305. }
  6306. else {
  6307. _super.prototype.visitInvokeFunctionExpr.call(this, expr, ctx);
  6308. }
  6309. return null;
  6310. };
  6311. AbstractJsEmitterVisitor.prototype.visitFunctionExpr = function (ast, ctx) {
  6312. ctx.print(ast, "function" + (ast.name ? ' ' + ast.name : '') + "(");
  6313. this._visitParams(ast.params, ctx);
  6314. ctx.println(ast, ") {");
  6315. ctx.incIndent();
  6316. this.visitAllStatements(ast.statements, ctx);
  6317. ctx.decIndent();
  6318. ctx.print(ast, "}");
  6319. return null;
  6320. };
  6321. AbstractJsEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
  6322. ctx.print(stmt, "function " + stmt.name + "(");
  6323. this._visitParams(stmt.params, ctx);
  6324. ctx.println(stmt, ") {");
  6325. ctx.incIndent();
  6326. this.visitAllStatements(stmt.statements, ctx);
  6327. ctx.decIndent();
  6328. ctx.println(stmt, "}");
  6329. return null;
  6330. };
  6331. AbstractJsEmitterVisitor.prototype.visitTryCatchStmt = function (stmt, ctx) {
  6332. ctx.println(stmt, "try {");
  6333. ctx.incIndent();
  6334. this.visitAllStatements(stmt.bodyStmts, ctx);
  6335. ctx.decIndent();
  6336. ctx.println(stmt, "} catch (" + CATCH_ERROR_VAR$1.name + ") {");
  6337. ctx.incIndent();
  6338. var catchStmts = [CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack')).toDeclStmt(null, [
  6339. exports.StmtModifier.Final
  6340. ])].concat(stmt.catchStmts);
  6341. this.visitAllStatements(catchStmts, ctx);
  6342. ctx.decIndent();
  6343. ctx.println(stmt, "}");
  6344. return null;
  6345. };
  6346. AbstractJsEmitterVisitor.prototype._visitParams = function (params, ctx) {
  6347. this.visitAllObjects(function (param) { return ctx.print(null, param.name); }, params, ctx, ',');
  6348. };
  6349. AbstractJsEmitterVisitor.prototype.getBuiltinMethodName = function (method) {
  6350. var name;
  6351. switch (method) {
  6352. case exports.BuiltinMethod.ConcatArray:
  6353. name = 'concat';
  6354. break;
  6355. case exports.BuiltinMethod.SubscribeObservable:
  6356. name = 'subscribe';
  6357. break;
  6358. case exports.BuiltinMethod.Bind:
  6359. name = 'bind';
  6360. break;
  6361. default:
  6362. throw new Error("Unknown builtin method: " + method);
  6363. }
  6364. return name;
  6365. };
  6366. return AbstractJsEmitterVisitor;
  6367. }(AbstractEmitterVisitor));
  6368. /**
  6369. * @license
  6370. * Copyright Google Inc. All Rights Reserved.
  6371. *
  6372. * Use of this source code is governed by an MIT-style license that can be
  6373. * found in the LICENSE file at https://angular.io/license
  6374. */
  6375. /**
  6376. * A helper class to manage the evaluation of JIT generated code.
  6377. */
  6378. var JitEvaluator = /** @class */ (function () {
  6379. function JitEvaluator() {
  6380. }
  6381. /**
  6382. *
  6383. * @param sourceUrl The URL of the generated code.
  6384. * @param statements An array of Angular statement AST nodes to be evaluated.
  6385. * @param reflector A helper used when converting the statements to executable code.
  6386. * @param createSourceMaps If true then create a source-map for the generated code and include it
  6387. * inline as a source-map comment.
  6388. * @returns A map of all the variables in the generated code.
  6389. */
  6390. JitEvaluator.prototype.evaluateStatements = function (sourceUrl, statements, reflector, createSourceMaps) {
  6391. var converter = new JitEmitterVisitor(reflector);
  6392. var ctx = EmitterVisitorContext.createRoot();
  6393. // Ensure generated code is in strict mode
  6394. if (statements.length > 0 && !isUseStrictStatement(statements[0])) {
  6395. statements = __spread([
  6396. literal('use strict').toStmt()
  6397. ], statements);
  6398. }
  6399. converter.visitAllStatements(statements, ctx);
  6400. converter.createReturnStmt(ctx);
  6401. return this.evaluateCode(sourceUrl, ctx, converter.getArgs(), createSourceMaps);
  6402. };
  6403. /**
  6404. * Evaluate a piece of JIT generated code.
  6405. * @param sourceUrl The URL of this generated code.
  6406. * @param ctx A context object that contains an AST of the code to be evaluated.
  6407. * @param vars A map containing the names and values of variables that the evaluated code might
  6408. * reference.
  6409. * @param createSourceMap If true then create a source-map for the generated code and include it
  6410. * inline as a source-map comment.
  6411. * @returns The result of evaluating the code.
  6412. */
  6413. JitEvaluator.prototype.evaluateCode = function (sourceUrl, ctx, vars, createSourceMap) {
  6414. var fnBody = "\"use strict\";" + ctx.toSource() + "\n//# sourceURL=" + sourceUrl;
  6415. var fnArgNames = [];
  6416. var fnArgValues = [];
  6417. for (var argName in vars) {
  6418. fnArgValues.push(vars[argName]);
  6419. fnArgNames.push(argName);
  6420. }
  6421. if (createSourceMap) {
  6422. // using `new Function(...)` generates a header, 1 line of no arguments, 2 lines otherwise
  6423. // E.g. ```
  6424. // function anonymous(a,b,c
  6425. // /**/) { ... }```
  6426. // We don't want to hard code this fact, so we auto detect it via an empty function first.
  6427. var emptyFn = new (Function.bind.apply(Function, __spread([void 0], fnArgNames.concat('return null;'))))().toString();
  6428. var headerLines = emptyFn.slice(0, emptyFn.indexOf('return null;')).split('\n').length - 1;
  6429. fnBody += "\n" + ctx.toSourceMapGenerator(sourceUrl, headerLines).toJsComment();
  6430. }
  6431. var fn = new (Function.bind.apply(Function, __spread([void 0], fnArgNames.concat(fnBody))))();
  6432. return this.executeFunction(fn, fnArgValues);
  6433. };
  6434. /**
  6435. * Execute a JIT generated function by calling it.
  6436. *
  6437. * This method can be overridden in tests to capture the functions that are generated
  6438. * by this `JitEvaluator` class.
  6439. *
  6440. * @param fn A function to execute.
  6441. * @param args The arguments to pass to the function being executed.
  6442. * @returns The return value of the executed function.
  6443. */
  6444. JitEvaluator.prototype.executeFunction = function (fn, args) { return fn.apply(void 0, __spread(args)); };
  6445. return JitEvaluator;
  6446. }());
  6447. /**
  6448. * An Angular AST visitor that converts AST nodes into executable JavaScript code.
  6449. */
  6450. var JitEmitterVisitor = /** @class */ (function (_super) {
  6451. __extends(JitEmitterVisitor, _super);
  6452. function JitEmitterVisitor(reflector) {
  6453. var _this = _super.call(this) || this;
  6454. _this.reflector = reflector;
  6455. _this._evalArgNames = [];
  6456. _this._evalArgValues = [];
  6457. _this._evalExportedVars = [];
  6458. return _this;
  6459. }
  6460. JitEmitterVisitor.prototype.createReturnStmt = function (ctx) {
  6461. var stmt = new ReturnStatement(new LiteralMapExpr(this._evalExportedVars.map(function (resultVar) { return new LiteralMapEntry(resultVar, variable(resultVar), false); })));
  6462. stmt.visitStatement(this, ctx);
  6463. };
  6464. JitEmitterVisitor.prototype.getArgs = function () {
  6465. var result = {};
  6466. for (var i = 0; i < this._evalArgNames.length; i++) {
  6467. result[this._evalArgNames[i]] = this._evalArgValues[i];
  6468. }
  6469. return result;
  6470. };
  6471. JitEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) {
  6472. this._emitReferenceToExternal(ast, this.reflector.resolveExternalReference(ast.value), ctx);
  6473. return null;
  6474. };
  6475. JitEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  6476. this._emitReferenceToExternal(ast, ast.node, ctx);
  6477. return null;
  6478. };
  6479. JitEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
  6480. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  6481. this._evalExportedVars.push(stmt.name);
  6482. }
  6483. return _super.prototype.visitDeclareVarStmt.call(this, stmt, ctx);
  6484. };
  6485. JitEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
  6486. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  6487. this._evalExportedVars.push(stmt.name);
  6488. }
  6489. return _super.prototype.visitDeclareFunctionStmt.call(this, stmt, ctx);
  6490. };
  6491. JitEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
  6492. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  6493. this._evalExportedVars.push(stmt.name);
  6494. }
  6495. return _super.prototype.visitDeclareClassStmt.call(this, stmt, ctx);
  6496. };
  6497. JitEmitterVisitor.prototype._emitReferenceToExternal = function (ast, value, ctx) {
  6498. var id = this._evalArgValues.indexOf(value);
  6499. if (id === -1) {
  6500. id = this._evalArgValues.length;
  6501. this._evalArgValues.push(value);
  6502. var name_1 = identifierName({ reference: value }) || 'val';
  6503. this._evalArgNames.push("jit_" + name_1 + "_" + id);
  6504. }
  6505. ctx.print(ast, this._evalArgNames[id]);
  6506. };
  6507. return JitEmitterVisitor;
  6508. }(AbstractJsEmitterVisitor));
  6509. function isUseStrictStatement(statement) {
  6510. return statement.isEquivalent(literal('use strict').toStmt());
  6511. }
  6512. /**
  6513. * @license
  6514. * Copyright Google Inc. All Rights Reserved.
  6515. *
  6516. * Use of this source code is governed by an MIT-style license that can be
  6517. * found in the LICENSE file at https://angular.io/license
  6518. */
  6519. /**
  6520. * Implementation of `CompileReflector` which resolves references to @angular/core
  6521. * symbols at runtime, according to a consumer-provided mapping.
  6522. *
  6523. * Only supports `resolveExternalReference`, all other methods throw.
  6524. */
  6525. var R3JitReflector = /** @class */ (function () {
  6526. function R3JitReflector(context) {
  6527. this.context = context;
  6528. }
  6529. R3JitReflector.prototype.resolveExternalReference = function (ref) {
  6530. // This reflector only handles @angular/core imports.
  6531. if (ref.moduleName !== '@angular/core') {
  6532. throw new Error("Cannot resolve external reference to " + ref.moduleName + ", only references to @angular/core are supported.");
  6533. }
  6534. if (!this.context.hasOwnProperty(ref.name)) {
  6535. throw new Error("No value provided for @angular/core symbol '" + ref.name + "'.");
  6536. }
  6537. return this.context[ref.name];
  6538. };
  6539. R3JitReflector.prototype.parameters = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6540. R3JitReflector.prototype.annotations = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6541. R3JitReflector.prototype.shallowAnnotations = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6542. R3JitReflector.prototype.tryAnnotations = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6543. R3JitReflector.prototype.propMetadata = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6544. R3JitReflector.prototype.hasLifecycleHook = function (type, lcProperty) { throw new Error('Not implemented.'); };
  6545. R3JitReflector.prototype.guards = function (typeOrFunc) { throw new Error('Not implemented.'); };
  6546. R3JitReflector.prototype.componentModuleUrl = function (type, cmpMetadata) { throw new Error('Not implemented.'); };
  6547. return R3JitReflector;
  6548. }());
  6549. /**
  6550. * @license
  6551. * Copyright Google Inc. All Rights Reserved.
  6552. *
  6553. * Use of this source code is governed by an MIT-style license that can be
  6554. * found in the LICENSE file at https://angular.io/license
  6555. */
  6556. /**
  6557. * Construct an `R3NgModuleDef` for the given `R3NgModuleMetadata`.
  6558. */
  6559. function compileNgModule(meta) {
  6560. 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;
  6561. var additionalStatements = [];
  6562. var definitionMap = {
  6563. type: moduleType
  6564. };
  6565. // Only generate the keys in the metadata if the arrays have values.
  6566. if (bootstrap.length) {
  6567. definitionMap.bootstrap = refsToArray(bootstrap, containsForwardDecls);
  6568. }
  6569. // If requested to emit scope information inline, pass the declarations, imports and exports to
  6570. // the `ɵɵdefineNgModule` call. The JIT compilation uses this.
  6571. if (emitInline) {
  6572. if (declarations.length) {
  6573. definitionMap.declarations = refsToArray(declarations, containsForwardDecls);
  6574. }
  6575. if (imports.length) {
  6576. definitionMap.imports = refsToArray(imports, containsForwardDecls);
  6577. }
  6578. if (exports.length) {
  6579. definitionMap.exports = refsToArray(exports, containsForwardDecls);
  6580. }
  6581. }
  6582. // If not emitting inline, the scope information is not passed into `ɵɵdefineNgModule` as it would
  6583. // prevent tree-shaking of the declarations, imports and exports references.
  6584. else {
  6585. var setNgModuleScopeCall = generateSetNgModuleScopeCall(meta);
  6586. if (setNgModuleScopeCall !== null) {
  6587. additionalStatements.push(setNgModuleScopeCall);
  6588. }
  6589. }
  6590. if (schemas && schemas.length) {
  6591. definitionMap.schemas = literalArr(schemas.map(function (ref) { return ref.value; }));
  6592. }
  6593. if (id) {
  6594. definitionMap.id = id;
  6595. }
  6596. var expression = importExpr(Identifiers$1.defineNgModule).callFn([mapToMapExpression(definitionMap)]);
  6597. var type = new ExpressionType(importExpr(Identifiers$1.NgModuleDefWithMeta, [
  6598. new ExpressionType(moduleType), tupleTypeOf(declarations), tupleTypeOf(imports),
  6599. tupleTypeOf(exports)
  6600. ]));
  6601. return { expression: expression, type: type, additionalStatements: additionalStatements };
  6602. }
  6603. /**
  6604. * Generates a function call to `ɵɵsetNgModuleScope` with all necessary information so that the
  6605. * transitive module scope can be computed during runtime in JIT mode. This call is marked pure
  6606. * such that the references to declarations, imports and exports may be elided causing these
  6607. * symbols to become tree-shakeable.
  6608. */
  6609. function generateSetNgModuleScopeCall(meta) {
  6610. var moduleType = meta.type, declarations = meta.declarations, imports = meta.imports, exports = meta.exports, containsForwardDecls = meta.containsForwardDecls;
  6611. var scopeMap = {};
  6612. if (declarations.length) {
  6613. scopeMap.declarations = refsToArray(declarations, containsForwardDecls);
  6614. }
  6615. if (imports.length) {
  6616. scopeMap.imports = refsToArray(imports, containsForwardDecls);
  6617. }
  6618. if (exports.length) {
  6619. scopeMap.exports = refsToArray(exports, containsForwardDecls);
  6620. }
  6621. if (Object.keys(scopeMap).length === 0) {
  6622. return null;
  6623. }
  6624. var fnCall = new InvokeFunctionExpr(
  6625. /* fn */ importExpr(Identifiers$1.setNgModuleScope),
  6626. /* args */ [moduleType, mapToMapExpression(scopeMap)],
  6627. /* type */ undefined,
  6628. /* sourceSpan */ undefined,
  6629. /* pure */ true);
  6630. return fnCall.toStmt();
  6631. }
  6632. function compileInjector(meta) {
  6633. var result = compileFactoryFunction({
  6634. name: meta.name,
  6635. type: meta.type,
  6636. deps: meta.deps,
  6637. injectFn: Identifiers$1.inject,
  6638. });
  6639. var definitionMap = {
  6640. factory: result.factory,
  6641. };
  6642. if (meta.providers !== null) {
  6643. definitionMap.providers = meta.providers;
  6644. }
  6645. if (meta.imports.length > 0) {
  6646. definitionMap.imports = literalArr(meta.imports);
  6647. }
  6648. var expression = importExpr(Identifiers$1.defineInjector).callFn([mapToMapExpression(definitionMap)]);
  6649. var type = new ExpressionType(importExpr(Identifiers$1.InjectorDef, [new ExpressionType(meta.type)]));
  6650. return { expression: expression, type: type, statements: result.statements };
  6651. }
  6652. // TODO(alxhub): integrate this with `compileNgModule`. Currently the two are separate operations.
  6653. function compileNgModuleFromRender2(ctx, ngModule, injectableCompiler) {
  6654. var className = identifierName(ngModule.type);
  6655. var rawImports = ngModule.rawImports ? [ngModule.rawImports] : [];
  6656. var rawExports = ngModule.rawExports ? [ngModule.rawExports] : [];
  6657. var injectorDefArg = mapLiteral({
  6658. 'factory': injectableCompiler.factoryFor({ type: ngModule.type, symbol: ngModule.type.reference }, ctx),
  6659. 'providers': convertMetaToOutput(ngModule.rawProviders, ctx),
  6660. 'imports': convertMetaToOutput(__spread(rawImports, rawExports), ctx),
  6661. });
  6662. var injectorDef = importExpr(Identifiers$1.defineInjector).callFn([injectorDefArg]);
  6663. ctx.statements.push(new ClassStmt(
  6664. /* name */ className,
  6665. /* parent */ null,
  6666. /* fields */ [new ClassField(
  6667. /* name */ 'ngInjectorDef',
  6668. /* type */ INFERRED_TYPE,
  6669. /* modifiers */ [exports.StmtModifier.Static],
  6670. /* initializer */ injectorDef)],
  6671. /* getters */ [],
  6672. /* constructorMethod */ new ClassMethod(null, [], []),
  6673. /* methods */ []));
  6674. }
  6675. function tupleTypeOf(exp) {
  6676. var types = exp.map(function (ref) { return typeofExpr(ref.type); });
  6677. return exp.length > 0 ? expressionType(literalArr(types)) : NONE_TYPE;
  6678. }
  6679. function refsToArray(refs, shouldForwardDeclare) {
  6680. var values = literalArr(refs.map(function (ref) { return ref.value; }));
  6681. return shouldForwardDeclare ? fn([], [new ReturnStatement(values)]) : values;
  6682. }
  6683. /**
  6684. * @license
  6685. * Copyright Google Inc. All Rights Reserved.
  6686. *
  6687. * Use of this source code is governed by an MIT-style license that can be
  6688. * found in the LICENSE file at https://angular.io/license
  6689. */
  6690. function compilePipeFromMetadata(metadata) {
  6691. var definitionMapValues = [];
  6692. // e.g. `name: 'myPipe'`
  6693. definitionMapValues.push({ key: 'name', value: literal(metadata.pipeName), quoted: false });
  6694. // e.g. `type: MyPipe`
  6695. definitionMapValues.push({ key: 'type', value: metadata.type, quoted: false });
  6696. var templateFactory = compileFactoryFunction({
  6697. name: metadata.name,
  6698. type: metadata.type,
  6699. deps: metadata.deps,
  6700. injectFn: Identifiers$1.directiveInject,
  6701. });
  6702. definitionMapValues.push({ key: 'factory', value: templateFactory.factory, quoted: false });
  6703. // e.g. `pure: true`
  6704. definitionMapValues.push({ key: 'pure', value: literal(metadata.pure), quoted: false });
  6705. var expression = importExpr(Identifiers$1.definePipe).callFn([literalMap(definitionMapValues)]);
  6706. var type = new ExpressionType(importExpr(Identifiers$1.PipeDefWithMeta, [
  6707. typeWithParameters(metadata.type, metadata.typeArgumentCount),
  6708. new ExpressionType(new LiteralExpr(metadata.pipeName)),
  6709. ]));
  6710. return { expression: expression, type: type, statements: templateFactory.statements };
  6711. }
  6712. /**
  6713. * Write a pipe definition to the output context.
  6714. */
  6715. function compilePipeFromRender2(outputCtx, pipe, reflector) {
  6716. var name = identifierName(pipe.type);
  6717. if (!name) {
  6718. return error("Cannot resolve the name of " + pipe.type);
  6719. }
  6720. var metadata = {
  6721. name: name,
  6722. pipeName: pipe.name,
  6723. type: outputCtx.importExpr(pipe.type.reference),
  6724. typeArgumentCount: 0,
  6725. deps: dependenciesFromGlobalMetadata(pipe.type, outputCtx, reflector),
  6726. pure: pipe.pure,
  6727. };
  6728. var res = compilePipeFromMetadata(metadata);
  6729. var definitionField = outputCtx.constantPool.propertyNameOf(3 /* Pipe */);
  6730. outputCtx.statements.push(new ClassStmt(
  6731. /* name */ name,
  6732. /* parent */ null,
  6733. /* fields */ [new ClassField(
  6734. /* name */ definitionField,
  6735. /* type */ INFERRED_TYPE,
  6736. /* modifiers */ [exports.StmtModifier.Static],
  6737. /* initializer */ res.expression)],
  6738. /* getters */ [],
  6739. /* constructorMethod */ new ClassMethod(null, [], []),
  6740. /* methods */ []));
  6741. }
  6742. /**
  6743. * @license
  6744. * Copyright Google Inc. All Rights Reserved.
  6745. *
  6746. * Use of this source code is governed by an MIT-style license that can be
  6747. * found in the LICENSE file at https://angular.io/license
  6748. */
  6749. var ParserError = /** @class */ (function () {
  6750. function ParserError(message, input, errLocation, ctxLocation) {
  6751. this.input = input;
  6752. this.errLocation = errLocation;
  6753. this.ctxLocation = ctxLocation;
  6754. this.message = "Parser Error: " + message + " " + errLocation + " [" + input + "] in " + ctxLocation;
  6755. }
  6756. return ParserError;
  6757. }());
  6758. var ParseSpan = /** @class */ (function () {
  6759. function ParseSpan(start, end) {
  6760. this.start = start;
  6761. this.end = end;
  6762. }
  6763. return ParseSpan;
  6764. }());
  6765. var AST = /** @class */ (function () {
  6766. function AST(span) {
  6767. this.span = span;
  6768. }
  6769. AST.prototype.visit = function (visitor, context) {
  6770. if (context === void 0) { context = null; }
  6771. return null;
  6772. };
  6773. AST.prototype.toString = function () { return 'AST'; };
  6774. return AST;
  6775. }());
  6776. /**
  6777. * Represents a quoted expression of the form:
  6778. *
  6779. * quote = prefix `:` uninterpretedExpression
  6780. * prefix = identifier
  6781. * uninterpretedExpression = arbitrary string
  6782. *
  6783. * A quoted expression is meant to be pre-processed by an AST transformer that
  6784. * converts it into another AST that no longer contains quoted expressions.
  6785. * It is meant to allow third-party developers to extend Angular template
  6786. * expression language. The `uninterpretedExpression` part of the quote is
  6787. * therefore not interpreted by the Angular's own expression parser.
  6788. */
  6789. var Quote = /** @class */ (function (_super) {
  6790. __extends(Quote, _super);
  6791. function Quote(span, prefix, uninterpretedExpression, location) {
  6792. var _this = _super.call(this, span) || this;
  6793. _this.prefix = prefix;
  6794. _this.uninterpretedExpression = uninterpretedExpression;
  6795. _this.location = location;
  6796. return _this;
  6797. }
  6798. Quote.prototype.visit = function (visitor, context) {
  6799. if (context === void 0) { context = null; }
  6800. return visitor.visitQuote(this, context);
  6801. };
  6802. Quote.prototype.toString = function () { return 'Quote'; };
  6803. return Quote;
  6804. }(AST));
  6805. var EmptyExpr = /** @class */ (function (_super) {
  6806. __extends(EmptyExpr, _super);
  6807. function EmptyExpr() {
  6808. return _super !== null && _super.apply(this, arguments) || this;
  6809. }
  6810. EmptyExpr.prototype.visit = function (visitor, context) {
  6811. if (context === void 0) { context = null; }
  6812. // do nothing
  6813. };
  6814. return EmptyExpr;
  6815. }(AST));
  6816. var ImplicitReceiver = /** @class */ (function (_super) {
  6817. __extends(ImplicitReceiver, _super);
  6818. function ImplicitReceiver() {
  6819. return _super !== null && _super.apply(this, arguments) || this;
  6820. }
  6821. ImplicitReceiver.prototype.visit = function (visitor, context) {
  6822. if (context === void 0) { context = null; }
  6823. return visitor.visitImplicitReceiver(this, context);
  6824. };
  6825. return ImplicitReceiver;
  6826. }(AST));
  6827. /**
  6828. * Multiple expressions separated by a semicolon.
  6829. */
  6830. var Chain = /** @class */ (function (_super) {
  6831. __extends(Chain, _super);
  6832. function Chain(span, expressions) {
  6833. var _this = _super.call(this, span) || this;
  6834. _this.expressions = expressions;
  6835. return _this;
  6836. }
  6837. Chain.prototype.visit = function (visitor, context) {
  6838. if (context === void 0) { context = null; }
  6839. return visitor.visitChain(this, context);
  6840. };
  6841. return Chain;
  6842. }(AST));
  6843. var Conditional = /** @class */ (function (_super) {
  6844. __extends(Conditional, _super);
  6845. function Conditional(span, condition, trueExp, falseExp) {
  6846. var _this = _super.call(this, span) || this;
  6847. _this.condition = condition;
  6848. _this.trueExp = trueExp;
  6849. _this.falseExp = falseExp;
  6850. return _this;
  6851. }
  6852. Conditional.prototype.visit = function (visitor, context) {
  6853. if (context === void 0) { context = null; }
  6854. return visitor.visitConditional(this, context);
  6855. };
  6856. return Conditional;
  6857. }(AST));
  6858. var PropertyRead = /** @class */ (function (_super) {
  6859. __extends(PropertyRead, _super);
  6860. function PropertyRead(span, receiver, name) {
  6861. var _this = _super.call(this, span) || this;
  6862. _this.receiver = receiver;
  6863. _this.name = name;
  6864. return _this;
  6865. }
  6866. PropertyRead.prototype.visit = function (visitor, context) {
  6867. if (context === void 0) { context = null; }
  6868. return visitor.visitPropertyRead(this, context);
  6869. };
  6870. return PropertyRead;
  6871. }(AST));
  6872. var PropertyWrite = /** @class */ (function (_super) {
  6873. __extends(PropertyWrite, _super);
  6874. function PropertyWrite(span, receiver, name, value) {
  6875. var _this = _super.call(this, span) || this;
  6876. _this.receiver = receiver;
  6877. _this.name = name;
  6878. _this.value = value;
  6879. return _this;
  6880. }
  6881. PropertyWrite.prototype.visit = function (visitor, context) {
  6882. if (context === void 0) { context = null; }
  6883. return visitor.visitPropertyWrite(this, context);
  6884. };
  6885. return PropertyWrite;
  6886. }(AST));
  6887. var SafePropertyRead = /** @class */ (function (_super) {
  6888. __extends(SafePropertyRead, _super);
  6889. function SafePropertyRead(span, receiver, name) {
  6890. var _this = _super.call(this, span) || this;
  6891. _this.receiver = receiver;
  6892. _this.name = name;
  6893. return _this;
  6894. }
  6895. SafePropertyRead.prototype.visit = function (visitor, context) {
  6896. if (context === void 0) { context = null; }
  6897. return visitor.visitSafePropertyRead(this, context);
  6898. };
  6899. return SafePropertyRead;
  6900. }(AST));
  6901. var KeyedRead = /** @class */ (function (_super) {
  6902. __extends(KeyedRead, _super);
  6903. function KeyedRead(span, obj, key) {
  6904. var _this = _super.call(this, span) || this;
  6905. _this.obj = obj;
  6906. _this.key = key;
  6907. return _this;
  6908. }
  6909. KeyedRead.prototype.visit = function (visitor, context) {
  6910. if (context === void 0) { context = null; }
  6911. return visitor.visitKeyedRead(this, context);
  6912. };
  6913. return KeyedRead;
  6914. }(AST));
  6915. var KeyedWrite = /** @class */ (function (_super) {
  6916. __extends(KeyedWrite, _super);
  6917. function KeyedWrite(span, obj, key, value) {
  6918. var _this = _super.call(this, span) || this;
  6919. _this.obj = obj;
  6920. _this.key = key;
  6921. _this.value = value;
  6922. return _this;
  6923. }
  6924. KeyedWrite.prototype.visit = function (visitor, context) {
  6925. if (context === void 0) { context = null; }
  6926. return visitor.visitKeyedWrite(this, context);
  6927. };
  6928. return KeyedWrite;
  6929. }(AST));
  6930. var BindingPipe = /** @class */ (function (_super) {
  6931. __extends(BindingPipe, _super);
  6932. function BindingPipe(span, exp, name, args) {
  6933. var _this = _super.call(this, span) || this;
  6934. _this.exp = exp;
  6935. _this.name = name;
  6936. _this.args = args;
  6937. return _this;
  6938. }
  6939. BindingPipe.prototype.visit = function (visitor, context) {
  6940. if (context === void 0) { context = null; }
  6941. return visitor.visitPipe(this, context);
  6942. };
  6943. return BindingPipe;
  6944. }(AST));
  6945. var LiteralPrimitive = /** @class */ (function (_super) {
  6946. __extends(LiteralPrimitive, _super);
  6947. function LiteralPrimitive(span, value) {
  6948. var _this = _super.call(this, span) || this;
  6949. _this.value = value;
  6950. return _this;
  6951. }
  6952. LiteralPrimitive.prototype.visit = function (visitor, context) {
  6953. if (context === void 0) { context = null; }
  6954. return visitor.visitLiteralPrimitive(this, context);
  6955. };
  6956. return LiteralPrimitive;
  6957. }(AST));
  6958. var LiteralArray = /** @class */ (function (_super) {
  6959. __extends(LiteralArray, _super);
  6960. function LiteralArray(span, expressions) {
  6961. var _this = _super.call(this, span) || this;
  6962. _this.expressions = expressions;
  6963. return _this;
  6964. }
  6965. LiteralArray.prototype.visit = function (visitor, context) {
  6966. if (context === void 0) { context = null; }
  6967. return visitor.visitLiteralArray(this, context);
  6968. };
  6969. return LiteralArray;
  6970. }(AST));
  6971. var LiteralMap = /** @class */ (function (_super) {
  6972. __extends(LiteralMap, _super);
  6973. function LiteralMap(span, keys, values) {
  6974. var _this = _super.call(this, span) || this;
  6975. _this.keys = keys;
  6976. _this.values = values;
  6977. return _this;
  6978. }
  6979. LiteralMap.prototype.visit = function (visitor, context) {
  6980. if (context === void 0) { context = null; }
  6981. return visitor.visitLiteralMap(this, context);
  6982. };
  6983. return LiteralMap;
  6984. }(AST));
  6985. var Interpolation = /** @class */ (function (_super) {
  6986. __extends(Interpolation, _super);
  6987. function Interpolation(span, strings, expressions) {
  6988. var _this = _super.call(this, span) || this;
  6989. _this.strings = strings;
  6990. _this.expressions = expressions;
  6991. return _this;
  6992. }
  6993. Interpolation.prototype.visit = function (visitor, context) {
  6994. if (context === void 0) { context = null; }
  6995. return visitor.visitInterpolation(this, context);
  6996. };
  6997. return Interpolation;
  6998. }(AST));
  6999. var Binary = /** @class */ (function (_super) {
  7000. __extends(Binary, _super);
  7001. function Binary(span, operation, left, right) {
  7002. var _this = _super.call(this, span) || this;
  7003. _this.operation = operation;
  7004. _this.left = left;
  7005. _this.right = right;
  7006. return _this;
  7007. }
  7008. Binary.prototype.visit = function (visitor, context) {
  7009. if (context === void 0) { context = null; }
  7010. return visitor.visitBinary(this, context);
  7011. };
  7012. return Binary;
  7013. }(AST));
  7014. var PrefixNot = /** @class */ (function (_super) {
  7015. __extends(PrefixNot, _super);
  7016. function PrefixNot(span, expression) {
  7017. var _this = _super.call(this, span) || this;
  7018. _this.expression = expression;
  7019. return _this;
  7020. }
  7021. PrefixNot.prototype.visit = function (visitor, context) {
  7022. if (context === void 0) { context = null; }
  7023. return visitor.visitPrefixNot(this, context);
  7024. };
  7025. return PrefixNot;
  7026. }(AST));
  7027. var NonNullAssert = /** @class */ (function (_super) {
  7028. __extends(NonNullAssert, _super);
  7029. function NonNullAssert(span, expression) {
  7030. var _this = _super.call(this, span) || this;
  7031. _this.expression = expression;
  7032. return _this;
  7033. }
  7034. NonNullAssert.prototype.visit = function (visitor, context) {
  7035. if (context === void 0) { context = null; }
  7036. return visitor.visitNonNullAssert(this, context);
  7037. };
  7038. return NonNullAssert;
  7039. }(AST));
  7040. var MethodCall = /** @class */ (function (_super) {
  7041. __extends(MethodCall, _super);
  7042. function MethodCall(span, receiver, name, args) {
  7043. var _this = _super.call(this, span) || this;
  7044. _this.receiver = receiver;
  7045. _this.name = name;
  7046. _this.args = args;
  7047. return _this;
  7048. }
  7049. MethodCall.prototype.visit = function (visitor, context) {
  7050. if (context === void 0) { context = null; }
  7051. return visitor.visitMethodCall(this, context);
  7052. };
  7053. return MethodCall;
  7054. }(AST));
  7055. var SafeMethodCall = /** @class */ (function (_super) {
  7056. __extends(SafeMethodCall, _super);
  7057. function SafeMethodCall(span, receiver, name, args) {
  7058. var _this = _super.call(this, span) || this;
  7059. _this.receiver = receiver;
  7060. _this.name = name;
  7061. _this.args = args;
  7062. return _this;
  7063. }
  7064. SafeMethodCall.prototype.visit = function (visitor, context) {
  7065. if (context === void 0) { context = null; }
  7066. return visitor.visitSafeMethodCall(this, context);
  7067. };
  7068. return SafeMethodCall;
  7069. }(AST));
  7070. var FunctionCall = /** @class */ (function (_super) {
  7071. __extends(FunctionCall, _super);
  7072. function FunctionCall(span, target, args) {
  7073. var _this = _super.call(this, span) || this;
  7074. _this.target = target;
  7075. _this.args = args;
  7076. return _this;
  7077. }
  7078. FunctionCall.prototype.visit = function (visitor, context) {
  7079. if (context === void 0) { context = null; }
  7080. return visitor.visitFunctionCall(this, context);
  7081. };
  7082. return FunctionCall;
  7083. }(AST));
  7084. var ASTWithSource = /** @class */ (function (_super) {
  7085. __extends(ASTWithSource, _super);
  7086. function ASTWithSource(ast, source, location, errors) {
  7087. var _this = _super.call(this, new ParseSpan(0, source == null ? 0 : source.length)) || this;
  7088. _this.ast = ast;
  7089. _this.source = source;
  7090. _this.location = location;
  7091. _this.errors = errors;
  7092. return _this;
  7093. }
  7094. ASTWithSource.prototype.visit = function (visitor, context) {
  7095. if (context === void 0) { context = null; }
  7096. return this.ast.visit(visitor, context);
  7097. };
  7098. ASTWithSource.prototype.toString = function () { return this.source + " in " + this.location; };
  7099. return ASTWithSource;
  7100. }(AST));
  7101. var TemplateBinding = /** @class */ (function () {
  7102. function TemplateBinding(span, key, keyIsVar, name, expression) {
  7103. this.span = span;
  7104. this.key = key;
  7105. this.keyIsVar = keyIsVar;
  7106. this.name = name;
  7107. this.expression = expression;
  7108. }
  7109. return TemplateBinding;
  7110. }());
  7111. var NullAstVisitor = /** @class */ (function () {
  7112. function NullAstVisitor() {
  7113. }
  7114. NullAstVisitor.prototype.visitBinary = function (ast, context) { };
  7115. NullAstVisitor.prototype.visitChain = function (ast, context) { };
  7116. NullAstVisitor.prototype.visitConditional = function (ast, context) { };
  7117. NullAstVisitor.prototype.visitFunctionCall = function (ast, context) { };
  7118. NullAstVisitor.prototype.visitImplicitReceiver = function (ast, context) { };
  7119. NullAstVisitor.prototype.visitInterpolation = function (ast, context) { };
  7120. NullAstVisitor.prototype.visitKeyedRead = function (ast, context) { };
  7121. NullAstVisitor.prototype.visitKeyedWrite = function (ast, context) { };
  7122. NullAstVisitor.prototype.visitLiteralArray = function (ast, context) { };
  7123. NullAstVisitor.prototype.visitLiteralMap = function (ast, context) { };
  7124. NullAstVisitor.prototype.visitLiteralPrimitive = function (ast, context) { };
  7125. NullAstVisitor.prototype.visitMethodCall = function (ast, context) { };
  7126. NullAstVisitor.prototype.visitPipe = function (ast, context) { };
  7127. NullAstVisitor.prototype.visitPrefixNot = function (ast, context) { };
  7128. NullAstVisitor.prototype.visitNonNullAssert = function (ast, context) { };
  7129. NullAstVisitor.prototype.visitPropertyRead = function (ast, context) { };
  7130. NullAstVisitor.prototype.visitPropertyWrite = function (ast, context) { };
  7131. NullAstVisitor.prototype.visitQuote = function (ast, context) { };
  7132. NullAstVisitor.prototype.visitSafeMethodCall = function (ast, context) { };
  7133. NullAstVisitor.prototype.visitSafePropertyRead = function (ast, context) { };
  7134. return NullAstVisitor;
  7135. }());
  7136. var RecursiveAstVisitor$1 = /** @class */ (function () {
  7137. function RecursiveAstVisitor() {
  7138. }
  7139. RecursiveAstVisitor.prototype.visitBinary = function (ast, context) {
  7140. ast.left.visit(this, context);
  7141. ast.right.visit(this, context);
  7142. return null;
  7143. };
  7144. RecursiveAstVisitor.prototype.visitChain = function (ast, context) { return this.visitAll(ast.expressions, context); };
  7145. RecursiveAstVisitor.prototype.visitConditional = function (ast, context) {
  7146. ast.condition.visit(this, context);
  7147. ast.trueExp.visit(this, context);
  7148. ast.falseExp.visit(this, context);
  7149. return null;
  7150. };
  7151. RecursiveAstVisitor.prototype.visitPipe = function (ast, context) {
  7152. ast.exp.visit(this, context);
  7153. this.visitAll(ast.args, context);
  7154. return null;
  7155. };
  7156. RecursiveAstVisitor.prototype.visitFunctionCall = function (ast, context) {
  7157. ast.target.visit(this, context);
  7158. this.visitAll(ast.args, context);
  7159. return null;
  7160. };
  7161. RecursiveAstVisitor.prototype.visitImplicitReceiver = function (ast, context) { return null; };
  7162. RecursiveAstVisitor.prototype.visitInterpolation = function (ast, context) {
  7163. return this.visitAll(ast.expressions, context);
  7164. };
  7165. RecursiveAstVisitor.prototype.visitKeyedRead = function (ast, context) {
  7166. ast.obj.visit(this, context);
  7167. ast.key.visit(this, context);
  7168. return null;
  7169. };
  7170. RecursiveAstVisitor.prototype.visitKeyedWrite = function (ast, context) {
  7171. ast.obj.visit(this, context);
  7172. ast.key.visit(this, context);
  7173. ast.value.visit(this, context);
  7174. return null;
  7175. };
  7176. RecursiveAstVisitor.prototype.visitLiteralArray = function (ast, context) {
  7177. return this.visitAll(ast.expressions, context);
  7178. };
  7179. RecursiveAstVisitor.prototype.visitLiteralMap = function (ast, context) { return this.visitAll(ast.values, context); };
  7180. RecursiveAstVisitor.prototype.visitLiteralPrimitive = function (ast, context) { return null; };
  7181. RecursiveAstVisitor.prototype.visitMethodCall = function (ast, context) {
  7182. ast.receiver.visit(this, context);
  7183. return this.visitAll(ast.args, context);
  7184. };
  7185. RecursiveAstVisitor.prototype.visitPrefixNot = function (ast, context) {
  7186. ast.expression.visit(this, context);
  7187. return null;
  7188. };
  7189. RecursiveAstVisitor.prototype.visitNonNullAssert = function (ast, context) {
  7190. ast.expression.visit(this, context);
  7191. return null;
  7192. };
  7193. RecursiveAstVisitor.prototype.visitPropertyRead = function (ast, context) {
  7194. ast.receiver.visit(this, context);
  7195. return null;
  7196. };
  7197. RecursiveAstVisitor.prototype.visitPropertyWrite = function (ast, context) {
  7198. ast.receiver.visit(this, context);
  7199. ast.value.visit(this, context);
  7200. return null;
  7201. };
  7202. RecursiveAstVisitor.prototype.visitSafePropertyRead = function (ast, context) {
  7203. ast.receiver.visit(this, context);
  7204. return null;
  7205. };
  7206. RecursiveAstVisitor.prototype.visitSafeMethodCall = function (ast, context) {
  7207. ast.receiver.visit(this, context);
  7208. return this.visitAll(ast.args, context);
  7209. };
  7210. RecursiveAstVisitor.prototype.visitAll = function (asts, context) {
  7211. var _this = this;
  7212. asts.forEach(function (ast) { return ast.visit(_this, context); });
  7213. return null;
  7214. };
  7215. RecursiveAstVisitor.prototype.visitQuote = function (ast, context) { return null; };
  7216. return RecursiveAstVisitor;
  7217. }());
  7218. var AstTransformer$1 = /** @class */ (function () {
  7219. function AstTransformer() {
  7220. }
  7221. AstTransformer.prototype.visitImplicitReceiver = function (ast, context) { return ast; };
  7222. AstTransformer.prototype.visitInterpolation = function (ast, context) {
  7223. return new Interpolation(ast.span, ast.strings, this.visitAll(ast.expressions));
  7224. };
  7225. AstTransformer.prototype.visitLiteralPrimitive = function (ast, context) {
  7226. return new LiteralPrimitive(ast.span, ast.value);
  7227. };
  7228. AstTransformer.prototype.visitPropertyRead = function (ast, context) {
  7229. return new PropertyRead(ast.span, ast.receiver.visit(this), ast.name);
  7230. };
  7231. AstTransformer.prototype.visitPropertyWrite = function (ast, context) {
  7232. return new PropertyWrite(ast.span, ast.receiver.visit(this), ast.name, ast.value.visit(this));
  7233. };
  7234. AstTransformer.prototype.visitSafePropertyRead = function (ast, context) {
  7235. return new SafePropertyRead(ast.span, ast.receiver.visit(this), ast.name);
  7236. };
  7237. AstTransformer.prototype.visitMethodCall = function (ast, context) {
  7238. return new MethodCall(ast.span, ast.receiver.visit(this), ast.name, this.visitAll(ast.args));
  7239. };
  7240. AstTransformer.prototype.visitSafeMethodCall = function (ast, context) {
  7241. return new SafeMethodCall(ast.span, ast.receiver.visit(this), ast.name, this.visitAll(ast.args));
  7242. };
  7243. AstTransformer.prototype.visitFunctionCall = function (ast, context) {
  7244. return new FunctionCall(ast.span, ast.target.visit(this), this.visitAll(ast.args));
  7245. };
  7246. AstTransformer.prototype.visitLiteralArray = function (ast, context) {
  7247. return new LiteralArray(ast.span, this.visitAll(ast.expressions));
  7248. };
  7249. AstTransformer.prototype.visitLiteralMap = function (ast, context) {
  7250. return new LiteralMap(ast.span, ast.keys, this.visitAll(ast.values));
  7251. };
  7252. AstTransformer.prototype.visitBinary = function (ast, context) {
  7253. return new Binary(ast.span, ast.operation, ast.left.visit(this), ast.right.visit(this));
  7254. };
  7255. AstTransformer.prototype.visitPrefixNot = function (ast, context) {
  7256. return new PrefixNot(ast.span, ast.expression.visit(this));
  7257. };
  7258. AstTransformer.prototype.visitNonNullAssert = function (ast, context) {
  7259. return new NonNullAssert(ast.span, ast.expression.visit(this));
  7260. };
  7261. AstTransformer.prototype.visitConditional = function (ast, context) {
  7262. return new Conditional(ast.span, ast.condition.visit(this), ast.trueExp.visit(this), ast.falseExp.visit(this));
  7263. };
  7264. AstTransformer.prototype.visitPipe = function (ast, context) {
  7265. return new BindingPipe(ast.span, ast.exp.visit(this), ast.name, this.visitAll(ast.args));
  7266. };
  7267. AstTransformer.prototype.visitKeyedRead = function (ast, context) {
  7268. return new KeyedRead(ast.span, ast.obj.visit(this), ast.key.visit(this));
  7269. };
  7270. AstTransformer.prototype.visitKeyedWrite = function (ast, context) {
  7271. return new KeyedWrite(ast.span, ast.obj.visit(this), ast.key.visit(this), ast.value.visit(this));
  7272. };
  7273. AstTransformer.prototype.visitAll = function (asts) {
  7274. var res = new Array(asts.length);
  7275. for (var i = 0; i < asts.length; ++i) {
  7276. res[i] = asts[i].visit(this);
  7277. }
  7278. return res;
  7279. };
  7280. AstTransformer.prototype.visitChain = function (ast, context) {
  7281. return new Chain(ast.span, this.visitAll(ast.expressions));
  7282. };
  7283. AstTransformer.prototype.visitQuote = function (ast, context) {
  7284. return new Quote(ast.span, ast.prefix, ast.uninterpretedExpression, ast.location);
  7285. };
  7286. return AstTransformer;
  7287. }());
  7288. // A transformer that only creates new nodes if the transformer makes a change or
  7289. // a change is made a child node.
  7290. var AstMemoryEfficientTransformer = /** @class */ (function () {
  7291. function AstMemoryEfficientTransformer() {
  7292. }
  7293. AstMemoryEfficientTransformer.prototype.visitImplicitReceiver = function (ast, context) { return ast; };
  7294. AstMemoryEfficientTransformer.prototype.visitInterpolation = function (ast, context) {
  7295. var expressions = this.visitAll(ast.expressions);
  7296. if (expressions !== ast.expressions)
  7297. return new Interpolation(ast.span, ast.strings, expressions);
  7298. return ast;
  7299. };
  7300. AstMemoryEfficientTransformer.prototype.visitLiteralPrimitive = function (ast, context) { return ast; };
  7301. AstMemoryEfficientTransformer.prototype.visitPropertyRead = function (ast, context) {
  7302. var receiver = ast.receiver.visit(this);
  7303. if (receiver !== ast.receiver) {
  7304. return new PropertyRead(ast.span, receiver, ast.name);
  7305. }
  7306. return ast;
  7307. };
  7308. AstMemoryEfficientTransformer.prototype.visitPropertyWrite = function (ast, context) {
  7309. var receiver = ast.receiver.visit(this);
  7310. var value = ast.value.visit(this);
  7311. if (receiver !== ast.receiver || value !== ast.value) {
  7312. return new PropertyWrite(ast.span, receiver, ast.name, value);
  7313. }
  7314. return ast;
  7315. };
  7316. AstMemoryEfficientTransformer.prototype.visitSafePropertyRead = function (ast, context) {
  7317. var receiver = ast.receiver.visit(this);
  7318. if (receiver !== ast.receiver) {
  7319. return new SafePropertyRead(ast.span, receiver, ast.name);
  7320. }
  7321. return ast;
  7322. };
  7323. AstMemoryEfficientTransformer.prototype.visitMethodCall = function (ast, context) {
  7324. var receiver = ast.receiver.visit(this);
  7325. var args = this.visitAll(ast.args);
  7326. if (receiver !== ast.receiver || args !== ast.args) {
  7327. return new MethodCall(ast.span, receiver, ast.name, args);
  7328. }
  7329. return ast;
  7330. };
  7331. AstMemoryEfficientTransformer.prototype.visitSafeMethodCall = function (ast, context) {
  7332. var receiver = ast.receiver.visit(this);
  7333. var args = this.visitAll(ast.args);
  7334. if (receiver !== ast.receiver || args !== ast.args) {
  7335. return new SafeMethodCall(ast.span, receiver, ast.name, args);
  7336. }
  7337. return ast;
  7338. };
  7339. AstMemoryEfficientTransformer.prototype.visitFunctionCall = function (ast, context) {
  7340. var target = ast.target && ast.target.visit(this);
  7341. var args = this.visitAll(ast.args);
  7342. if (target !== ast.target || args !== ast.args) {
  7343. return new FunctionCall(ast.span, target, args);
  7344. }
  7345. return ast;
  7346. };
  7347. AstMemoryEfficientTransformer.prototype.visitLiteralArray = function (ast, context) {
  7348. var expressions = this.visitAll(ast.expressions);
  7349. if (expressions !== ast.expressions) {
  7350. return new LiteralArray(ast.span, expressions);
  7351. }
  7352. return ast;
  7353. };
  7354. AstMemoryEfficientTransformer.prototype.visitLiteralMap = function (ast, context) {
  7355. var values = this.visitAll(ast.values);
  7356. if (values !== ast.values) {
  7357. return new LiteralMap(ast.span, ast.keys, values);
  7358. }
  7359. return ast;
  7360. };
  7361. AstMemoryEfficientTransformer.prototype.visitBinary = function (ast, context) {
  7362. var left = ast.left.visit(this);
  7363. var right = ast.right.visit(this);
  7364. if (left !== ast.left || right !== ast.right) {
  7365. return new Binary(ast.span, ast.operation, left, right);
  7366. }
  7367. return ast;
  7368. };
  7369. AstMemoryEfficientTransformer.prototype.visitPrefixNot = function (ast, context) {
  7370. var expression = ast.expression.visit(this);
  7371. if (expression !== ast.expression) {
  7372. return new PrefixNot(ast.span, expression);
  7373. }
  7374. return ast;
  7375. };
  7376. AstMemoryEfficientTransformer.prototype.visitNonNullAssert = function (ast, context) {
  7377. var expression = ast.expression.visit(this);
  7378. if (expression !== ast.expression) {
  7379. return new NonNullAssert(ast.span, expression);
  7380. }
  7381. return ast;
  7382. };
  7383. AstMemoryEfficientTransformer.prototype.visitConditional = function (ast, context) {
  7384. var condition = ast.condition.visit(this);
  7385. var trueExp = ast.trueExp.visit(this);
  7386. var falseExp = ast.falseExp.visit(this);
  7387. if (condition !== ast.condition || trueExp !== ast.trueExp || falseExp !== ast.falseExp) {
  7388. return new Conditional(ast.span, condition, trueExp, falseExp);
  7389. }
  7390. return ast;
  7391. };
  7392. AstMemoryEfficientTransformer.prototype.visitPipe = function (ast, context) {
  7393. var exp = ast.exp.visit(this);
  7394. var args = this.visitAll(ast.args);
  7395. if (exp !== ast.exp || args !== ast.args) {
  7396. return new BindingPipe(ast.span, exp, ast.name, args);
  7397. }
  7398. return ast;
  7399. };
  7400. AstMemoryEfficientTransformer.prototype.visitKeyedRead = function (ast, context) {
  7401. var obj = ast.obj.visit(this);
  7402. var key = ast.key.visit(this);
  7403. if (obj !== ast.obj || key !== ast.key) {
  7404. return new KeyedRead(ast.span, obj, key);
  7405. }
  7406. return ast;
  7407. };
  7408. AstMemoryEfficientTransformer.prototype.visitKeyedWrite = function (ast, context) {
  7409. var obj = ast.obj.visit(this);
  7410. var key = ast.key.visit(this);
  7411. var value = ast.value.visit(this);
  7412. if (obj !== ast.obj || key !== ast.key || value !== ast.value) {
  7413. return new KeyedWrite(ast.span, obj, key, value);
  7414. }
  7415. return ast;
  7416. };
  7417. AstMemoryEfficientTransformer.prototype.visitAll = function (asts) {
  7418. var res = new Array(asts.length);
  7419. var modified = false;
  7420. for (var i = 0; i < asts.length; ++i) {
  7421. var original = asts[i];
  7422. var value = original.visit(this);
  7423. res[i] = value;
  7424. modified = modified || value !== original;
  7425. }
  7426. return modified ? res : asts;
  7427. };
  7428. AstMemoryEfficientTransformer.prototype.visitChain = function (ast, context) {
  7429. var expressions = this.visitAll(ast.expressions);
  7430. if (expressions !== ast.expressions) {
  7431. return new Chain(ast.span, expressions);
  7432. }
  7433. return ast;
  7434. };
  7435. AstMemoryEfficientTransformer.prototype.visitQuote = function (ast, context) { return ast; };
  7436. return AstMemoryEfficientTransformer;
  7437. }());
  7438. function visitAstChildren(ast, visitor, context) {
  7439. function visit(ast) {
  7440. visitor.visit && visitor.visit(ast, context) || ast.visit(visitor, context);
  7441. }
  7442. function visitAll(asts) { asts.forEach(visit); }
  7443. ast.visit({
  7444. visitBinary: function (ast) {
  7445. visit(ast.left);
  7446. visit(ast.right);
  7447. },
  7448. visitChain: function (ast) { visitAll(ast.expressions); },
  7449. visitConditional: function (ast) {
  7450. visit(ast.condition);
  7451. visit(ast.trueExp);
  7452. visit(ast.falseExp);
  7453. },
  7454. visitFunctionCall: function (ast) {
  7455. if (ast.target) {
  7456. visit(ast.target);
  7457. }
  7458. visitAll(ast.args);
  7459. },
  7460. visitImplicitReceiver: function (ast) { },
  7461. visitInterpolation: function (ast) { visitAll(ast.expressions); },
  7462. visitKeyedRead: function (ast) {
  7463. visit(ast.obj);
  7464. visit(ast.key);
  7465. },
  7466. visitKeyedWrite: function (ast) {
  7467. visit(ast.obj);
  7468. visit(ast.key);
  7469. visit(ast.obj);
  7470. },
  7471. visitLiteralArray: function (ast) { visitAll(ast.expressions); },
  7472. visitLiteralMap: function (ast) { },
  7473. visitLiteralPrimitive: function (ast) { },
  7474. visitMethodCall: function (ast) {
  7475. visit(ast.receiver);
  7476. visitAll(ast.args);
  7477. },
  7478. visitPipe: function (ast) {
  7479. visit(ast.exp);
  7480. visitAll(ast.args);
  7481. },
  7482. visitPrefixNot: function (ast) { visit(ast.expression); },
  7483. visitNonNullAssert: function (ast) { visit(ast.expression); },
  7484. visitPropertyRead: function (ast) { visit(ast.receiver); },
  7485. visitPropertyWrite: function (ast) {
  7486. visit(ast.receiver);
  7487. visit(ast.value);
  7488. },
  7489. visitQuote: function (ast) { },
  7490. visitSafeMethodCall: function (ast) {
  7491. visit(ast.receiver);
  7492. visitAll(ast.args);
  7493. },
  7494. visitSafePropertyRead: function (ast) { visit(ast.receiver); },
  7495. });
  7496. }
  7497. // Bindings
  7498. var ParsedProperty = /** @class */ (function () {
  7499. function ParsedProperty(name, expression, type, sourceSpan) {
  7500. this.name = name;
  7501. this.expression = expression;
  7502. this.type = type;
  7503. this.sourceSpan = sourceSpan;
  7504. this.isLiteral = this.type === exports.ParsedPropertyType.LITERAL_ATTR;
  7505. this.isAnimation = this.type === exports.ParsedPropertyType.ANIMATION;
  7506. }
  7507. return ParsedProperty;
  7508. }());
  7509. (function (ParsedPropertyType) {
  7510. ParsedPropertyType[ParsedPropertyType["DEFAULT"] = 0] = "DEFAULT";
  7511. ParsedPropertyType[ParsedPropertyType["LITERAL_ATTR"] = 1] = "LITERAL_ATTR";
  7512. ParsedPropertyType[ParsedPropertyType["ANIMATION"] = 2] = "ANIMATION";
  7513. })(exports.ParsedPropertyType || (exports.ParsedPropertyType = {}));
  7514. var ParsedEvent = /** @class */ (function () {
  7515. // Regular events have a target
  7516. // Animation events have a phase
  7517. function ParsedEvent(name, targetOrPhase, type, handler, sourceSpan, handlerSpan) {
  7518. this.name = name;
  7519. this.targetOrPhase = targetOrPhase;
  7520. this.type = type;
  7521. this.handler = handler;
  7522. this.sourceSpan = sourceSpan;
  7523. this.handlerSpan = handlerSpan;
  7524. }
  7525. return ParsedEvent;
  7526. }());
  7527. var ParsedVariable = /** @class */ (function () {
  7528. function ParsedVariable(name, value, sourceSpan) {
  7529. this.name = name;
  7530. this.value = value;
  7531. this.sourceSpan = sourceSpan;
  7532. }
  7533. return ParsedVariable;
  7534. }());
  7535. var BoundElementProperty = /** @class */ (function () {
  7536. function BoundElementProperty(name, type, securityContext, value, unit, sourceSpan) {
  7537. this.name = name;
  7538. this.type = type;
  7539. this.securityContext = securityContext;
  7540. this.value = value;
  7541. this.unit = unit;
  7542. this.sourceSpan = sourceSpan;
  7543. }
  7544. return BoundElementProperty;
  7545. }());
  7546. /**
  7547. * @license
  7548. * Copyright Google Inc. All Rights Reserved.
  7549. *
  7550. * Use of this source code is governed by an MIT-style license that can be
  7551. * found in the LICENSE file at https://angular.io/license
  7552. */
  7553. var EventHandlerVars = /** @class */ (function () {
  7554. function EventHandlerVars() {
  7555. }
  7556. EventHandlerVars.event = variable('$event');
  7557. return EventHandlerVars;
  7558. }());
  7559. var ConvertActionBindingResult = /** @class */ (function () {
  7560. function ConvertActionBindingResult(
  7561. /**
  7562. * Render2 compatible statements,
  7563. */
  7564. stmts,
  7565. /**
  7566. * Variable name used with render2 compatible statements.
  7567. */
  7568. allowDefault) {
  7569. this.stmts = stmts;
  7570. this.allowDefault = allowDefault;
  7571. /**
  7572. * This is bit of a hack. It converts statements which render2 expects to statements which are
  7573. * expected by render3.
  7574. *
  7575. * Example: `<div click="doSomething($event)">` will generate:
  7576. *
  7577. * Render3:
  7578. * ```
  7579. * const pd_b:any = ((<any>ctx.doSomething($event)) !== false);
  7580. * return pd_b;
  7581. * ```
  7582. *
  7583. * but render2 expects:
  7584. * ```
  7585. * return ctx.doSomething($event);
  7586. * ```
  7587. */
  7588. // TODO(misko): remove this hack once we no longer support ViewEngine.
  7589. this.render3Stmts = stmts.map(function (statement) {
  7590. if (statement instanceof DeclareVarStmt && statement.name == allowDefault.name &&
  7591. statement.value instanceof BinaryOperatorExpr) {
  7592. var lhs = statement.value.lhs;
  7593. return new ReturnStatement(lhs.value);
  7594. }
  7595. return statement;
  7596. });
  7597. }
  7598. return ConvertActionBindingResult;
  7599. }());
  7600. /**
  7601. * Converts the given expression AST into an executable output AST, assuming the expression is
  7602. * used in an action binding (e.g. an event handler).
  7603. */
  7604. function convertActionBinding(localResolver, implicitReceiver, action, bindingId, interpolationFunction, baseSourceSpan) {
  7605. if (!localResolver) {
  7606. localResolver = new DefaultLocalResolver();
  7607. }
  7608. var actionWithoutBuiltins = convertPropertyBindingBuiltins({
  7609. createLiteralArrayConverter: function (argCount) {
  7610. // Note: no caching for literal arrays in actions.
  7611. return function (args) { return literalArr(args); };
  7612. },
  7613. createLiteralMapConverter: function (keys) {
  7614. // Note: no caching for literal maps in actions.
  7615. return function (values) {
  7616. var entries = keys.map(function (k, i) { return ({
  7617. key: k.key,
  7618. value: values[i],
  7619. quoted: k.quoted,
  7620. }); });
  7621. return literalMap(entries);
  7622. };
  7623. },
  7624. createPipeConverter: function (name) {
  7625. throw new Error("Illegal State: Actions are not allowed to contain pipes. Pipe: " + name);
  7626. }
  7627. }, action);
  7628. var visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction, baseSourceSpan);
  7629. var actionStmts = [];
  7630. flattenStatements(actionWithoutBuiltins.visit(visitor, _Mode.Statement), actionStmts);
  7631. prependTemporaryDecls(visitor.temporaryCount, bindingId, actionStmts);
  7632. if (visitor.usesImplicitReceiver) {
  7633. localResolver.notifyImplicitReceiverUse();
  7634. }
  7635. var lastIndex = actionStmts.length - 1;
  7636. var preventDefaultVar = null;
  7637. if (lastIndex >= 0) {
  7638. var lastStatement = actionStmts[lastIndex];
  7639. var returnExpr = convertStmtIntoExpression(lastStatement);
  7640. if (returnExpr) {
  7641. // Note: We need to cast the result of the method call to dynamic,
  7642. // as it might be a void method!
  7643. preventDefaultVar = createPreventDefaultVar(bindingId);
  7644. actionStmts[lastIndex] =
  7645. preventDefaultVar.set(returnExpr.cast(DYNAMIC_TYPE).notIdentical(literal(false)))
  7646. .toDeclStmt(null, [exports.StmtModifier.Final]);
  7647. }
  7648. }
  7649. return new ConvertActionBindingResult(actionStmts, preventDefaultVar);
  7650. }
  7651. function convertPropertyBindingBuiltins(converterFactory, ast) {
  7652. return convertBuiltins(converterFactory, ast);
  7653. }
  7654. var ConvertPropertyBindingResult = /** @class */ (function () {
  7655. function ConvertPropertyBindingResult(stmts, currValExpr) {
  7656. this.stmts = stmts;
  7657. this.currValExpr = currValExpr;
  7658. }
  7659. return ConvertPropertyBindingResult;
  7660. }());
  7661. var BindingForm;
  7662. (function (BindingForm) {
  7663. // The general form of binding expression, supports all expressions.
  7664. BindingForm[BindingForm["General"] = 0] = "General";
  7665. // Try to generate a simple binding (no temporaries or statements)
  7666. // otherwise generate a general binding
  7667. BindingForm[BindingForm["TrySimple"] = 1] = "TrySimple";
  7668. })(BindingForm || (BindingForm = {}));
  7669. /**
  7670. * Converts the given expression AST into an executable output AST, assuming the expression
  7671. * is used in property binding. The expression has to be preprocessed via
  7672. * `convertPropertyBindingBuiltins`.
  7673. */
  7674. function convertPropertyBinding(localResolver, implicitReceiver, expressionWithoutBuiltins, bindingId, form, interpolationFunction) {
  7675. if (!localResolver) {
  7676. localResolver = new DefaultLocalResolver();
  7677. }
  7678. var currValExpr = createCurrValueExpr(bindingId);
  7679. var visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction);
  7680. var outputExpr = expressionWithoutBuiltins.visit(visitor, _Mode.Expression);
  7681. var stmts = getStatementsFromVisitor(visitor, bindingId);
  7682. if (visitor.usesImplicitReceiver) {
  7683. localResolver.notifyImplicitReceiverUse();
  7684. }
  7685. if (visitor.temporaryCount === 0 && form == BindingForm.TrySimple) {
  7686. return new ConvertPropertyBindingResult([], outputExpr);
  7687. }
  7688. stmts.push(currValExpr.set(outputExpr).toDeclStmt(DYNAMIC_TYPE, [exports.StmtModifier.Final]));
  7689. return new ConvertPropertyBindingResult(stmts, currValExpr);
  7690. }
  7691. /**
  7692. * Given some expression, such as a binding or interpolation expression, and a context expression to
  7693. * look values up on, visit each facet of the given expression resolving values from the context
  7694. * expression such that a list of arguments can be derived from the found values that can be used as
  7695. * arguments to an external update instruction.
  7696. *
  7697. * @param localResolver The resolver to use to look up expressions by name appropriately
  7698. * @param contextVariableExpression The expression representing the context variable used to create
  7699. * the final argument expressions
  7700. * @param expressionWithArgumentsToExtract The expression to visit to figure out what values need to
  7701. * be resolved and what arguments list to build.
  7702. * @param bindingId A name prefix used to create temporary variable names if they're needed for the
  7703. * arguments generated
  7704. * @returns An array of expressions that can be passed as arguments to instruction expressions like
  7705. * `o.importExpr(R3.propertyInterpolate).callFn(result)`
  7706. */
  7707. function convertUpdateArguments(localResolver, contextVariableExpression, expressionWithArgumentsToExtract, bindingId) {
  7708. var visitor = new _AstToIrVisitor(localResolver, contextVariableExpression, bindingId, undefined);
  7709. var outputExpr = expressionWithArgumentsToExtract.visit(visitor, _Mode.Expression);
  7710. if (visitor.usesImplicitReceiver) {
  7711. localResolver.notifyImplicitReceiverUse();
  7712. }
  7713. var stmts = getStatementsFromVisitor(visitor, bindingId);
  7714. // Removing the first argument, because it was a length for ViewEngine, not Ivy.
  7715. var args = outputExpr.args.slice(1);
  7716. if (expressionWithArgumentsToExtract instanceof Interpolation) {
  7717. // If we're dealing with an interpolation of 1 value with an empty prefix and suffix, reduce the
  7718. // args returned to just the value, because we're going to pass it to a special instruction.
  7719. var strings = expressionWithArgumentsToExtract.strings;
  7720. if (args.length === 3 && strings[0] === '' && strings[1] === '') {
  7721. // Single argument interpolate instructions.
  7722. args = [args[1]];
  7723. }
  7724. else if (args.length >= 19) {
  7725. // 19 or more arguments must be passed to the `interpolateV`-style instructions, which accept
  7726. // an array of arguments
  7727. args = [literalArr(args)];
  7728. }
  7729. }
  7730. return { stmts: stmts, args: args };
  7731. }
  7732. function getStatementsFromVisitor(visitor, bindingId) {
  7733. var stmts = [];
  7734. for (var i = 0; i < visitor.temporaryCount; i++) {
  7735. stmts.push(temporaryDeclaration(bindingId, i));
  7736. }
  7737. return stmts;
  7738. }
  7739. function convertBuiltins(converterFactory, ast) {
  7740. var visitor = new _BuiltinAstConverter(converterFactory);
  7741. return ast.visit(visitor);
  7742. }
  7743. function temporaryName(bindingId, temporaryNumber) {
  7744. return "tmp_" + bindingId + "_" + temporaryNumber;
  7745. }
  7746. function temporaryDeclaration(bindingId, temporaryNumber) {
  7747. return new DeclareVarStmt(temporaryName(bindingId, temporaryNumber), NULL_EXPR);
  7748. }
  7749. function prependTemporaryDecls(temporaryCount, bindingId, statements) {
  7750. for (var i = temporaryCount - 1; i >= 0; i--) {
  7751. statements.unshift(temporaryDeclaration(bindingId, i));
  7752. }
  7753. }
  7754. var _Mode;
  7755. (function (_Mode) {
  7756. _Mode[_Mode["Statement"] = 0] = "Statement";
  7757. _Mode[_Mode["Expression"] = 1] = "Expression";
  7758. })(_Mode || (_Mode = {}));
  7759. function ensureStatementMode(mode, ast) {
  7760. if (mode !== _Mode.Statement) {
  7761. throw new Error("Expected a statement, but saw " + ast);
  7762. }
  7763. }
  7764. function ensureExpressionMode(mode, ast) {
  7765. if (mode !== _Mode.Expression) {
  7766. throw new Error("Expected an expression, but saw " + ast);
  7767. }
  7768. }
  7769. function convertToStatementIfNeeded(mode, expr) {
  7770. if (mode === _Mode.Statement) {
  7771. return expr.toStmt();
  7772. }
  7773. else {
  7774. return expr;
  7775. }
  7776. }
  7777. var _BuiltinAstConverter = /** @class */ (function (_super) {
  7778. __extends(_BuiltinAstConverter, _super);
  7779. function _BuiltinAstConverter(_converterFactory) {
  7780. var _this = _super.call(this) || this;
  7781. _this._converterFactory = _converterFactory;
  7782. return _this;
  7783. }
  7784. _BuiltinAstConverter.prototype.visitPipe = function (ast, context) {
  7785. var _this = this;
  7786. var args = __spread([ast.exp], ast.args).map(function (ast) { return ast.visit(_this, context); });
  7787. return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createPipeConverter(ast.name, args.length));
  7788. };
  7789. _BuiltinAstConverter.prototype.visitLiteralArray = function (ast, context) {
  7790. var _this = this;
  7791. var args = ast.expressions.map(function (ast) { return ast.visit(_this, context); });
  7792. return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createLiteralArrayConverter(ast.expressions.length));
  7793. };
  7794. _BuiltinAstConverter.prototype.visitLiteralMap = function (ast, context) {
  7795. var _this = this;
  7796. var args = ast.values.map(function (ast) { return ast.visit(_this, context); });
  7797. return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createLiteralMapConverter(ast.keys));
  7798. };
  7799. return _BuiltinAstConverter;
  7800. }(AstTransformer$1));
  7801. var _AstToIrVisitor = /** @class */ (function () {
  7802. function _AstToIrVisitor(_localResolver, _implicitReceiver, bindingId, interpolationFunction, baseSourceSpan) {
  7803. this._localResolver = _localResolver;
  7804. this._implicitReceiver = _implicitReceiver;
  7805. this.bindingId = bindingId;
  7806. this.interpolationFunction = interpolationFunction;
  7807. this.baseSourceSpan = baseSourceSpan;
  7808. this._nodeMap = new Map();
  7809. this._resultMap = new Map();
  7810. this._currentTemporary = 0;
  7811. this.temporaryCount = 0;
  7812. this.usesImplicitReceiver = false;
  7813. }
  7814. _AstToIrVisitor.prototype.visitBinary = function (ast, mode) {
  7815. var op;
  7816. switch (ast.operation) {
  7817. case '+':
  7818. op = exports.BinaryOperator.Plus;
  7819. break;
  7820. case '-':
  7821. op = exports.BinaryOperator.Minus;
  7822. break;
  7823. case '*':
  7824. op = exports.BinaryOperator.Multiply;
  7825. break;
  7826. case '/':
  7827. op = exports.BinaryOperator.Divide;
  7828. break;
  7829. case '%':
  7830. op = exports.BinaryOperator.Modulo;
  7831. break;
  7832. case '&&':
  7833. op = exports.BinaryOperator.And;
  7834. break;
  7835. case '||':
  7836. op = exports.BinaryOperator.Or;
  7837. break;
  7838. case '==':
  7839. op = exports.BinaryOperator.Equals;
  7840. break;
  7841. case '!=':
  7842. op = exports.BinaryOperator.NotEquals;
  7843. break;
  7844. case '===':
  7845. op = exports.BinaryOperator.Identical;
  7846. break;
  7847. case '!==':
  7848. op = exports.BinaryOperator.NotIdentical;
  7849. break;
  7850. case '<':
  7851. op = exports.BinaryOperator.Lower;
  7852. break;
  7853. case '>':
  7854. op = exports.BinaryOperator.Bigger;
  7855. break;
  7856. case '<=':
  7857. op = exports.BinaryOperator.LowerEquals;
  7858. break;
  7859. case '>=':
  7860. op = exports.BinaryOperator.BiggerEquals;
  7861. break;
  7862. default:
  7863. throw new Error("Unsupported operation " + ast.operation);
  7864. }
  7865. return convertToStatementIfNeeded(mode, new BinaryOperatorExpr(op, this._visit(ast.left, _Mode.Expression), this._visit(ast.right, _Mode.Expression), undefined, this.convertSourceSpan(ast.span)));
  7866. };
  7867. _AstToIrVisitor.prototype.visitChain = function (ast, mode) {
  7868. ensureStatementMode(mode, ast);
  7869. return this.visitAll(ast.expressions, mode);
  7870. };
  7871. _AstToIrVisitor.prototype.visitConditional = function (ast, mode) {
  7872. var value = this._visit(ast.condition, _Mode.Expression);
  7873. return convertToStatementIfNeeded(mode, value.conditional(this._visit(ast.trueExp, _Mode.Expression), this._visit(ast.falseExp, _Mode.Expression), this.convertSourceSpan(ast.span)));
  7874. };
  7875. _AstToIrVisitor.prototype.visitPipe = function (ast, mode) {
  7876. throw new Error("Illegal state: Pipes should have been converted into functions. Pipe: " + ast.name);
  7877. };
  7878. _AstToIrVisitor.prototype.visitFunctionCall = function (ast, mode) {
  7879. var convertedArgs = this.visitAll(ast.args, _Mode.Expression);
  7880. var fnResult;
  7881. if (ast instanceof BuiltinFunctionCall) {
  7882. fnResult = ast.converter(convertedArgs);
  7883. }
  7884. else {
  7885. fnResult = this._visit(ast.target, _Mode.Expression)
  7886. .callFn(convertedArgs, this.convertSourceSpan(ast.span));
  7887. }
  7888. return convertToStatementIfNeeded(mode, fnResult);
  7889. };
  7890. _AstToIrVisitor.prototype.visitImplicitReceiver = function (ast, mode) {
  7891. ensureExpressionMode(mode, ast);
  7892. this.usesImplicitReceiver = true;
  7893. return this._implicitReceiver;
  7894. };
  7895. _AstToIrVisitor.prototype.visitInterpolation = function (ast, mode) {
  7896. ensureExpressionMode(mode, ast);
  7897. var args = [literal(ast.expressions.length)];
  7898. for (var i = 0; i < ast.strings.length - 1; i++) {
  7899. args.push(literal(ast.strings[i]));
  7900. args.push(this._visit(ast.expressions[i], _Mode.Expression));
  7901. }
  7902. args.push(literal(ast.strings[ast.strings.length - 1]));
  7903. if (this.interpolationFunction) {
  7904. return this.interpolationFunction(args);
  7905. }
  7906. return ast.expressions.length <= 9 ?
  7907. importExpr(Identifiers.inlineInterpolate).callFn(args) :
  7908. importExpr(Identifiers.interpolate).callFn([
  7909. args[0], literalArr(args.slice(1), undefined, this.convertSourceSpan(ast.span))
  7910. ]);
  7911. };
  7912. _AstToIrVisitor.prototype.visitKeyedRead = function (ast, mode) {
  7913. var leftMostSafe = this.leftMostSafeNode(ast);
  7914. if (leftMostSafe) {
  7915. return this.convertSafeAccess(ast, leftMostSafe, mode);
  7916. }
  7917. else {
  7918. return convertToStatementIfNeeded(mode, this._visit(ast.obj, _Mode.Expression).key(this._visit(ast.key, _Mode.Expression)));
  7919. }
  7920. };
  7921. _AstToIrVisitor.prototype.visitKeyedWrite = function (ast, mode) {
  7922. var obj = this._visit(ast.obj, _Mode.Expression);
  7923. var key = this._visit(ast.key, _Mode.Expression);
  7924. var value = this._visit(ast.value, _Mode.Expression);
  7925. return convertToStatementIfNeeded(mode, obj.key(key).set(value));
  7926. };
  7927. _AstToIrVisitor.prototype.visitLiteralArray = function (ast, mode) {
  7928. throw new Error("Illegal State: literal arrays should have been converted into functions");
  7929. };
  7930. _AstToIrVisitor.prototype.visitLiteralMap = function (ast, mode) {
  7931. throw new Error("Illegal State: literal maps should have been converted into functions");
  7932. };
  7933. _AstToIrVisitor.prototype.visitLiteralPrimitive = function (ast, mode) {
  7934. // For literal values of null, undefined, true, or false allow type interference
  7935. // to infer the type.
  7936. var type = ast.value === null || ast.value === undefined || ast.value === true || ast.value === true ?
  7937. INFERRED_TYPE :
  7938. undefined;
  7939. return convertToStatementIfNeeded(mode, literal(ast.value, type, this.convertSourceSpan(ast.span)));
  7940. };
  7941. _AstToIrVisitor.prototype._getLocal = function (name) { return this._localResolver.getLocal(name); };
  7942. _AstToIrVisitor.prototype.visitMethodCall = function (ast, mode) {
  7943. if (ast.receiver instanceof ImplicitReceiver && ast.name == '$any') {
  7944. var args = this.visitAll(ast.args, _Mode.Expression);
  7945. if (args.length != 1) {
  7946. throw new Error("Invalid call to $any, expected 1 argument but received " + (args.length || 'none'));
  7947. }
  7948. return args[0].cast(DYNAMIC_TYPE, this.convertSourceSpan(ast.span));
  7949. }
  7950. var leftMostSafe = this.leftMostSafeNode(ast);
  7951. if (leftMostSafe) {
  7952. return this.convertSafeAccess(ast, leftMostSafe, mode);
  7953. }
  7954. else {
  7955. var args = this.visitAll(ast.args, _Mode.Expression);
  7956. var prevUsesImplicitReceiver = this.usesImplicitReceiver;
  7957. var result = null;
  7958. var receiver = this._visit(ast.receiver, _Mode.Expression);
  7959. if (receiver === this._implicitReceiver) {
  7960. var varExpr = this._getLocal(ast.name);
  7961. if (varExpr) {
  7962. // Restore the previous "usesImplicitReceiver" state since the implicit
  7963. // receiver has been replaced with a resolved local expression.
  7964. this.usesImplicitReceiver = prevUsesImplicitReceiver;
  7965. result = varExpr.callFn(args);
  7966. }
  7967. }
  7968. if (result == null) {
  7969. result = receiver.callMethod(ast.name, args, this.convertSourceSpan(ast.span));
  7970. }
  7971. return convertToStatementIfNeeded(mode, result);
  7972. }
  7973. };
  7974. _AstToIrVisitor.prototype.visitPrefixNot = function (ast, mode) {
  7975. return convertToStatementIfNeeded(mode, not(this._visit(ast.expression, _Mode.Expression)));
  7976. };
  7977. _AstToIrVisitor.prototype.visitNonNullAssert = function (ast, mode) {
  7978. return convertToStatementIfNeeded(mode, assertNotNull(this._visit(ast.expression, _Mode.Expression)));
  7979. };
  7980. _AstToIrVisitor.prototype.visitPropertyRead = function (ast, mode) {
  7981. var leftMostSafe = this.leftMostSafeNode(ast);
  7982. if (leftMostSafe) {
  7983. return this.convertSafeAccess(ast, leftMostSafe, mode);
  7984. }
  7985. else {
  7986. var result = null;
  7987. var prevUsesImplicitReceiver = this.usesImplicitReceiver;
  7988. var receiver = this._visit(ast.receiver, _Mode.Expression);
  7989. if (receiver === this._implicitReceiver) {
  7990. result = this._getLocal(ast.name);
  7991. if (result) {
  7992. // Restore the previous "usesImplicitReceiver" state since the implicit
  7993. // receiver has been replaced with a resolved local expression.
  7994. this.usesImplicitReceiver = prevUsesImplicitReceiver;
  7995. }
  7996. }
  7997. if (result == null) {
  7998. result = receiver.prop(ast.name);
  7999. }
  8000. return convertToStatementIfNeeded(mode, result);
  8001. }
  8002. };
  8003. _AstToIrVisitor.prototype.visitPropertyWrite = function (ast, mode) {
  8004. var receiver = this._visit(ast.receiver, _Mode.Expression);
  8005. var prevUsesImplicitReceiver = this.usesImplicitReceiver;
  8006. var varExpr = null;
  8007. if (receiver === this._implicitReceiver) {
  8008. var localExpr = this._getLocal(ast.name);
  8009. if (localExpr) {
  8010. if (localExpr instanceof ReadPropExpr) {
  8011. // If the local variable is a property read expression, it's a reference
  8012. // to a 'context.property' value and will be used as the target of the
  8013. // write expression.
  8014. varExpr = localExpr;
  8015. // Restore the previous "usesImplicitReceiver" state since the implicit
  8016. // receiver has been replaced with a resolved local expression.
  8017. this.usesImplicitReceiver = prevUsesImplicitReceiver;
  8018. }
  8019. else {
  8020. // Otherwise it's an error.
  8021. throw new Error('Cannot assign to a reference or variable!');
  8022. }
  8023. }
  8024. }
  8025. // If no local expression could be produced, use the original receiver's
  8026. // property as the target.
  8027. if (varExpr === null) {
  8028. varExpr = receiver.prop(ast.name);
  8029. }
  8030. return convertToStatementIfNeeded(mode, varExpr.set(this._visit(ast.value, _Mode.Expression)));
  8031. };
  8032. _AstToIrVisitor.prototype.visitSafePropertyRead = function (ast, mode) {
  8033. return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
  8034. };
  8035. _AstToIrVisitor.prototype.visitSafeMethodCall = function (ast, mode) {
  8036. return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
  8037. };
  8038. _AstToIrVisitor.prototype.visitAll = function (asts, mode) {
  8039. var _this = this;
  8040. return asts.map(function (ast) { return _this._visit(ast, mode); });
  8041. };
  8042. _AstToIrVisitor.prototype.visitQuote = function (ast, mode) {
  8043. throw new Error("Quotes are not supported for evaluation!\n Statement: " + ast.uninterpretedExpression + " located at " + ast.location);
  8044. };
  8045. _AstToIrVisitor.prototype._visit = function (ast, mode) {
  8046. var result = this._resultMap.get(ast);
  8047. if (result)
  8048. return result;
  8049. return (this._nodeMap.get(ast) || ast).visit(this, mode);
  8050. };
  8051. _AstToIrVisitor.prototype.convertSafeAccess = function (ast, leftMostSafe, mode) {
  8052. // If the expression contains a safe access node on the left it needs to be converted to
  8053. // an expression that guards the access to the member by checking the receiver for blank. As
  8054. // execution proceeds from left to right, the left most part of the expression must be guarded
  8055. // first but, because member access is left associative, the right side of the expression is at
  8056. // the top of the AST. The desired result requires lifting a copy of the the left part of the
  8057. // expression up to test it for blank before generating the unguarded version.
  8058. // Consider, for example the following expression: a?.b.c?.d.e
  8059. // This results in the ast:
  8060. // .
  8061. // / \
  8062. // ?. e
  8063. // / \
  8064. // . d
  8065. // / \
  8066. // ?. c
  8067. // / \
  8068. // a b
  8069. // The following tree should be generated:
  8070. //
  8071. // /---- ? ----\
  8072. // / | \
  8073. // a /--- ? ---\ null
  8074. // / | \
  8075. // . . null
  8076. // / \ / \
  8077. // . c . e
  8078. // / \ / \
  8079. // a b . d
  8080. // / \
  8081. // . c
  8082. // / \
  8083. // a b
  8084. //
  8085. // Notice that the first guard condition is the left hand of the left most safe access node
  8086. // which comes in as leftMostSafe to this routine.
  8087. var guardedExpression = this._visit(leftMostSafe.receiver, _Mode.Expression);
  8088. var temporary = undefined;
  8089. if (this.needsTemporary(leftMostSafe.receiver)) {
  8090. // If the expression has method calls or pipes then we need to save the result into a
  8091. // temporary variable to avoid calling stateful or impure code more than once.
  8092. temporary = this.allocateTemporary();
  8093. // Preserve the result in the temporary variable
  8094. guardedExpression = temporary.set(guardedExpression);
  8095. // Ensure all further references to the guarded expression refer to the temporary instead.
  8096. this._resultMap.set(leftMostSafe.receiver, temporary);
  8097. }
  8098. var condition = guardedExpression.isBlank();
  8099. // Convert the ast to an unguarded access to the receiver's member. The map will substitute
  8100. // leftMostNode with its unguarded version in the call to `this.visit()`.
  8101. if (leftMostSafe instanceof SafeMethodCall) {
  8102. this._nodeMap.set(leftMostSafe, new MethodCall(leftMostSafe.span, leftMostSafe.receiver, leftMostSafe.name, leftMostSafe.args));
  8103. }
  8104. else {
  8105. this._nodeMap.set(leftMostSafe, new PropertyRead(leftMostSafe.span, leftMostSafe.receiver, leftMostSafe.name));
  8106. }
  8107. // Recursively convert the node now without the guarded member access.
  8108. var access = this._visit(ast, _Mode.Expression);
  8109. // Remove the mapping. This is not strictly required as the converter only traverses each node
  8110. // once but is safer if the conversion is changed to traverse the nodes more than once.
  8111. this._nodeMap.delete(leftMostSafe);
  8112. // If we allocated a temporary, release it.
  8113. if (temporary) {
  8114. this.releaseTemporary(temporary);
  8115. }
  8116. // Produce the conditional
  8117. return convertToStatementIfNeeded(mode, condition.conditional(literal(null), access));
  8118. };
  8119. // Given a expression of the form a?.b.c?.d.e the the left most safe node is
  8120. // the (a?.b). The . and ?. are left associative thus can be rewritten as:
  8121. // ((((a?.c).b).c)?.d).e. This returns the most deeply nested safe read or
  8122. // safe method call as this needs be transform initially to:
  8123. // a == null ? null : a.c.b.c?.d.e
  8124. // then to:
  8125. // a == null ? null : a.b.c == null ? null : a.b.c.d.e
  8126. _AstToIrVisitor.prototype.leftMostSafeNode = function (ast) {
  8127. var _this = this;
  8128. var visit = function (visitor, ast) {
  8129. return (_this._nodeMap.get(ast) || ast).visit(visitor);
  8130. };
  8131. return ast.visit({
  8132. visitBinary: function (ast) { return null; },
  8133. visitChain: function (ast) { return null; },
  8134. visitConditional: function (ast) { return null; },
  8135. visitFunctionCall: function (ast) { return null; },
  8136. visitImplicitReceiver: function (ast) { return null; },
  8137. visitInterpolation: function (ast) { return null; },
  8138. visitKeyedRead: function (ast) { return visit(this, ast.obj); },
  8139. visitKeyedWrite: function (ast) { return null; },
  8140. visitLiteralArray: function (ast) { return null; },
  8141. visitLiteralMap: function (ast) { return null; },
  8142. visitLiteralPrimitive: function (ast) { return null; },
  8143. visitMethodCall: function (ast) { return visit(this, ast.receiver); },
  8144. visitPipe: function (ast) { return null; },
  8145. visitPrefixNot: function (ast) { return null; },
  8146. visitNonNullAssert: function (ast) { return null; },
  8147. visitPropertyRead: function (ast) { return visit(this, ast.receiver); },
  8148. visitPropertyWrite: function (ast) { return null; },
  8149. visitQuote: function (ast) { return null; },
  8150. visitSafeMethodCall: function (ast) { return visit(this, ast.receiver) || ast; },
  8151. visitSafePropertyRead: function (ast) {
  8152. return visit(this, ast.receiver) || ast;
  8153. }
  8154. });
  8155. };
  8156. // Returns true of the AST includes a method or a pipe indicating that, if the
  8157. // expression is used as the target of a safe property or method access then
  8158. // the expression should be stored into a temporary variable.
  8159. _AstToIrVisitor.prototype.needsTemporary = function (ast) {
  8160. var _this = this;
  8161. var visit = function (visitor, ast) {
  8162. return ast && (_this._nodeMap.get(ast) || ast).visit(visitor);
  8163. };
  8164. var visitSome = function (visitor, ast) {
  8165. return ast.some(function (ast) { return visit(visitor, ast); });
  8166. };
  8167. return ast.visit({
  8168. visitBinary: function (ast) { return visit(this, ast.left) || visit(this, ast.right); },
  8169. visitChain: function (ast) { return false; },
  8170. visitConditional: function (ast) {
  8171. return visit(this, ast.condition) || visit(this, ast.trueExp) ||
  8172. visit(this, ast.falseExp);
  8173. },
  8174. visitFunctionCall: function (ast) { return true; },
  8175. visitImplicitReceiver: function (ast) { return false; },
  8176. visitInterpolation: function (ast) { return visitSome(this, ast.expressions); },
  8177. visitKeyedRead: function (ast) { return false; },
  8178. visitKeyedWrite: function (ast) { return false; },
  8179. visitLiteralArray: function (ast) { return true; },
  8180. visitLiteralMap: function (ast) { return true; },
  8181. visitLiteralPrimitive: function (ast) { return false; },
  8182. visitMethodCall: function (ast) { return true; },
  8183. visitPipe: function (ast) { return true; },
  8184. visitPrefixNot: function (ast) { return visit(this, ast.expression); },
  8185. visitNonNullAssert: function (ast) { return visit(this, ast.expression); },
  8186. visitPropertyRead: function (ast) { return false; },
  8187. visitPropertyWrite: function (ast) { return false; },
  8188. visitQuote: function (ast) { return false; },
  8189. visitSafeMethodCall: function (ast) { return true; },
  8190. visitSafePropertyRead: function (ast) { return false; }
  8191. });
  8192. };
  8193. _AstToIrVisitor.prototype.allocateTemporary = function () {
  8194. var tempNumber = this._currentTemporary++;
  8195. this.temporaryCount = Math.max(this._currentTemporary, this.temporaryCount);
  8196. return new ReadVarExpr(temporaryName(this.bindingId, tempNumber));
  8197. };
  8198. _AstToIrVisitor.prototype.releaseTemporary = function (temporary) {
  8199. this._currentTemporary--;
  8200. if (temporary.name != temporaryName(this.bindingId, this._currentTemporary)) {
  8201. throw new Error("Temporary " + temporary.name + " released out of order");
  8202. }
  8203. };
  8204. /**
  8205. * Creates an absolute `ParseSourceSpan` from the relative `ParseSpan`.
  8206. *
  8207. * `ParseSpan` objects are relative to the start of the expression.
  8208. * This method converts these to full `ParseSourceSpan` objects that
  8209. * show where the span is within the overall source file.
  8210. *
  8211. * @param span the relative span to convert.
  8212. * @returns a `ParseSourceSpan` for the the given span or null if no
  8213. * `baseSourceSpan` was provided to this class.
  8214. */
  8215. _AstToIrVisitor.prototype.convertSourceSpan = function (span) {
  8216. if (this.baseSourceSpan) {
  8217. var start = this.baseSourceSpan.start.moveBy(span.start);
  8218. var end = this.baseSourceSpan.start.moveBy(span.end);
  8219. return new ParseSourceSpan(start, end);
  8220. }
  8221. else {
  8222. return null;
  8223. }
  8224. };
  8225. return _AstToIrVisitor;
  8226. }());
  8227. function flattenStatements(arg, output) {
  8228. if (Array.isArray(arg)) {
  8229. arg.forEach(function (entry) { return flattenStatements(entry, output); });
  8230. }
  8231. else {
  8232. output.push(arg);
  8233. }
  8234. }
  8235. var DefaultLocalResolver = /** @class */ (function () {
  8236. function DefaultLocalResolver() {
  8237. }
  8238. DefaultLocalResolver.prototype.notifyImplicitReceiverUse = function () { };
  8239. DefaultLocalResolver.prototype.getLocal = function (name) {
  8240. if (name === EventHandlerVars.event.name) {
  8241. return EventHandlerVars.event;
  8242. }
  8243. return null;
  8244. };
  8245. return DefaultLocalResolver;
  8246. }());
  8247. function createCurrValueExpr(bindingId) {
  8248. return variable("currVal_" + bindingId); // fix syntax highlighting: `
  8249. }
  8250. function createPreventDefaultVar(bindingId) {
  8251. return variable("pd_" + bindingId);
  8252. }
  8253. function convertStmtIntoExpression(stmt) {
  8254. if (stmt instanceof ExpressionStatement) {
  8255. return stmt.expr;
  8256. }
  8257. else if (stmt instanceof ReturnStatement) {
  8258. return stmt.value;
  8259. }
  8260. return null;
  8261. }
  8262. var BuiltinFunctionCall = /** @class */ (function (_super) {
  8263. __extends(BuiltinFunctionCall, _super);
  8264. function BuiltinFunctionCall(span, args, converter) {
  8265. var _this = _super.call(this, span, null, args) || this;
  8266. _this.args = args;
  8267. _this.converter = converter;
  8268. return _this;
  8269. }
  8270. return BuiltinFunctionCall;
  8271. }(FunctionCall));
  8272. /**
  8273. * @license
  8274. * Copyright Google Inc. All Rights Reserved.
  8275. *
  8276. * Use of this source code is governed by an MIT-style license that can be
  8277. * found in the LICENSE file at https://angular.io/license
  8278. */
  8279. /**
  8280. * This file is a port of shadowCSS from webcomponents.js to TypeScript.
  8281. *
  8282. * Please make sure to keep to edits in sync with the source file.
  8283. *
  8284. * Source:
  8285. * https://github.com/webcomponents/webcomponentsjs/blob/4efecd7e0e/src/ShadowCSS/ShadowCSS.js
  8286. *
  8287. * The original file level comment is reproduced below
  8288. */
  8289. /*
  8290. This is a limited shim for ShadowDOM css styling.
  8291. https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html#styles
  8292. The intention here is to support only the styling features which can be
  8293. relatively simply implemented. The goal is to allow users to avoid the
  8294. most obvious pitfalls and do so without compromising performance significantly.
  8295. For ShadowDOM styling that's not covered here, a set of best practices
  8296. can be provided that should allow users to accomplish more complex styling.
  8297. The following is a list of specific ShadowDOM styling features and a brief
  8298. discussion of the approach used to shim.
  8299. Shimmed features:
  8300. * :host, :host-context: ShadowDOM allows styling of the shadowRoot's host
  8301. element using the :host rule. To shim this feature, the :host styles are
  8302. reformatted and prefixed with a given scope name and promoted to a
  8303. document level stylesheet.
  8304. For example, given a scope name of .foo, a rule like this:
  8305. :host {
  8306. background: red;
  8307. }
  8308. }
  8309. becomes:
  8310. .foo {
  8311. background: red;
  8312. }
  8313. * encapsulation: Styles defined within ShadowDOM, apply only to
  8314. dom inside the ShadowDOM. Polymer uses one of two techniques to implement
  8315. this feature.
  8316. By default, rules are prefixed with the host element tag name
  8317. as a descendant selector. This ensures styling does not leak out of the 'top'
  8318. of the element's ShadowDOM. For example,
  8319. div {
  8320. font-weight: bold;
  8321. }
  8322. becomes:
  8323. x-foo div {
  8324. font-weight: bold;
  8325. }
  8326. becomes:
  8327. Alternatively, if WebComponents.ShadowCSS.strictStyling is set to true then
  8328. selectors are scoped by adding an attribute selector suffix to each
  8329. simple selector that contains the host element tag name. Each element
  8330. in the element's ShadowDOM template is also given the scope attribute.
  8331. Thus, these rules match only elements that have the scope attribute.
  8332. For example, given a scope name of x-foo, a rule like this:
  8333. div {
  8334. font-weight: bold;
  8335. }
  8336. becomes:
  8337. div[x-foo] {
  8338. font-weight: bold;
  8339. }
  8340. Note that elements that are dynamically added to a scope must have the scope
  8341. selector added to them manually.
  8342. * upper/lower bound encapsulation: Styles which are defined outside a
  8343. shadowRoot should not cross the ShadowDOM boundary and should not apply
  8344. inside a shadowRoot.
  8345. This styling behavior is not emulated. Some possible ways to do this that
  8346. were rejected due to complexity and/or performance concerns include: (1) reset
  8347. every possible property for every possible selector for a given scope name;
  8348. (2) re-implement css in javascript.
  8349. As an alternative, users should make sure to use selectors
  8350. specific to the scope in which they are working.
  8351. * ::distributed: This behavior is not emulated. It's often not necessary
  8352. to style the contents of a specific insertion point and instead, descendants
  8353. of the host element can be styled selectively. Users can also create an
  8354. extra node around an insertion point and style that node's contents
  8355. via descendent selectors. For example, with a shadowRoot like this:
  8356. <style>
  8357. ::content(div) {
  8358. background: red;
  8359. }
  8360. </style>
  8361. <content></content>
  8362. could become:
  8363. <style>
  8364. / *@polyfill .content-container div * /
  8365. ::content(div) {
  8366. background: red;
  8367. }
  8368. </style>
  8369. <div class="content-container">
  8370. <content></content>
  8371. </div>
  8372. Note the use of @polyfill in the comment above a ShadowDOM specific style
  8373. declaration. This is a directive to the styling shim to use the selector
  8374. in comments in lieu of the next selector when running under polyfill.
  8375. */
  8376. var ShadowCss = /** @class */ (function () {
  8377. function ShadowCss() {
  8378. this.strictStyling = true;
  8379. }
  8380. /*
  8381. * Shim some cssText with the given selector. Returns cssText that can
  8382. * be included in the document via WebComponents.ShadowCSS.addCssToDocument(css).
  8383. *
  8384. * When strictStyling is true:
  8385. * - selector is the attribute added to all elements inside the host,
  8386. * - hostSelector is the attribute added to the host itself.
  8387. */
  8388. ShadowCss.prototype.shimCssText = function (cssText, selector, hostSelector) {
  8389. if (hostSelector === void 0) { hostSelector = ''; }
  8390. var commentsWithHash = extractCommentsWithHash(cssText);
  8391. cssText = stripComments(cssText);
  8392. cssText = this._insertDirectives(cssText);
  8393. var scopedCssText = this._scopeCssText(cssText, selector, hostSelector);
  8394. return __spread([scopedCssText], commentsWithHash).join('\n');
  8395. };
  8396. ShadowCss.prototype._insertDirectives = function (cssText) {
  8397. cssText = this._insertPolyfillDirectivesInCssText(cssText);
  8398. return this._insertPolyfillRulesInCssText(cssText);
  8399. };
  8400. /*
  8401. * Process styles to convert native ShadowDOM rules that will trip
  8402. * up the css parser; we rely on decorating the stylesheet with inert rules.
  8403. *
  8404. * For example, we convert this rule:
  8405. *
  8406. * polyfill-next-selector { content: ':host menu-item'; }
  8407. * ::content menu-item {
  8408. *
  8409. * to this:
  8410. *
  8411. * scopeName menu-item {
  8412. *
  8413. **/
  8414. ShadowCss.prototype._insertPolyfillDirectivesInCssText = function (cssText) {
  8415. // Difference with webcomponents.js: does not handle comments
  8416. return cssText.replace(_cssContentNextSelectorRe, function () {
  8417. var m = [];
  8418. for (var _i = 0; _i < arguments.length; _i++) {
  8419. m[_i] = arguments[_i];
  8420. }
  8421. return m[2] + '{';
  8422. });
  8423. };
  8424. /*
  8425. * Process styles to add rules which will only apply under the polyfill
  8426. *
  8427. * For example, we convert this rule:
  8428. *
  8429. * polyfill-rule {
  8430. * content: ':host menu-item';
  8431. * ...
  8432. * }
  8433. *
  8434. * to this:
  8435. *
  8436. * scopeName menu-item {...}
  8437. *
  8438. **/
  8439. ShadowCss.prototype._insertPolyfillRulesInCssText = function (cssText) {
  8440. // Difference with webcomponents.js: does not handle comments
  8441. return cssText.replace(_cssContentRuleRe, function () {
  8442. var m = [];
  8443. for (var _i = 0; _i < arguments.length; _i++) {
  8444. m[_i] = arguments[_i];
  8445. }
  8446. var rule = m[0].replace(m[1], '').replace(m[2], '');
  8447. return m[4] + rule;
  8448. });
  8449. };
  8450. /* Ensure styles are scoped. Pseudo-scoping takes a rule like:
  8451. *
  8452. * .foo {... }
  8453. *
  8454. * and converts this to
  8455. *
  8456. * scopeName .foo { ... }
  8457. */
  8458. ShadowCss.prototype._scopeCssText = function (cssText, scopeSelector, hostSelector) {
  8459. var unscopedRules = this._extractUnscopedRulesFromCssText(cssText);
  8460. // replace :host and :host-context -shadowcsshost and -shadowcsshost respectively
  8461. cssText = this._insertPolyfillHostInCssText(cssText);
  8462. cssText = this._convertColonHost(cssText);
  8463. cssText = this._convertColonHostContext(cssText);
  8464. cssText = this._convertShadowDOMSelectors(cssText);
  8465. if (scopeSelector) {
  8466. cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector);
  8467. }
  8468. cssText = cssText + '\n' + unscopedRules;
  8469. return cssText.trim();
  8470. };
  8471. /*
  8472. * Process styles to add rules which will only apply under the polyfill
  8473. * and do not process via CSSOM. (CSSOM is destructive to rules on rare
  8474. * occasions, e.g. -webkit-calc on Safari.)
  8475. * For example, we convert this rule:
  8476. *
  8477. * @polyfill-unscoped-rule {
  8478. * content: 'menu-item';
  8479. * ... }
  8480. *
  8481. * to this:
  8482. *
  8483. * menu-item {...}
  8484. *
  8485. **/
  8486. ShadowCss.prototype._extractUnscopedRulesFromCssText = function (cssText) {
  8487. // Difference with webcomponents.js: does not handle comments
  8488. var r = '';
  8489. var m;
  8490. _cssContentUnscopedRuleRe.lastIndex = 0;
  8491. while ((m = _cssContentUnscopedRuleRe.exec(cssText)) !== null) {
  8492. var rule = m[0].replace(m[2], '').replace(m[1], m[4]);
  8493. r += rule + '\n\n';
  8494. }
  8495. return r;
  8496. };
  8497. /*
  8498. * convert a rule like :host(.foo) > .bar { }
  8499. *
  8500. * to
  8501. *
  8502. * .foo<scopeName> > .bar
  8503. */
  8504. ShadowCss.prototype._convertColonHost = function (cssText) {
  8505. return this._convertColonRule(cssText, _cssColonHostRe, this._colonHostPartReplacer);
  8506. };
  8507. /*
  8508. * convert a rule like :host-context(.foo) > .bar { }
  8509. *
  8510. * to
  8511. *
  8512. * .foo<scopeName> > .bar, .foo scopeName > .bar { }
  8513. *
  8514. * and
  8515. *
  8516. * :host-context(.foo:host) .bar { ... }
  8517. *
  8518. * to
  8519. *
  8520. * .foo<scopeName> .bar { ... }
  8521. */
  8522. ShadowCss.prototype._convertColonHostContext = function (cssText) {
  8523. return this._convertColonRule(cssText, _cssColonHostContextRe, this._colonHostContextPartReplacer);
  8524. };
  8525. ShadowCss.prototype._convertColonRule = function (cssText, regExp, partReplacer) {
  8526. // m[1] = :host(-context), m[2] = contents of (), m[3] rest of rule
  8527. return cssText.replace(regExp, function () {
  8528. var m = [];
  8529. for (var _i = 0; _i < arguments.length; _i++) {
  8530. m[_i] = arguments[_i];
  8531. }
  8532. if (m[2]) {
  8533. var parts = m[2].split(',');
  8534. var r = [];
  8535. for (var i = 0; i < parts.length; i++) {
  8536. var p = parts[i].trim();
  8537. if (!p)
  8538. break;
  8539. r.push(partReplacer(_polyfillHostNoCombinator, p, m[3]));
  8540. }
  8541. return r.join(',');
  8542. }
  8543. else {
  8544. return _polyfillHostNoCombinator + m[3];
  8545. }
  8546. });
  8547. };
  8548. ShadowCss.prototype._colonHostContextPartReplacer = function (host, part, suffix) {
  8549. if (part.indexOf(_polyfillHost) > -1) {
  8550. return this._colonHostPartReplacer(host, part, suffix);
  8551. }
  8552. else {
  8553. return host + part + suffix + ', ' + part + ' ' + host + suffix;
  8554. }
  8555. };
  8556. ShadowCss.prototype._colonHostPartReplacer = function (host, part, suffix) {
  8557. return host + part.replace(_polyfillHost, '') + suffix;
  8558. };
  8559. /*
  8560. * Convert combinators like ::shadow and pseudo-elements like ::content
  8561. * by replacing with space.
  8562. */
  8563. ShadowCss.prototype._convertShadowDOMSelectors = function (cssText) {
  8564. return _shadowDOMSelectorsRe.reduce(function (result, pattern) { return result.replace(pattern, ' '); }, cssText);
  8565. };
  8566. // change a selector like 'div' to 'name div'
  8567. ShadowCss.prototype._scopeSelectors = function (cssText, scopeSelector, hostSelector) {
  8568. var _this = this;
  8569. return processRules(cssText, function (rule) {
  8570. var selector = rule.selector;
  8571. var content = rule.content;
  8572. if (rule.selector[0] != '@') {
  8573. selector =
  8574. _this._scopeSelector(rule.selector, scopeSelector, hostSelector, _this.strictStyling);
  8575. }
  8576. else if (rule.selector.startsWith('@media') || rule.selector.startsWith('@supports') ||
  8577. rule.selector.startsWith('@page') || rule.selector.startsWith('@document')) {
  8578. content = _this._scopeSelectors(rule.content, scopeSelector, hostSelector);
  8579. }
  8580. return new CssRule(selector, content);
  8581. });
  8582. };
  8583. ShadowCss.prototype._scopeSelector = function (selector, scopeSelector, hostSelector, strict) {
  8584. var _this = this;
  8585. return selector.split(',')
  8586. .map(function (part) { return part.trim().split(_shadowDeepSelectors); })
  8587. .map(function (deepParts) {
  8588. var _a = __read(deepParts), shallowPart = _a[0], otherParts = _a.slice(1);
  8589. var applyScope = function (shallowPart) {
  8590. if (_this._selectorNeedsScoping(shallowPart, scopeSelector)) {
  8591. return strict ?
  8592. _this._applyStrictSelectorScope(shallowPart, scopeSelector, hostSelector) :
  8593. _this._applySelectorScope(shallowPart, scopeSelector, hostSelector);
  8594. }
  8595. else {
  8596. return shallowPart;
  8597. }
  8598. };
  8599. return __spread([applyScope(shallowPart)], otherParts).join(' ');
  8600. })
  8601. .join(', ');
  8602. };
  8603. ShadowCss.prototype._selectorNeedsScoping = function (selector, scopeSelector) {
  8604. var re = this._makeScopeMatcher(scopeSelector);
  8605. return !re.test(selector);
  8606. };
  8607. ShadowCss.prototype._makeScopeMatcher = function (scopeSelector) {
  8608. var lre = /\[/g;
  8609. var rre = /\]/g;
  8610. scopeSelector = scopeSelector.replace(lre, '\\[').replace(rre, '\\]');
  8611. return new RegExp('^(' + scopeSelector + ')' + _selectorReSuffix, 'm');
  8612. };
  8613. ShadowCss.prototype._applySelectorScope = function (selector, scopeSelector, hostSelector) {
  8614. // Difference from webcomponents.js: scopeSelector could not be an array
  8615. return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector);
  8616. };
  8617. // scope via name and [is=name]
  8618. ShadowCss.prototype._applySimpleSelectorScope = function (selector, scopeSelector, hostSelector) {
  8619. // In Android browser, the lastIndex is not reset when the regex is used in String.replace()
  8620. _polyfillHostRe.lastIndex = 0;
  8621. if (_polyfillHostRe.test(selector)) {
  8622. var replaceBy_1 = this.strictStyling ? "[" + hostSelector + "]" : scopeSelector;
  8623. return selector
  8624. .replace(_polyfillHostNoCombinatorRe, function (hnc, selector) {
  8625. return selector.replace(/([^:]*)(:*)(.*)/, function (_, before, colon, after) {
  8626. return before + replaceBy_1 + colon + after;
  8627. });
  8628. })
  8629. .replace(_polyfillHostRe, replaceBy_1 + ' ');
  8630. }
  8631. return scopeSelector + ' ' + selector;
  8632. };
  8633. // return a selector with [name] suffix on each simple selector
  8634. // e.g. .foo.bar > .zot becomes .foo[name].bar[name] > .zot[name] /** @internal */
  8635. ShadowCss.prototype._applyStrictSelectorScope = function (selector, scopeSelector, hostSelector) {
  8636. var _this = this;
  8637. var isRe = /\[is=([^\]]*)\]/g;
  8638. scopeSelector = scopeSelector.replace(isRe, function (_) {
  8639. var parts = [];
  8640. for (var _i = 1; _i < arguments.length; _i++) {
  8641. parts[_i - 1] = arguments[_i];
  8642. }
  8643. return parts[0];
  8644. });
  8645. var attrName = '[' + scopeSelector + ']';
  8646. var _scopeSelectorPart = function (p) {
  8647. var scopedP = p.trim();
  8648. if (!scopedP) {
  8649. return '';
  8650. }
  8651. if (p.indexOf(_polyfillHostNoCombinator) > -1) {
  8652. scopedP = _this._applySimpleSelectorScope(p, scopeSelector, hostSelector);
  8653. }
  8654. else {
  8655. // remove :host since it should be unnecessary
  8656. var t = p.replace(_polyfillHostRe, '');
  8657. if (t.length > 0) {
  8658. var matches = t.match(/([^:]*)(:*)(.*)/);
  8659. if (matches) {
  8660. scopedP = matches[1] + attrName + matches[2] + matches[3];
  8661. }
  8662. }
  8663. }
  8664. return scopedP;
  8665. };
  8666. var safeContent = new SafeSelector(selector);
  8667. selector = safeContent.content();
  8668. var scopedSelector = '';
  8669. var startIndex = 0;
  8670. var res;
  8671. var sep = /( |>|\+|~(?!=))\s*/g;
  8672. // If a selector appears before :host it should not be shimmed as it
  8673. // matches on ancestor elements and not on elements in the host's shadow
  8674. // `:host-context(div)` is transformed to
  8675. // `-shadowcsshost-no-combinatordiv, div -shadowcsshost-no-combinator`
  8676. // the `div` is not part of the component in the 2nd selectors and should not be scoped.
  8677. // Historically `component-tag:host` was matching the component so we also want to preserve
  8678. // this behavior to avoid breaking legacy apps (it should not match).
  8679. // The behavior should be:
  8680. // - `tag:host` -> `tag[h]` (this is to avoid breaking legacy apps, should not match anything)
  8681. // - `tag :host` -> `tag [h]` (`tag` is not scoped because it's considered part of a
  8682. // `:host-context(tag)`)
  8683. var hasHost = selector.indexOf(_polyfillHostNoCombinator) > -1;
  8684. // Only scope parts after the first `-shadowcsshost-no-combinator` when it is present
  8685. var shouldScope = !hasHost;
  8686. while ((res = sep.exec(selector)) !== null) {
  8687. var separator = res[1];
  8688. var part_1 = selector.slice(startIndex, res.index).trim();
  8689. shouldScope = shouldScope || part_1.indexOf(_polyfillHostNoCombinator) > -1;
  8690. var scopedPart = shouldScope ? _scopeSelectorPart(part_1) : part_1;
  8691. scopedSelector += scopedPart + " " + separator + " ";
  8692. startIndex = sep.lastIndex;
  8693. }
  8694. var part = selector.substring(startIndex);
  8695. shouldScope = shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1;
  8696. scopedSelector += shouldScope ? _scopeSelectorPart(part) : part;
  8697. // replace the placeholders with their original values
  8698. return safeContent.restore(scopedSelector);
  8699. };
  8700. ShadowCss.prototype._insertPolyfillHostInCssText = function (selector) {
  8701. return selector.replace(_colonHostContextRe, _polyfillHostContext)
  8702. .replace(_colonHostRe, _polyfillHost);
  8703. };
  8704. return ShadowCss;
  8705. }());
  8706. var SafeSelector = /** @class */ (function () {
  8707. function SafeSelector(selector) {
  8708. var _this = this;
  8709. this.placeholders = [];
  8710. this.index = 0;
  8711. // Replaces attribute selectors with placeholders.
  8712. // The WS in [attr="va lue"] would otherwise be interpreted as a selector separator.
  8713. selector = selector.replace(/(\[[^\]]*\])/g, function (_, keep) {
  8714. var replaceBy = "__ph-" + _this.index + "__";
  8715. _this.placeholders.push(keep);
  8716. _this.index++;
  8717. return replaceBy;
  8718. });
  8719. // Replaces the expression in `:nth-child(2n + 1)` with a placeholder.
  8720. // WS and "+" would otherwise be interpreted as selector separators.
  8721. this._content = selector.replace(/(:nth-[-\w]+)(\([^)]+\))/g, function (_, pseudo, exp) {
  8722. var replaceBy = "__ph-" + _this.index + "__";
  8723. _this.placeholders.push(exp);
  8724. _this.index++;
  8725. return pseudo + replaceBy;
  8726. });
  8727. }
  8728. SafeSelector.prototype.restore = function (content) {
  8729. var _this = this;
  8730. return content.replace(/__ph-(\d+)__/g, function (ph, index) { return _this.placeholders[+index]; });
  8731. };
  8732. SafeSelector.prototype.content = function () { return this._content; };
  8733. return SafeSelector;
  8734. }());
  8735. var _cssContentNextSelectorRe = /polyfill-next-selector[^}]*content:[\s]*?(['"])(.*?)\1[;\s]*}([^{]*?){/gim;
  8736. var _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
  8737. var _cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
  8738. var _polyfillHost = '-shadowcsshost';
  8739. // note: :host-context pre-processed to -shadowcsshostcontext.
  8740. var _polyfillHostContext = '-shadowcsscontext';
  8741. var _parenSuffix = ')(?:\\((' +
  8742. '(?:\\([^)(]*\\)|[^)(]*)+?' +
  8743. ')\\))?([^,{]*)';
  8744. var _cssColonHostRe = new RegExp('(' + _polyfillHost + _parenSuffix, 'gim');
  8745. var _cssColonHostContextRe = new RegExp('(' + _polyfillHostContext + _parenSuffix, 'gim');
  8746. var _polyfillHostNoCombinator = _polyfillHost + '-no-combinator';
  8747. var _polyfillHostNoCombinatorRe = /-shadowcsshost-no-combinator([^\s]*)/;
  8748. var _shadowDOMSelectorsRe = [
  8749. /::shadow/g,
  8750. /::content/g,
  8751. // Deprecated selectors
  8752. /\/shadow-deep\//g,
  8753. /\/shadow\//g,
  8754. ];
  8755. // The deep combinator is deprecated in the CSS spec
  8756. // Support for `>>>`, `deep`, `::ng-deep` is then also deprecated and will be removed in the future.
  8757. // see https://github.com/angular/angular/pull/17677
  8758. var _shadowDeepSelectors = /(?:>>>)|(?:\/deep\/)|(?:::ng-deep)/g;
  8759. var _selectorReSuffix = '([>\\s~+\[.,{:][\\s\\S]*)?$';
  8760. var _polyfillHostRe = /-shadowcsshost/gim;
  8761. var _colonHostRe = /:host/gim;
  8762. var _colonHostContextRe = /:host-context/gim;
  8763. var _commentRe = /\/\*\s*[\s\S]*?\*\//g;
  8764. function stripComments(input) {
  8765. return input.replace(_commentRe, '');
  8766. }
  8767. var _commentWithHashRe = /\/\*\s*#\s*source(Mapping)?URL=[\s\S]+?\*\//g;
  8768. function extractCommentsWithHash(input) {
  8769. return input.match(_commentWithHashRe) || [];
  8770. }
  8771. var _ruleRe = /(\s*)([^;\{\}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g;
  8772. var _curlyRe = /([{}])/g;
  8773. var OPEN_CURLY = '{';
  8774. var CLOSE_CURLY = '}';
  8775. var BLOCK_PLACEHOLDER = '%BLOCK%';
  8776. var CssRule = /** @class */ (function () {
  8777. function CssRule(selector, content) {
  8778. this.selector = selector;
  8779. this.content = content;
  8780. }
  8781. return CssRule;
  8782. }());
  8783. function processRules(input, ruleCallback) {
  8784. var inputWithEscapedBlocks = escapeBlocks(input);
  8785. var nextBlockIndex = 0;
  8786. return inputWithEscapedBlocks.escapedString.replace(_ruleRe, function () {
  8787. var m = [];
  8788. for (var _i = 0; _i < arguments.length; _i++) {
  8789. m[_i] = arguments[_i];
  8790. }
  8791. var selector = m[2];
  8792. var content = '';
  8793. var suffix = m[4];
  8794. var contentPrefix = '';
  8795. if (suffix && suffix.startsWith('{' + BLOCK_PLACEHOLDER)) {
  8796. content = inputWithEscapedBlocks.blocks[nextBlockIndex++];
  8797. suffix = suffix.substring(BLOCK_PLACEHOLDER.length + 1);
  8798. contentPrefix = '{';
  8799. }
  8800. var rule = ruleCallback(new CssRule(selector, content));
  8801. return "" + m[1] + rule.selector + m[3] + contentPrefix + rule.content + suffix;
  8802. });
  8803. }
  8804. var StringWithEscapedBlocks = /** @class */ (function () {
  8805. function StringWithEscapedBlocks(escapedString, blocks) {
  8806. this.escapedString = escapedString;
  8807. this.blocks = blocks;
  8808. }
  8809. return StringWithEscapedBlocks;
  8810. }());
  8811. function escapeBlocks(input) {
  8812. var inputParts = input.split(_curlyRe);
  8813. var resultParts = [];
  8814. var escapedBlocks = [];
  8815. var bracketCount = 0;
  8816. var currentBlockParts = [];
  8817. for (var partIndex = 0; partIndex < inputParts.length; partIndex++) {
  8818. var part = inputParts[partIndex];
  8819. if (part == CLOSE_CURLY) {
  8820. bracketCount--;
  8821. }
  8822. if (bracketCount > 0) {
  8823. currentBlockParts.push(part);
  8824. }
  8825. else {
  8826. if (currentBlockParts.length > 0) {
  8827. escapedBlocks.push(currentBlockParts.join(''));
  8828. resultParts.push(BLOCK_PLACEHOLDER);
  8829. currentBlockParts = [];
  8830. }
  8831. resultParts.push(part);
  8832. }
  8833. if (part == OPEN_CURLY) {
  8834. bracketCount++;
  8835. }
  8836. }
  8837. if (currentBlockParts.length > 0) {
  8838. escapedBlocks.push(currentBlockParts.join(''));
  8839. resultParts.push(BLOCK_PLACEHOLDER);
  8840. }
  8841. return new StringWithEscapedBlocks(resultParts.join(''), escapedBlocks);
  8842. }
  8843. /**
  8844. * @license
  8845. * Copyright Google Inc. All Rights Reserved.
  8846. *
  8847. * Use of this source code is governed by an MIT-style license that can be
  8848. * found in the LICENSE file at https://angular.io/license
  8849. */
  8850. var COMPONENT_VARIABLE = '%COMP%';
  8851. var HOST_ATTR = "_nghost-" + COMPONENT_VARIABLE;
  8852. var CONTENT_ATTR = "_ngcontent-" + COMPONENT_VARIABLE;
  8853. var StylesCompileDependency = /** @class */ (function () {
  8854. function StylesCompileDependency(name, moduleUrl, setValue) {
  8855. this.name = name;
  8856. this.moduleUrl = moduleUrl;
  8857. this.setValue = setValue;
  8858. }
  8859. return StylesCompileDependency;
  8860. }());
  8861. var CompiledStylesheet = /** @class */ (function () {
  8862. function CompiledStylesheet(outputCtx, stylesVar, dependencies, isShimmed, meta) {
  8863. this.outputCtx = outputCtx;
  8864. this.stylesVar = stylesVar;
  8865. this.dependencies = dependencies;
  8866. this.isShimmed = isShimmed;
  8867. this.meta = meta;
  8868. }
  8869. return CompiledStylesheet;
  8870. }());
  8871. var StyleCompiler = /** @class */ (function () {
  8872. function StyleCompiler(_urlResolver) {
  8873. this._urlResolver = _urlResolver;
  8874. this._shadowCss = new ShadowCss();
  8875. }
  8876. StyleCompiler.prototype.compileComponent = function (outputCtx, comp) {
  8877. var template = comp.template;
  8878. return this._compileStyles(outputCtx, comp, new CompileStylesheetMetadata({
  8879. styles: template.styles,
  8880. styleUrls: template.styleUrls,
  8881. moduleUrl: identifierModuleUrl(comp.type)
  8882. }), this.needsStyleShim(comp), true);
  8883. };
  8884. StyleCompiler.prototype.compileStyles = function (outputCtx, comp, stylesheet, shim) {
  8885. if (shim === void 0) { shim = this.needsStyleShim(comp); }
  8886. return this._compileStyles(outputCtx, comp, stylesheet, shim, false);
  8887. };
  8888. StyleCompiler.prototype.needsStyleShim = function (comp) {
  8889. return comp.template.encapsulation === ViewEncapsulation.Emulated;
  8890. };
  8891. StyleCompiler.prototype._compileStyles = function (outputCtx, comp, stylesheet, shim, isComponentStylesheet) {
  8892. var _this = this;
  8893. var styleExpressions = stylesheet.styles.map(function (plainStyle) { return literal(_this._shimIfNeeded(plainStyle, shim)); });
  8894. var dependencies = [];
  8895. stylesheet.styleUrls.forEach(function (styleUrl) {
  8896. var exprIndex = styleExpressions.length;
  8897. // Note: This placeholder will be filled later.
  8898. styleExpressions.push(null);
  8899. dependencies.push(new StylesCompileDependency(getStylesVarName(null), styleUrl, function (value) { return styleExpressions[exprIndex] = outputCtx.importExpr(value); }));
  8900. });
  8901. // styles variable contains plain strings and arrays of other styles arrays (recursive),
  8902. // so we set its type to dynamic.
  8903. var stylesVar = getStylesVarName(isComponentStylesheet ? comp : null);
  8904. var stmt = variable(stylesVar)
  8905. .set(literalArr(styleExpressions, new ArrayType(DYNAMIC_TYPE, [TypeModifier.Const])))
  8906. .toDeclStmt(null, isComponentStylesheet ? [exports.StmtModifier.Final] : [
  8907. exports.StmtModifier.Final, exports.StmtModifier.Exported
  8908. ]);
  8909. outputCtx.statements.push(stmt);
  8910. return new CompiledStylesheet(outputCtx, stylesVar, dependencies, shim, stylesheet);
  8911. };
  8912. StyleCompiler.prototype._shimIfNeeded = function (style, shim) {
  8913. return shim ? this._shadowCss.shimCssText(style, CONTENT_ATTR, HOST_ATTR) : style;
  8914. };
  8915. return StyleCompiler;
  8916. }());
  8917. function getStylesVarName(component) {
  8918. var result = "styles";
  8919. if (component) {
  8920. result += "_" + identifierName(component.type);
  8921. }
  8922. return result;
  8923. }
  8924. /**
  8925. * @license
  8926. * Copyright Google Inc. All Rights Reserved.
  8927. *
  8928. * Use of this source code is governed by an MIT-style license that can be
  8929. * found in the LICENSE file at https://angular.io/license
  8930. */
  8931. /**
  8932. * A path is an ordered set of elements. Typically a path is to a
  8933. * particular offset in a source file. The head of the list is the top
  8934. * most node. The tail is the node that contains the offset directly.
  8935. *
  8936. * For example, the expression `a + b + c` might have an ast that looks
  8937. * like:
  8938. * +
  8939. * / \
  8940. * a +
  8941. * / \
  8942. * b c
  8943. *
  8944. * The path to the node at offset 9 would be `['+' at 1-10, '+' at 7-10,
  8945. * 'c' at 9-10]` and the path the node at offset 1 would be
  8946. * `['+' at 1-10, 'a' at 1-2]`.
  8947. */
  8948. var AstPath = /** @class */ (function () {
  8949. function AstPath(path, position) {
  8950. if (position === void 0) { position = -1; }
  8951. this.path = path;
  8952. this.position = position;
  8953. }
  8954. Object.defineProperty(AstPath.prototype, "empty", {
  8955. get: function () { return !this.path || !this.path.length; },
  8956. enumerable: true,
  8957. configurable: true
  8958. });
  8959. Object.defineProperty(AstPath.prototype, "head", {
  8960. get: function () { return this.path[0]; },
  8961. enumerable: true,
  8962. configurable: true
  8963. });
  8964. Object.defineProperty(AstPath.prototype, "tail", {
  8965. get: function () { return this.path[this.path.length - 1]; },
  8966. enumerable: true,
  8967. configurable: true
  8968. });
  8969. AstPath.prototype.parentOf = function (node) {
  8970. return node && this.path[this.path.indexOf(node) - 1];
  8971. };
  8972. AstPath.prototype.childOf = function (node) { return this.path[this.path.indexOf(node) + 1]; };
  8973. AstPath.prototype.first = function (ctor) {
  8974. for (var i = this.path.length - 1; i >= 0; i--) {
  8975. var item = this.path[i];
  8976. if (item instanceof ctor)
  8977. return item;
  8978. }
  8979. };
  8980. AstPath.prototype.push = function (node) { this.path.push(node); };
  8981. AstPath.prototype.pop = function () { return this.path.pop(); };
  8982. return AstPath;
  8983. }());
  8984. /**
  8985. * @license
  8986. * Copyright Google Inc. All Rights Reserved.
  8987. *
  8988. * Use of this source code is governed by an MIT-style license that can be
  8989. * found in the LICENSE file at https://angular.io/license
  8990. */
  8991. var Text$3 = /** @class */ (function () {
  8992. function Text(value, sourceSpan, i18n) {
  8993. this.value = value;
  8994. this.sourceSpan = sourceSpan;
  8995. this.i18n = i18n;
  8996. }
  8997. Text.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
  8998. return Text;
  8999. }());
  9000. var Expansion = /** @class */ (function () {
  9001. function Expansion(switchValue, type, cases, sourceSpan, switchValueSourceSpan, i18n) {
  9002. this.switchValue = switchValue;
  9003. this.type = type;
  9004. this.cases = cases;
  9005. this.sourceSpan = sourceSpan;
  9006. this.switchValueSourceSpan = switchValueSourceSpan;
  9007. this.i18n = i18n;
  9008. }
  9009. Expansion.prototype.visit = function (visitor, context) { return visitor.visitExpansion(this, context); };
  9010. return Expansion;
  9011. }());
  9012. var ExpansionCase = /** @class */ (function () {
  9013. function ExpansionCase(value, expression, sourceSpan, valueSourceSpan, expSourceSpan) {
  9014. this.value = value;
  9015. this.expression = expression;
  9016. this.sourceSpan = sourceSpan;
  9017. this.valueSourceSpan = valueSourceSpan;
  9018. this.expSourceSpan = expSourceSpan;
  9019. }
  9020. ExpansionCase.prototype.visit = function (visitor, context) { return visitor.visitExpansionCase(this, context); };
  9021. return ExpansionCase;
  9022. }());
  9023. var Attribute = /** @class */ (function () {
  9024. function Attribute(name, value, sourceSpan, valueSpan, i18n) {
  9025. this.name = name;
  9026. this.value = value;
  9027. this.sourceSpan = sourceSpan;
  9028. this.valueSpan = valueSpan;
  9029. this.i18n = i18n;
  9030. }
  9031. Attribute.prototype.visit = function (visitor, context) { return visitor.visitAttribute(this, context); };
  9032. return Attribute;
  9033. }());
  9034. var Element$1 = /** @class */ (function () {
  9035. function Element(name, attrs, children, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
  9036. if (startSourceSpan === void 0) { startSourceSpan = null; }
  9037. if (endSourceSpan === void 0) { endSourceSpan = null; }
  9038. this.name = name;
  9039. this.attrs = attrs;
  9040. this.children = children;
  9041. this.sourceSpan = sourceSpan;
  9042. this.startSourceSpan = startSourceSpan;
  9043. this.endSourceSpan = endSourceSpan;
  9044. this.i18n = i18n;
  9045. }
  9046. Element.prototype.visit = function (visitor, context) { return visitor.visitElement(this, context); };
  9047. return Element;
  9048. }());
  9049. var Comment = /** @class */ (function () {
  9050. function Comment(value, sourceSpan) {
  9051. this.value = value;
  9052. this.sourceSpan = sourceSpan;
  9053. }
  9054. Comment.prototype.visit = function (visitor, context) { return visitor.visitComment(this, context); };
  9055. return Comment;
  9056. }());
  9057. function visitAll$1(visitor, nodes, context) {
  9058. if (context === void 0) { context = null; }
  9059. var result = [];
  9060. var visit = visitor.visit ?
  9061. function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } :
  9062. function (ast) { return ast.visit(visitor, context); };
  9063. nodes.forEach(function (ast) {
  9064. var astResult = visit(ast);
  9065. if (astResult) {
  9066. result.push(astResult);
  9067. }
  9068. });
  9069. return result;
  9070. }
  9071. var RecursiveVisitor = /** @class */ (function () {
  9072. function RecursiveVisitor() {
  9073. }
  9074. RecursiveVisitor.prototype.visitElement = function (ast, context) {
  9075. this.visitChildren(context, function (visit) {
  9076. visit(ast.attrs);
  9077. visit(ast.children);
  9078. });
  9079. };
  9080. RecursiveVisitor.prototype.visitAttribute = function (ast, context) { };
  9081. RecursiveVisitor.prototype.visitText = function (ast, context) { };
  9082. RecursiveVisitor.prototype.visitComment = function (ast, context) { };
  9083. RecursiveVisitor.prototype.visitExpansion = function (ast, context) {
  9084. return this.visitChildren(context, function (visit) { visit(ast.cases); });
  9085. };
  9086. RecursiveVisitor.prototype.visitExpansionCase = function (ast, context) { };
  9087. RecursiveVisitor.prototype.visitChildren = function (context, cb) {
  9088. var results = [];
  9089. var t = this;
  9090. function visit(children) {
  9091. if (children)
  9092. results.push(visitAll$1(t, children, context));
  9093. }
  9094. cb(visit);
  9095. return [].concat.apply([], results);
  9096. };
  9097. return RecursiveVisitor;
  9098. }());
  9099. function spanOf(ast) {
  9100. var start = ast.sourceSpan.start.offset;
  9101. var end = ast.sourceSpan.end.offset;
  9102. if (ast instanceof Element$1) {
  9103. if (ast.endSourceSpan) {
  9104. end = ast.endSourceSpan.end.offset;
  9105. }
  9106. else if (ast.children && ast.children.length) {
  9107. end = spanOf(ast.children[ast.children.length - 1]).end;
  9108. }
  9109. }
  9110. return { start: start, end: end };
  9111. }
  9112. function findNode(nodes, position) {
  9113. var path = [];
  9114. var visitor = new /** @class */ (function (_super) {
  9115. __extends(class_1, _super);
  9116. function class_1() {
  9117. return _super !== null && _super.apply(this, arguments) || this;
  9118. }
  9119. class_1.prototype.visit = function (ast, context) {
  9120. var span = spanOf(ast);
  9121. if (span.start <= position && position < span.end) {
  9122. path.push(ast);
  9123. }
  9124. else {
  9125. // Returning a value here will result in the children being skipped.
  9126. return true;
  9127. }
  9128. };
  9129. return class_1;
  9130. }(RecursiveVisitor));
  9131. visitAll$1(visitor, nodes);
  9132. return new AstPath(path, position);
  9133. }
  9134. /**
  9135. * @license
  9136. * Copyright Google Inc. All Rights Reserved.
  9137. *
  9138. * Use of this source code is governed by an MIT-style license that can be
  9139. * found in the LICENSE file at https://angular.io/license
  9140. */
  9141. var TokenType;
  9142. (function (TokenType) {
  9143. TokenType[TokenType["TAG_OPEN_START"] = 0] = "TAG_OPEN_START";
  9144. TokenType[TokenType["TAG_OPEN_END"] = 1] = "TAG_OPEN_END";
  9145. TokenType[TokenType["TAG_OPEN_END_VOID"] = 2] = "TAG_OPEN_END_VOID";
  9146. TokenType[TokenType["TAG_CLOSE"] = 3] = "TAG_CLOSE";
  9147. TokenType[TokenType["TEXT"] = 4] = "TEXT";
  9148. TokenType[TokenType["ESCAPABLE_RAW_TEXT"] = 5] = "ESCAPABLE_RAW_TEXT";
  9149. TokenType[TokenType["RAW_TEXT"] = 6] = "RAW_TEXT";
  9150. TokenType[TokenType["COMMENT_START"] = 7] = "COMMENT_START";
  9151. TokenType[TokenType["COMMENT_END"] = 8] = "COMMENT_END";
  9152. TokenType[TokenType["CDATA_START"] = 9] = "CDATA_START";
  9153. TokenType[TokenType["CDATA_END"] = 10] = "CDATA_END";
  9154. TokenType[TokenType["ATTR_NAME"] = 11] = "ATTR_NAME";
  9155. TokenType[TokenType["ATTR_QUOTE"] = 12] = "ATTR_QUOTE";
  9156. TokenType[TokenType["ATTR_VALUE"] = 13] = "ATTR_VALUE";
  9157. TokenType[TokenType["DOC_TYPE"] = 14] = "DOC_TYPE";
  9158. TokenType[TokenType["EXPANSION_FORM_START"] = 15] = "EXPANSION_FORM_START";
  9159. TokenType[TokenType["EXPANSION_CASE_VALUE"] = 16] = "EXPANSION_CASE_VALUE";
  9160. TokenType[TokenType["EXPANSION_CASE_EXP_START"] = 17] = "EXPANSION_CASE_EXP_START";
  9161. TokenType[TokenType["EXPANSION_CASE_EXP_END"] = 18] = "EXPANSION_CASE_EXP_END";
  9162. TokenType[TokenType["EXPANSION_FORM_END"] = 19] = "EXPANSION_FORM_END";
  9163. TokenType[TokenType["EOF"] = 20] = "EOF";
  9164. })(TokenType || (TokenType = {}));
  9165. var Token = /** @class */ (function () {
  9166. function Token(type, parts, sourceSpan) {
  9167. this.type = type;
  9168. this.parts = parts;
  9169. this.sourceSpan = sourceSpan;
  9170. }
  9171. return Token;
  9172. }());
  9173. var TokenError = /** @class */ (function (_super) {
  9174. __extends(TokenError, _super);
  9175. function TokenError(errorMsg, tokenType, span) {
  9176. var _this = _super.call(this, span, errorMsg) || this;
  9177. _this.tokenType = tokenType;
  9178. return _this;
  9179. }
  9180. return TokenError;
  9181. }(ParseError));
  9182. var TokenizeResult = /** @class */ (function () {
  9183. function TokenizeResult(tokens, errors) {
  9184. this.tokens = tokens;
  9185. this.errors = errors;
  9186. }
  9187. return TokenizeResult;
  9188. }());
  9189. function tokenize(source, url, getTagDefinition, options) {
  9190. if (options === void 0) { options = {}; }
  9191. return new _Tokenizer(new ParseSourceFile(source, url), getTagDefinition, options).tokenize();
  9192. }
  9193. var _CR_OR_CRLF_REGEXP = /\r\n?/g;
  9194. function _unexpectedCharacterErrorMsg(charCode) {
  9195. var char = charCode === $EOF ? 'EOF' : String.fromCharCode(charCode);
  9196. return "Unexpected character \"" + char + "\"";
  9197. }
  9198. function _unknownEntityErrorMsg(entitySrc) {
  9199. return "Unknown entity \"" + entitySrc + "\" - use the \"&#<decimal>;\" or \"&#x<hex>;\" syntax";
  9200. }
  9201. var _ControlFlowError = /** @class */ (function () {
  9202. function _ControlFlowError(error) {
  9203. this.error = error;
  9204. }
  9205. return _ControlFlowError;
  9206. }());
  9207. // See http://www.w3.org/TR/html51/syntax.html#writing
  9208. var _Tokenizer = /** @class */ (function () {
  9209. /**
  9210. * @param _file The html source file being tokenized.
  9211. * @param _getTagDefinition A function that will retrieve a tag definition for a given tag name.
  9212. * @param options Configuration of the tokenization.
  9213. */
  9214. function _Tokenizer(_file, _getTagDefinition, options) {
  9215. this._getTagDefinition = _getTagDefinition;
  9216. this._currentTokenStart = null;
  9217. this._currentTokenType = null;
  9218. this._expansionCaseStack = [];
  9219. this._inInterpolation = false;
  9220. this.tokens = [];
  9221. this.errors = [];
  9222. this._tokenizeIcu = options.tokenizeExpansionForms || false;
  9223. this._interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
  9224. this._leadingTriviaCodePoints =
  9225. options.leadingTriviaChars && options.leadingTriviaChars.map(function (c) { return c.codePointAt(0) || 0; });
  9226. var range = options.range || { endPos: _file.content.length, startPos: 0, startLine: 0, startCol: 0 };
  9227. this._cursor = options.escapedString ? new EscapedCharacterCursor(_file, range) :
  9228. new PlainCharacterCursor(_file, range);
  9229. try {
  9230. this._cursor.init();
  9231. }
  9232. catch (e) {
  9233. this.handleError(e);
  9234. }
  9235. }
  9236. _Tokenizer.prototype._processCarriageReturns = function (content) {
  9237. // http://www.w3.org/TR/html5/syntax.html#preprocessing-the-input-stream
  9238. // In order to keep the original position in the source, we can not
  9239. // pre-process it.
  9240. // Instead CRs are processed right before instantiating the tokens.
  9241. return content.replace(_CR_OR_CRLF_REGEXP, '\n');
  9242. };
  9243. _Tokenizer.prototype.tokenize = function () {
  9244. while (this._cursor.peek() !== $EOF) {
  9245. var start = this._cursor.clone();
  9246. try {
  9247. if (this._attemptCharCode($LT)) {
  9248. if (this._attemptCharCode($BANG)) {
  9249. if (this._attemptCharCode($LBRACKET)) {
  9250. this._consumeCdata(start);
  9251. }
  9252. else if (this._attemptCharCode($MINUS)) {
  9253. this._consumeComment(start);
  9254. }
  9255. else {
  9256. this._consumeDocType(start);
  9257. }
  9258. }
  9259. else if (this._attemptCharCode($SLASH)) {
  9260. this._consumeTagClose(start);
  9261. }
  9262. else {
  9263. this._consumeTagOpen(start);
  9264. }
  9265. }
  9266. else if (!(this._tokenizeIcu && this._tokenizeExpansionForm())) {
  9267. this._consumeText();
  9268. }
  9269. }
  9270. catch (e) {
  9271. this.handleError(e);
  9272. }
  9273. }
  9274. this._beginToken(TokenType.EOF);
  9275. this._endToken([]);
  9276. return new TokenizeResult(mergeTextTokens(this.tokens), this.errors);
  9277. };
  9278. /**
  9279. * @returns whether an ICU token has been created
  9280. * @internal
  9281. */
  9282. _Tokenizer.prototype._tokenizeExpansionForm = function () {
  9283. if (this.isExpansionFormStart()) {
  9284. this._consumeExpansionFormStart();
  9285. return true;
  9286. }
  9287. if (isExpansionCaseStart(this._cursor.peek()) && this._isInExpansionForm()) {
  9288. this._consumeExpansionCaseStart();
  9289. return true;
  9290. }
  9291. if (this._cursor.peek() === $RBRACE) {
  9292. if (this._isInExpansionCase()) {
  9293. this._consumeExpansionCaseEnd();
  9294. return true;
  9295. }
  9296. if (this._isInExpansionForm()) {
  9297. this._consumeExpansionFormEnd();
  9298. return true;
  9299. }
  9300. }
  9301. return false;
  9302. };
  9303. _Tokenizer.prototype._beginToken = function (type, start) {
  9304. if (start === void 0) { start = this._cursor.clone(); }
  9305. this._currentTokenStart = start;
  9306. this._currentTokenType = type;
  9307. };
  9308. _Tokenizer.prototype._endToken = function (parts, end) {
  9309. if (end === void 0) { end = this._cursor.clone(); }
  9310. if (this._currentTokenStart === null) {
  9311. throw new TokenError('Programming error - attempted to end a token when there was no start to the token', this._currentTokenType, this._cursor.getSpan(end));
  9312. }
  9313. if (this._currentTokenType === null) {
  9314. throw new TokenError('Programming error - attempted to end a token which has no token type', null, this._cursor.getSpan(this._currentTokenStart));
  9315. }
  9316. var token = new Token(this._currentTokenType, parts, this._cursor.getSpan(this._currentTokenStart, this._leadingTriviaCodePoints));
  9317. this.tokens.push(token);
  9318. this._currentTokenStart = null;
  9319. this._currentTokenType = null;
  9320. return token;
  9321. };
  9322. _Tokenizer.prototype._createError = function (msg, span) {
  9323. if (this._isInExpansionForm()) {
  9324. msg += " (Do you have an unescaped \"{\" in your template? Use \"{{ '{' }}\") to escape it.)";
  9325. }
  9326. var error = new TokenError(msg, this._currentTokenType, span);
  9327. this._currentTokenStart = null;
  9328. this._currentTokenType = null;
  9329. return new _ControlFlowError(error);
  9330. };
  9331. _Tokenizer.prototype.handleError = function (e) {
  9332. if (e instanceof CursorError) {
  9333. e = this._createError(e.msg, this._cursor.getSpan(e.cursor));
  9334. }
  9335. if (e instanceof _ControlFlowError) {
  9336. this.errors.push(e.error);
  9337. }
  9338. else {
  9339. throw e;
  9340. }
  9341. };
  9342. _Tokenizer.prototype._attemptCharCode = function (charCode) {
  9343. if (this._cursor.peek() === charCode) {
  9344. this._cursor.advance();
  9345. return true;
  9346. }
  9347. return false;
  9348. };
  9349. _Tokenizer.prototype._attemptCharCodeCaseInsensitive = function (charCode) {
  9350. if (compareCharCodeCaseInsensitive(this._cursor.peek(), charCode)) {
  9351. this._cursor.advance();
  9352. return true;
  9353. }
  9354. return false;
  9355. };
  9356. _Tokenizer.prototype._requireCharCode = function (charCode) {
  9357. var location = this._cursor.clone();
  9358. if (!this._attemptCharCode(charCode)) {
  9359. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location));
  9360. }
  9361. };
  9362. _Tokenizer.prototype._attemptStr = function (chars) {
  9363. var len = chars.length;
  9364. if (this._cursor.charsLeft() < len) {
  9365. return false;
  9366. }
  9367. var initialPosition = this._cursor.clone();
  9368. for (var i = 0; i < len; i++) {
  9369. if (!this._attemptCharCode(chars.charCodeAt(i))) {
  9370. // If attempting to parse the string fails, we want to reset the parser
  9371. // to where it was before the attempt
  9372. this._cursor = initialPosition;
  9373. return false;
  9374. }
  9375. }
  9376. return true;
  9377. };
  9378. _Tokenizer.prototype._attemptStrCaseInsensitive = function (chars) {
  9379. for (var i = 0; i < chars.length; i++) {
  9380. if (!this._attemptCharCodeCaseInsensitive(chars.charCodeAt(i))) {
  9381. return false;
  9382. }
  9383. }
  9384. return true;
  9385. };
  9386. _Tokenizer.prototype._requireStr = function (chars) {
  9387. var location = this._cursor.clone();
  9388. if (!this._attemptStr(chars)) {
  9389. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location));
  9390. }
  9391. };
  9392. _Tokenizer.prototype._attemptCharCodeUntilFn = function (predicate) {
  9393. while (!predicate(this._cursor.peek())) {
  9394. this._cursor.advance();
  9395. }
  9396. };
  9397. _Tokenizer.prototype._requireCharCodeUntilFn = function (predicate, len) {
  9398. var start = this._cursor.clone();
  9399. this._attemptCharCodeUntilFn(predicate);
  9400. var end = this._cursor.clone();
  9401. if (end.diff(start) < len) {
  9402. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start));
  9403. }
  9404. };
  9405. _Tokenizer.prototype._attemptUntilChar = function (char) {
  9406. while (this._cursor.peek() !== char) {
  9407. this._cursor.advance();
  9408. }
  9409. };
  9410. _Tokenizer.prototype._readChar = function (decodeEntities) {
  9411. if (decodeEntities && this._cursor.peek() === $AMPERSAND) {
  9412. return this._decodeEntity();
  9413. }
  9414. else {
  9415. // Don't rely upon reading directly from `_input` as the actual char value
  9416. // may have been generated from an escape sequence.
  9417. var char = String.fromCodePoint(this._cursor.peek());
  9418. this._cursor.advance();
  9419. return char;
  9420. }
  9421. };
  9422. _Tokenizer.prototype._decodeEntity = function () {
  9423. var start = this._cursor.clone();
  9424. this._cursor.advance();
  9425. if (this._attemptCharCode($HASH)) {
  9426. var isHex = this._attemptCharCode($x) || this._attemptCharCode($X);
  9427. var codeStart = this._cursor.clone();
  9428. this._attemptCharCodeUntilFn(isDigitEntityEnd);
  9429. if (this._cursor.peek() != $SEMICOLON) {
  9430. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan());
  9431. }
  9432. var strNum = this._cursor.getChars(codeStart);
  9433. this._cursor.advance();
  9434. try {
  9435. var charCode = parseInt(strNum, isHex ? 16 : 10);
  9436. return String.fromCharCode(charCode);
  9437. }
  9438. catch (_a) {
  9439. throw this._createError(_unknownEntityErrorMsg(this._cursor.getChars(start)), this._cursor.getSpan());
  9440. }
  9441. }
  9442. else {
  9443. var nameStart = this._cursor.clone();
  9444. this._attemptCharCodeUntilFn(isNamedEntityEnd);
  9445. if (this._cursor.peek() != $SEMICOLON) {
  9446. this._cursor = nameStart;
  9447. return '&';
  9448. }
  9449. var name_1 = this._cursor.getChars(nameStart);
  9450. this._cursor.advance();
  9451. var char = NAMED_ENTITIES[name_1];
  9452. if (!char) {
  9453. throw this._createError(_unknownEntityErrorMsg(name_1), this._cursor.getSpan(start));
  9454. }
  9455. return char;
  9456. }
  9457. };
  9458. _Tokenizer.prototype._consumeRawText = function (decodeEntities, endMarkerPredicate) {
  9459. this._beginToken(decodeEntities ? TokenType.ESCAPABLE_RAW_TEXT : TokenType.RAW_TEXT);
  9460. var parts = [];
  9461. while (true) {
  9462. var tagCloseStart = this._cursor.clone();
  9463. var foundEndMarker = endMarkerPredicate();
  9464. this._cursor = tagCloseStart;
  9465. if (foundEndMarker) {
  9466. break;
  9467. }
  9468. parts.push(this._readChar(decodeEntities));
  9469. }
  9470. return this._endToken([this._processCarriageReturns(parts.join(''))]);
  9471. };
  9472. _Tokenizer.prototype._consumeComment = function (start) {
  9473. var _this = this;
  9474. this._beginToken(TokenType.COMMENT_START, start);
  9475. this._requireCharCode($MINUS);
  9476. this._endToken([]);
  9477. this._consumeRawText(false, function () { return _this._attemptStr('-->'); });
  9478. this._beginToken(TokenType.COMMENT_END);
  9479. this._requireStr('-->');
  9480. this._endToken([]);
  9481. };
  9482. _Tokenizer.prototype._consumeCdata = function (start) {
  9483. var _this = this;
  9484. this._beginToken(TokenType.CDATA_START, start);
  9485. this._requireStr('CDATA[');
  9486. this._endToken([]);
  9487. this._consumeRawText(false, function () { return _this._attemptStr(']]>'); });
  9488. this._beginToken(TokenType.CDATA_END);
  9489. this._requireStr(']]>');
  9490. this._endToken([]);
  9491. };
  9492. _Tokenizer.prototype._consumeDocType = function (start) {
  9493. this._beginToken(TokenType.DOC_TYPE, start);
  9494. var contentStart = this._cursor.clone();
  9495. this._attemptUntilChar($GT);
  9496. var content = this._cursor.getChars(contentStart);
  9497. this._cursor.advance();
  9498. this._endToken([content]);
  9499. };
  9500. _Tokenizer.prototype._consumePrefixAndName = function () {
  9501. var nameOrPrefixStart = this._cursor.clone();
  9502. var prefix = '';
  9503. while (this._cursor.peek() !== $COLON && !isPrefixEnd(this._cursor.peek())) {
  9504. this._cursor.advance();
  9505. }
  9506. var nameStart;
  9507. if (this._cursor.peek() === $COLON) {
  9508. prefix = this._cursor.getChars(nameOrPrefixStart);
  9509. this._cursor.advance();
  9510. nameStart = this._cursor.clone();
  9511. }
  9512. else {
  9513. nameStart = nameOrPrefixStart;
  9514. }
  9515. this._requireCharCodeUntilFn(isNameEnd, prefix === '' ? 0 : 1);
  9516. var name = this._cursor.getChars(nameStart);
  9517. return [prefix, name];
  9518. };
  9519. _Tokenizer.prototype._consumeTagOpen = function (start) {
  9520. var tagName;
  9521. var prefix;
  9522. var openTagToken;
  9523. var tokensBeforeTagOpen = this.tokens.length;
  9524. var innerStart = this._cursor.clone();
  9525. try {
  9526. if (!isAsciiLetter(this._cursor.peek())) {
  9527. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start));
  9528. }
  9529. openTagToken = this._consumeTagOpenStart(start);
  9530. prefix = openTagToken.parts[0];
  9531. tagName = openTagToken.parts[1];
  9532. this._attemptCharCodeUntilFn(isNotWhitespace);
  9533. while (this._cursor.peek() !== $SLASH && this._cursor.peek() !== $GT) {
  9534. this._consumeAttributeName();
  9535. this._attemptCharCodeUntilFn(isNotWhitespace);
  9536. if (this._attemptCharCode($EQ)) {
  9537. this._attemptCharCodeUntilFn(isNotWhitespace);
  9538. this._consumeAttributeValue();
  9539. }
  9540. this._attemptCharCodeUntilFn(isNotWhitespace);
  9541. }
  9542. this._consumeTagOpenEnd();
  9543. }
  9544. catch (e) {
  9545. if (e instanceof _ControlFlowError) {
  9546. // When the start tag is invalid (including invalid "attributes"), assume we want a "<"
  9547. this._cursor = innerStart;
  9548. if (openTagToken) {
  9549. this.tokens.length = tokensBeforeTagOpen;
  9550. }
  9551. // Back to back text tokens are merged at the end
  9552. this._beginToken(TokenType.TEXT, start);
  9553. this._endToken(['<']);
  9554. return;
  9555. }
  9556. throw e;
  9557. }
  9558. var contentTokenType = this._getTagDefinition(tagName).contentType;
  9559. if (contentTokenType === exports.TagContentType.RAW_TEXT) {
  9560. this._consumeRawTextWithTagClose(prefix, tagName, false);
  9561. }
  9562. else if (contentTokenType === exports.TagContentType.ESCAPABLE_RAW_TEXT) {
  9563. this._consumeRawTextWithTagClose(prefix, tagName, true);
  9564. }
  9565. };
  9566. _Tokenizer.prototype._consumeRawTextWithTagClose = function (prefix, tagName, decodeEntities) {
  9567. var _this = this;
  9568. var textToken = this._consumeRawText(decodeEntities, function () {
  9569. if (!_this._attemptCharCode($LT))
  9570. return false;
  9571. if (!_this._attemptCharCode($SLASH))
  9572. return false;
  9573. _this._attemptCharCodeUntilFn(isNotWhitespace);
  9574. if (!_this._attemptStrCaseInsensitive(tagName))
  9575. return false;
  9576. _this._attemptCharCodeUntilFn(isNotWhitespace);
  9577. return _this._attemptCharCode($GT);
  9578. });
  9579. this._beginToken(TokenType.TAG_CLOSE);
  9580. this._requireCharCodeUntilFn(function (code) { return code === $GT; }, 3);
  9581. this._cursor.advance(); // Consume the `>`
  9582. this._endToken([prefix, tagName]);
  9583. };
  9584. _Tokenizer.prototype._consumeTagOpenStart = function (start) {
  9585. this._beginToken(TokenType.TAG_OPEN_START, start);
  9586. var parts = this._consumePrefixAndName();
  9587. return this._endToken(parts);
  9588. };
  9589. _Tokenizer.prototype._consumeAttributeName = function () {
  9590. var attrNameStart = this._cursor.peek();
  9591. if (attrNameStart === $SQ || attrNameStart === $DQ) {
  9592. throw this._createError(_unexpectedCharacterErrorMsg(attrNameStart), this._cursor.getSpan());
  9593. }
  9594. this._beginToken(TokenType.ATTR_NAME);
  9595. var prefixAndName = this._consumePrefixAndName();
  9596. this._endToken(prefixAndName);
  9597. };
  9598. _Tokenizer.prototype._consumeAttributeValue = function () {
  9599. var value;
  9600. if (this._cursor.peek() === $SQ || this._cursor.peek() === $DQ) {
  9601. this._beginToken(TokenType.ATTR_QUOTE);
  9602. var quoteChar = this._cursor.peek();
  9603. this._cursor.advance();
  9604. this._endToken([String.fromCodePoint(quoteChar)]);
  9605. this._beginToken(TokenType.ATTR_VALUE);
  9606. var parts = [];
  9607. while (this._cursor.peek() !== quoteChar) {
  9608. parts.push(this._readChar(true));
  9609. }
  9610. value = parts.join('');
  9611. this._endToken([this._processCarriageReturns(value)]);
  9612. this._beginToken(TokenType.ATTR_QUOTE);
  9613. this._cursor.advance();
  9614. this._endToken([String.fromCodePoint(quoteChar)]);
  9615. }
  9616. else {
  9617. this._beginToken(TokenType.ATTR_VALUE);
  9618. var valueStart = this._cursor.clone();
  9619. this._requireCharCodeUntilFn(isNameEnd, 1);
  9620. value = this._cursor.getChars(valueStart);
  9621. this._endToken([this._processCarriageReturns(value)]);
  9622. }
  9623. };
  9624. _Tokenizer.prototype._consumeTagOpenEnd = function () {
  9625. var tokenType = this._attemptCharCode($SLASH) ? TokenType.TAG_OPEN_END_VOID : TokenType.TAG_OPEN_END;
  9626. this._beginToken(tokenType);
  9627. this._requireCharCode($GT);
  9628. this._endToken([]);
  9629. };
  9630. _Tokenizer.prototype._consumeTagClose = function (start) {
  9631. this._beginToken(TokenType.TAG_CLOSE, start);
  9632. this._attemptCharCodeUntilFn(isNotWhitespace);
  9633. var prefixAndName = this._consumePrefixAndName();
  9634. this._attemptCharCodeUntilFn(isNotWhitespace);
  9635. this._requireCharCode($GT);
  9636. this._endToken(prefixAndName);
  9637. };
  9638. _Tokenizer.prototype._consumeExpansionFormStart = function () {
  9639. this._beginToken(TokenType.EXPANSION_FORM_START);
  9640. this._requireCharCode($LBRACE);
  9641. this._endToken([]);
  9642. this._expansionCaseStack.push(TokenType.EXPANSION_FORM_START);
  9643. this._beginToken(TokenType.RAW_TEXT);
  9644. var condition = this._readUntil($COMMA);
  9645. this._endToken([condition]);
  9646. this._requireCharCode($COMMA);
  9647. this._attemptCharCodeUntilFn(isNotWhitespace);
  9648. this._beginToken(TokenType.RAW_TEXT);
  9649. var type = this._readUntil($COMMA);
  9650. this._endToken([type]);
  9651. this._requireCharCode($COMMA);
  9652. this._attemptCharCodeUntilFn(isNotWhitespace);
  9653. };
  9654. _Tokenizer.prototype._consumeExpansionCaseStart = function () {
  9655. this._beginToken(TokenType.EXPANSION_CASE_VALUE);
  9656. var value = this._readUntil($LBRACE).trim();
  9657. this._endToken([value]);
  9658. this._attemptCharCodeUntilFn(isNotWhitespace);
  9659. this._beginToken(TokenType.EXPANSION_CASE_EXP_START);
  9660. this._requireCharCode($LBRACE);
  9661. this._endToken([]);
  9662. this._attemptCharCodeUntilFn(isNotWhitespace);
  9663. this._expansionCaseStack.push(TokenType.EXPANSION_CASE_EXP_START);
  9664. };
  9665. _Tokenizer.prototype._consumeExpansionCaseEnd = function () {
  9666. this._beginToken(TokenType.EXPANSION_CASE_EXP_END);
  9667. this._requireCharCode($RBRACE);
  9668. this._endToken([]);
  9669. this._attemptCharCodeUntilFn(isNotWhitespace);
  9670. this._expansionCaseStack.pop();
  9671. };
  9672. _Tokenizer.prototype._consumeExpansionFormEnd = function () {
  9673. this._beginToken(TokenType.EXPANSION_FORM_END);
  9674. this._requireCharCode($RBRACE);
  9675. this._endToken([]);
  9676. this._expansionCaseStack.pop();
  9677. };
  9678. _Tokenizer.prototype._consumeText = function () {
  9679. var start = this._cursor.clone();
  9680. this._beginToken(TokenType.TEXT, start);
  9681. var parts = [];
  9682. do {
  9683. if (this._interpolationConfig && this._attemptStr(this._interpolationConfig.start)) {
  9684. parts.push(this._interpolationConfig.start);
  9685. this._inInterpolation = true;
  9686. }
  9687. else if (this._interpolationConfig && this._inInterpolation &&
  9688. this._attemptStr(this._interpolationConfig.end)) {
  9689. parts.push(this._interpolationConfig.end);
  9690. this._inInterpolation = false;
  9691. }
  9692. else {
  9693. parts.push(this._readChar(true));
  9694. }
  9695. } while (!this._isTextEnd());
  9696. this._endToken([this._processCarriageReturns(parts.join(''))]);
  9697. };
  9698. _Tokenizer.prototype._isTextEnd = function () {
  9699. if (this._cursor.peek() === $LT || this._cursor.peek() === $EOF) {
  9700. return true;
  9701. }
  9702. if (this._tokenizeIcu && !this._inInterpolation) {
  9703. if (this.isExpansionFormStart()) {
  9704. // start of an expansion form
  9705. return true;
  9706. }
  9707. if (this._cursor.peek() === $RBRACE && this._isInExpansionCase()) {
  9708. // end of and expansion case
  9709. return true;
  9710. }
  9711. }
  9712. return false;
  9713. };
  9714. _Tokenizer.prototype._readUntil = function (char) {
  9715. var start = this._cursor.clone();
  9716. this._attemptUntilChar(char);
  9717. return this._cursor.getChars(start);
  9718. };
  9719. _Tokenizer.prototype._isInExpansionCase = function () {
  9720. return this._expansionCaseStack.length > 0 &&
  9721. this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
  9722. TokenType.EXPANSION_CASE_EXP_START;
  9723. };
  9724. _Tokenizer.prototype._isInExpansionForm = function () {
  9725. return this._expansionCaseStack.length > 0 &&
  9726. this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
  9727. TokenType.EXPANSION_FORM_START;
  9728. };
  9729. _Tokenizer.prototype.isExpansionFormStart = function () {
  9730. if (this._cursor.peek() !== $LBRACE) {
  9731. return false;
  9732. }
  9733. if (this._interpolationConfig) {
  9734. var start = this._cursor.clone();
  9735. var isInterpolation = this._attemptStr(this._interpolationConfig.start);
  9736. this._cursor = start;
  9737. return !isInterpolation;
  9738. }
  9739. return true;
  9740. };
  9741. return _Tokenizer;
  9742. }());
  9743. function isNotWhitespace(code) {
  9744. return !isWhitespace(code) || code === $EOF;
  9745. }
  9746. function isNameEnd(code) {
  9747. return isWhitespace(code) || code === $GT || code === $SLASH ||
  9748. code === $SQ || code === $DQ || code === $EQ;
  9749. }
  9750. function isPrefixEnd(code) {
  9751. return (code < $a || $z < code) && (code < $A || $Z < code) &&
  9752. (code < $0 || code > $9);
  9753. }
  9754. function isDigitEntityEnd(code) {
  9755. return code == $SEMICOLON || code == $EOF || !isAsciiHexDigit(code);
  9756. }
  9757. function isNamedEntityEnd(code) {
  9758. return code == $SEMICOLON || code == $EOF || !isAsciiLetter(code);
  9759. }
  9760. function isExpansionCaseStart(peek) {
  9761. return peek === $EQ || isAsciiLetter(peek) || isDigit(peek);
  9762. }
  9763. function compareCharCodeCaseInsensitive(code1, code2) {
  9764. return toUpperCaseCharCode(code1) == toUpperCaseCharCode(code2);
  9765. }
  9766. function toUpperCaseCharCode(code) {
  9767. return code >= $a && code <= $z ? code - $a + $A : code;
  9768. }
  9769. function mergeTextTokens(srcTokens) {
  9770. var dstTokens = [];
  9771. var lastDstToken = undefined;
  9772. for (var i = 0; i < srcTokens.length; i++) {
  9773. var token = srcTokens[i];
  9774. if (lastDstToken && lastDstToken.type == TokenType.TEXT && token.type == TokenType.TEXT) {
  9775. lastDstToken.parts[0] += token.parts[0];
  9776. lastDstToken.sourceSpan.end = token.sourceSpan.end;
  9777. }
  9778. else {
  9779. lastDstToken = token;
  9780. dstTokens.push(lastDstToken);
  9781. }
  9782. }
  9783. return dstTokens;
  9784. }
  9785. var PlainCharacterCursor = /** @class */ (function () {
  9786. function PlainCharacterCursor(fileOrCursor, range) {
  9787. if (fileOrCursor instanceof PlainCharacterCursor) {
  9788. this.file = fileOrCursor.file;
  9789. this.input = fileOrCursor.input;
  9790. this.end = fileOrCursor.end;
  9791. this.state = __assign({}, fileOrCursor.state);
  9792. }
  9793. else {
  9794. if (!range) {
  9795. throw new Error('Programming error: the range argument must be provided with a file argument.');
  9796. }
  9797. this.file = fileOrCursor;
  9798. this.input = fileOrCursor.content;
  9799. this.end = range.endPos;
  9800. this.state = {
  9801. peek: -1,
  9802. offset: range.startPos,
  9803. line: range.startLine,
  9804. column: range.startCol,
  9805. };
  9806. }
  9807. }
  9808. PlainCharacterCursor.prototype.clone = function () { return new PlainCharacterCursor(this); };
  9809. PlainCharacterCursor.prototype.peek = function () { return this.state.peek; };
  9810. PlainCharacterCursor.prototype.charsLeft = function () { return this.end - this.state.offset; };
  9811. PlainCharacterCursor.prototype.diff = function (other) { return this.state.offset - other.state.offset; };
  9812. PlainCharacterCursor.prototype.advance = function () { this.advanceState(this.state); };
  9813. PlainCharacterCursor.prototype.init = function () { this.updatePeek(this.state); };
  9814. PlainCharacterCursor.prototype.getSpan = function (start, leadingTriviaCodePoints) {
  9815. start = start || this;
  9816. if (leadingTriviaCodePoints) {
  9817. start = start.clone();
  9818. while (this.diff(start) > 0 && leadingTriviaCodePoints.indexOf(start.peek()) !== -1) {
  9819. start.advance();
  9820. }
  9821. }
  9822. 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));
  9823. };
  9824. PlainCharacterCursor.prototype.getChars = function (start) {
  9825. return this.input.substring(start.state.offset, this.state.offset);
  9826. };
  9827. PlainCharacterCursor.prototype.charAt = function (pos) { return this.input.charCodeAt(pos); };
  9828. PlainCharacterCursor.prototype.advanceState = function (state) {
  9829. if (state.offset >= this.end) {
  9830. this.state = state;
  9831. throw new CursorError('Unexpected character "EOF"', this);
  9832. }
  9833. var currentChar = this.charAt(state.offset);
  9834. if (currentChar === $LF) {
  9835. state.line++;
  9836. state.column = 0;
  9837. }
  9838. else if (!isNewLine(currentChar)) {
  9839. state.column++;
  9840. }
  9841. state.offset++;
  9842. this.updatePeek(state);
  9843. };
  9844. PlainCharacterCursor.prototype.updatePeek = function (state) {
  9845. state.peek = state.offset >= this.end ? $EOF : this.charAt(state.offset);
  9846. };
  9847. return PlainCharacterCursor;
  9848. }());
  9849. var EscapedCharacterCursor = /** @class */ (function (_super) {
  9850. __extends(EscapedCharacterCursor, _super);
  9851. function EscapedCharacterCursor(fileOrCursor, range) {
  9852. var _this = this;
  9853. if (fileOrCursor instanceof EscapedCharacterCursor) {
  9854. _this = _super.call(this, fileOrCursor) || this;
  9855. _this.internalState = __assign({}, fileOrCursor.internalState);
  9856. }
  9857. else {
  9858. _this = _super.call(this, fileOrCursor, range) || this;
  9859. _this.internalState = _this.state;
  9860. }
  9861. return _this;
  9862. }
  9863. EscapedCharacterCursor.prototype.advance = function () {
  9864. this.state = this.internalState;
  9865. _super.prototype.advance.call(this);
  9866. this.processEscapeSequence();
  9867. };
  9868. EscapedCharacterCursor.prototype.init = function () {
  9869. _super.prototype.init.call(this);
  9870. this.processEscapeSequence();
  9871. };
  9872. EscapedCharacterCursor.prototype.clone = function () { return new EscapedCharacterCursor(this); };
  9873. EscapedCharacterCursor.prototype.getChars = function (start) {
  9874. var cursor = start.clone();
  9875. var chars = '';
  9876. while (cursor.internalState.offset < this.internalState.offset) {
  9877. chars += String.fromCodePoint(cursor.peek());
  9878. cursor.advance();
  9879. }
  9880. return chars;
  9881. };
  9882. /**
  9883. * Process the escape sequence that starts at the current position in the text.
  9884. *
  9885. * This method is called to ensure that `peek` has the unescaped value of escape sequences.
  9886. */
  9887. EscapedCharacterCursor.prototype.processEscapeSequence = function () {
  9888. var _this = this;
  9889. var peek = function () { return _this.internalState.peek; };
  9890. if (peek() === $BACKSLASH) {
  9891. // We have hit an escape sequence so we need the internal state to become independent
  9892. // of the external state.
  9893. this.internalState = __assign({}, this.state);
  9894. // Move past the backslash
  9895. this.advanceState(this.internalState);
  9896. // First check for standard control char sequences
  9897. if (peek() === $n) {
  9898. this.state.peek = $LF;
  9899. }
  9900. else if (peek() === $r) {
  9901. this.state.peek = $CR;
  9902. }
  9903. else if (peek() === $v) {
  9904. this.state.peek = $VTAB;
  9905. }
  9906. else if (peek() === $t) {
  9907. this.state.peek = $TAB;
  9908. }
  9909. else if (peek() === $b) {
  9910. this.state.peek = $BSPACE;
  9911. }
  9912. else if (peek() === $f) {
  9913. this.state.peek = $FF;
  9914. }
  9915. // Now consider more complex sequences
  9916. else if (peek() === $u) {
  9917. // Unicode code-point sequence
  9918. this.advanceState(this.internalState); // advance past the `u` char
  9919. if (peek() === $LBRACE) {
  9920. // Variable length Unicode, e.g. `\x{123}`
  9921. this.advanceState(this.internalState); // advance past the `{` char
  9922. // Advance past the variable number of hex digits until we hit a `}` char
  9923. var digitStart = this.clone();
  9924. var length_1 = 0;
  9925. while (peek() !== $RBRACE) {
  9926. this.advanceState(this.internalState);
  9927. length_1++;
  9928. }
  9929. this.state.peek = this.decodeHexDigits(digitStart, length_1);
  9930. }
  9931. else {
  9932. // Fixed length Unicode, e.g. `\u1234`
  9933. var digitStart = this.clone();
  9934. this.advanceState(this.internalState);
  9935. this.advanceState(this.internalState);
  9936. this.advanceState(this.internalState);
  9937. this.state.peek = this.decodeHexDigits(digitStart, 4);
  9938. }
  9939. }
  9940. else if (peek() === $x) {
  9941. // Hex char code, e.g. `\x2F`
  9942. this.advanceState(this.internalState); // advance past the `x` char
  9943. var digitStart = this.clone();
  9944. this.advanceState(this.internalState);
  9945. this.state.peek = this.decodeHexDigits(digitStart, 2);
  9946. }
  9947. else if (isOctalDigit(peek())) {
  9948. // Octal char code, e.g. `\012`,
  9949. var octal = '';
  9950. var length_2 = 0;
  9951. var previous = this.clone();
  9952. while (isOctalDigit(peek()) && length_2 < 3) {
  9953. previous = this.clone();
  9954. octal += String.fromCodePoint(peek());
  9955. this.advanceState(this.internalState);
  9956. length_2++;
  9957. }
  9958. this.state.peek = parseInt(octal, 8);
  9959. // Backup one char
  9960. this.internalState = previous.internalState;
  9961. }
  9962. else if (isNewLine(this.internalState.peek)) {
  9963. // Line continuation `\` followed by a new line
  9964. this.advanceState(this.internalState); // advance over the newline
  9965. this.state = this.internalState;
  9966. }
  9967. else {
  9968. // If none of the `if` blocks were executed then we just have an escaped normal character.
  9969. // In that case we just, effectively, skip the backslash from the character.
  9970. this.state.peek = this.internalState.peek;
  9971. }
  9972. }
  9973. };
  9974. EscapedCharacterCursor.prototype.decodeHexDigits = function (start, length) {
  9975. var hex = this.input.substr(start.internalState.offset, length);
  9976. var charCode = parseInt(hex, 16);
  9977. if (!isNaN(charCode)) {
  9978. return charCode;
  9979. }
  9980. else {
  9981. start.state = start.internalState;
  9982. throw new CursorError('Invalid hexadecimal escape sequence', start);
  9983. }
  9984. };
  9985. return EscapedCharacterCursor;
  9986. }(PlainCharacterCursor));
  9987. var CursorError = /** @class */ (function () {
  9988. function CursorError(msg, cursor) {
  9989. this.msg = msg;
  9990. this.cursor = cursor;
  9991. }
  9992. return CursorError;
  9993. }());
  9994. /**
  9995. * @license
  9996. * Copyright Google Inc. All Rights Reserved.
  9997. *
  9998. * Use of this source code is governed by an MIT-style license that can be
  9999. * found in the LICENSE file at https://angular.io/license
  10000. */
  10001. var TreeError = /** @class */ (function (_super) {
  10002. __extends(TreeError, _super);
  10003. function TreeError(elementName, span, msg) {
  10004. var _this = _super.call(this, span, msg) || this;
  10005. _this.elementName = elementName;
  10006. return _this;
  10007. }
  10008. TreeError.create = function (elementName, span, msg) {
  10009. return new TreeError(elementName, span, msg);
  10010. };
  10011. return TreeError;
  10012. }(ParseError));
  10013. var ParseTreeResult = /** @class */ (function () {
  10014. function ParseTreeResult(rootNodes, errors) {
  10015. this.rootNodes = rootNodes;
  10016. this.errors = errors;
  10017. }
  10018. return ParseTreeResult;
  10019. }());
  10020. var Parser = /** @class */ (function () {
  10021. function Parser(getTagDefinition) {
  10022. this.getTagDefinition = getTagDefinition;
  10023. }
  10024. Parser.prototype.parse = function (source, url, options) {
  10025. var tokensAndErrors = tokenize(source, url, this.getTagDefinition, options);
  10026. var treeAndErrors = new _TreeBuilder(tokensAndErrors.tokens, this.getTagDefinition).build();
  10027. return new ParseTreeResult(treeAndErrors.rootNodes, tokensAndErrors.errors.concat(treeAndErrors.errors));
  10028. };
  10029. return Parser;
  10030. }());
  10031. var _TreeBuilder = /** @class */ (function () {
  10032. function _TreeBuilder(tokens, getTagDefinition) {
  10033. this.tokens = tokens;
  10034. this.getTagDefinition = getTagDefinition;
  10035. this._index = -1;
  10036. this._rootNodes = [];
  10037. this._errors = [];
  10038. this._elementStack = [];
  10039. this._advance();
  10040. }
  10041. _TreeBuilder.prototype.build = function () {
  10042. while (this._peek.type !== TokenType.EOF) {
  10043. if (this._peek.type === TokenType.TAG_OPEN_START) {
  10044. this._consumeStartTag(this._advance());
  10045. }
  10046. else if (this._peek.type === TokenType.TAG_CLOSE) {
  10047. this._consumeEndTag(this._advance());
  10048. }
  10049. else if (this._peek.type === TokenType.CDATA_START) {
  10050. this._closeVoidElement();
  10051. this._consumeCdata(this._advance());
  10052. }
  10053. else if (this._peek.type === TokenType.COMMENT_START) {
  10054. this._closeVoidElement();
  10055. this._consumeComment(this._advance());
  10056. }
  10057. else if (this._peek.type === TokenType.TEXT || this._peek.type === TokenType.RAW_TEXT ||
  10058. this._peek.type === TokenType.ESCAPABLE_RAW_TEXT) {
  10059. this._closeVoidElement();
  10060. this._consumeText(this._advance());
  10061. }
  10062. else if (this._peek.type === TokenType.EXPANSION_FORM_START) {
  10063. this._consumeExpansion(this._advance());
  10064. }
  10065. else {
  10066. // Skip all other tokens...
  10067. this._advance();
  10068. }
  10069. }
  10070. return new ParseTreeResult(this._rootNodes, this._errors);
  10071. };
  10072. _TreeBuilder.prototype._advance = function () {
  10073. var prev = this._peek;
  10074. if (this._index < this.tokens.length - 1) {
  10075. // Note: there is always an EOF token at the end
  10076. this._index++;
  10077. }
  10078. this._peek = this.tokens[this._index];
  10079. return prev;
  10080. };
  10081. _TreeBuilder.prototype._advanceIf = function (type) {
  10082. if (this._peek.type === type) {
  10083. return this._advance();
  10084. }
  10085. return null;
  10086. };
  10087. _TreeBuilder.prototype._consumeCdata = function (startToken) {
  10088. this._consumeText(this._advance());
  10089. this._advanceIf(TokenType.CDATA_END);
  10090. };
  10091. _TreeBuilder.prototype._consumeComment = function (token) {
  10092. var text = this._advanceIf(TokenType.RAW_TEXT);
  10093. this._advanceIf(TokenType.COMMENT_END);
  10094. var value = text != null ? text.parts[0].trim() : null;
  10095. this._addToParent(new Comment(value, token.sourceSpan));
  10096. };
  10097. _TreeBuilder.prototype._consumeExpansion = function (token) {
  10098. var switchValue = this._advance();
  10099. var type = this._advance();
  10100. var cases = [];
  10101. // read =
  10102. while (this._peek.type === TokenType.EXPANSION_CASE_VALUE) {
  10103. var expCase = this._parseExpansionCase();
  10104. if (!expCase)
  10105. return; // error
  10106. cases.push(expCase);
  10107. }
  10108. // read the final }
  10109. if (this._peek.type !== TokenType.EXPANSION_FORM_END) {
  10110. this._errors.push(TreeError.create(null, this._peek.sourceSpan, "Invalid ICU message. Missing '}'."));
  10111. return;
  10112. }
  10113. var sourceSpan = new ParseSourceSpan(token.sourceSpan.start, this._peek.sourceSpan.end);
  10114. this._addToParent(new Expansion(switchValue.parts[0], type.parts[0], cases, sourceSpan, switchValue.sourceSpan));
  10115. this._advance();
  10116. };
  10117. _TreeBuilder.prototype._parseExpansionCase = function () {
  10118. var value = this._advance();
  10119. // read {
  10120. if (this._peek.type !== TokenType.EXPANSION_CASE_EXP_START) {
  10121. this._errors.push(TreeError.create(null, this._peek.sourceSpan, "Invalid ICU message. Missing '{'."));
  10122. return null;
  10123. }
  10124. // read until }
  10125. var start = this._advance();
  10126. var exp = this._collectExpansionExpTokens(start);
  10127. if (!exp)
  10128. return null;
  10129. var end = this._advance();
  10130. exp.push(new Token(TokenType.EOF, [], end.sourceSpan));
  10131. // parse everything in between { and }
  10132. var parsedExp = new _TreeBuilder(exp, this.getTagDefinition).build();
  10133. if (parsedExp.errors.length > 0) {
  10134. this._errors = this._errors.concat(parsedExp.errors);
  10135. return null;
  10136. }
  10137. var sourceSpan = new ParseSourceSpan(value.sourceSpan.start, end.sourceSpan.end);
  10138. var expSourceSpan = new ParseSourceSpan(start.sourceSpan.start, end.sourceSpan.end);
  10139. return new ExpansionCase(value.parts[0], parsedExp.rootNodes, sourceSpan, value.sourceSpan, expSourceSpan);
  10140. };
  10141. _TreeBuilder.prototype._collectExpansionExpTokens = function (start) {
  10142. var exp = [];
  10143. var expansionFormStack = [TokenType.EXPANSION_CASE_EXP_START];
  10144. while (true) {
  10145. if (this._peek.type === TokenType.EXPANSION_FORM_START ||
  10146. this._peek.type === TokenType.EXPANSION_CASE_EXP_START) {
  10147. expansionFormStack.push(this._peek.type);
  10148. }
  10149. if (this._peek.type === TokenType.EXPANSION_CASE_EXP_END) {
  10150. if (lastOnStack(expansionFormStack, TokenType.EXPANSION_CASE_EXP_START)) {
  10151. expansionFormStack.pop();
  10152. if (expansionFormStack.length == 0)
  10153. return exp;
  10154. }
  10155. else {
  10156. this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
  10157. return null;
  10158. }
  10159. }
  10160. if (this._peek.type === TokenType.EXPANSION_FORM_END) {
  10161. if (lastOnStack(expansionFormStack, TokenType.EXPANSION_FORM_START)) {
  10162. expansionFormStack.pop();
  10163. }
  10164. else {
  10165. this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
  10166. return null;
  10167. }
  10168. }
  10169. if (this._peek.type === TokenType.EOF) {
  10170. this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
  10171. return null;
  10172. }
  10173. exp.push(this._advance());
  10174. }
  10175. };
  10176. _TreeBuilder.prototype._consumeText = function (token) {
  10177. var text = token.parts[0];
  10178. if (text.length > 0 && text[0] == '\n') {
  10179. var parent_1 = this._getParentElement();
  10180. if (parent_1 != null && parent_1.children.length == 0 &&
  10181. this.getTagDefinition(parent_1.name).ignoreFirstLf) {
  10182. text = text.substring(1);
  10183. }
  10184. }
  10185. if (text.length > 0) {
  10186. this._addToParent(new Text$3(text, token.sourceSpan));
  10187. }
  10188. };
  10189. _TreeBuilder.prototype._closeVoidElement = function () {
  10190. var el = this._getParentElement();
  10191. if (el && this.getTagDefinition(el.name).isVoid) {
  10192. this._elementStack.pop();
  10193. }
  10194. };
  10195. _TreeBuilder.prototype._consumeStartTag = function (startTagToken) {
  10196. var prefix = startTagToken.parts[0];
  10197. var name = startTagToken.parts[1];
  10198. var attrs = [];
  10199. while (this._peek.type === TokenType.ATTR_NAME) {
  10200. attrs.push(this._consumeAttr(this._advance()));
  10201. }
  10202. var fullName = this._getElementFullName(prefix, name, this._getParentElement());
  10203. var selfClosing = false;
  10204. // Note: There could have been a tokenizer error
  10205. // so that we don't get a token for the end tag...
  10206. if (this._peek.type === TokenType.TAG_OPEN_END_VOID) {
  10207. this._advance();
  10208. selfClosing = true;
  10209. var tagDef = this.getTagDefinition(fullName);
  10210. if (!(tagDef.canSelfClose || getNsPrefix(fullName) !== null || tagDef.isVoid)) {
  10211. this._errors.push(TreeError.create(fullName, startTagToken.sourceSpan, "Only void and foreign elements can be self closed \"" + startTagToken.parts[1] + "\""));
  10212. }
  10213. }
  10214. else if (this._peek.type === TokenType.TAG_OPEN_END) {
  10215. this._advance();
  10216. selfClosing = false;
  10217. }
  10218. var end = this._peek.sourceSpan.start;
  10219. var span = new ParseSourceSpan(startTagToken.sourceSpan.start, end);
  10220. var el = new Element$1(fullName, attrs, [], span, span, undefined);
  10221. this._pushElement(el);
  10222. if (selfClosing) {
  10223. this._popElement(fullName);
  10224. el.endSourceSpan = span;
  10225. }
  10226. };
  10227. _TreeBuilder.prototype._pushElement = function (el) {
  10228. var parentEl = this._getParentElement();
  10229. if (parentEl && this.getTagDefinition(parentEl.name).isClosedByChild(el.name)) {
  10230. this._elementStack.pop();
  10231. }
  10232. this._addToParent(el);
  10233. this._elementStack.push(el);
  10234. };
  10235. _TreeBuilder.prototype._consumeEndTag = function (endTagToken) {
  10236. var fullName = this._getElementFullName(endTagToken.parts[0], endTagToken.parts[1], this._getParentElement());
  10237. if (this._getParentElement()) {
  10238. this._getParentElement().endSourceSpan = endTagToken.sourceSpan;
  10239. }
  10240. if (this.getTagDefinition(fullName).isVoid) {
  10241. this._errors.push(TreeError.create(fullName, endTagToken.sourceSpan, "Void elements do not have end tags \"" + endTagToken.parts[1] + "\""));
  10242. }
  10243. else if (!this._popElement(fullName)) {
  10244. 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";
  10245. this._errors.push(TreeError.create(fullName, endTagToken.sourceSpan, errMsg));
  10246. }
  10247. };
  10248. _TreeBuilder.prototype._popElement = function (fullName) {
  10249. for (var stackIndex = this._elementStack.length - 1; stackIndex >= 0; stackIndex--) {
  10250. var el = this._elementStack[stackIndex];
  10251. if (el.name == fullName) {
  10252. this._elementStack.splice(stackIndex, this._elementStack.length - stackIndex);
  10253. return true;
  10254. }
  10255. if (!this.getTagDefinition(el.name).closedByParent) {
  10256. return false;
  10257. }
  10258. }
  10259. return false;
  10260. };
  10261. _TreeBuilder.prototype._consumeAttr = function (attrName) {
  10262. var fullName = mergeNsAndName(attrName.parts[0], attrName.parts[1]);
  10263. var end = attrName.sourceSpan.end;
  10264. var value = '';
  10265. var valueSpan = undefined;
  10266. if (this._peek.type === TokenType.ATTR_QUOTE) {
  10267. this._advance();
  10268. }
  10269. if (this._peek.type === TokenType.ATTR_VALUE) {
  10270. var valueToken = this._advance();
  10271. value = valueToken.parts[0];
  10272. end = valueToken.sourceSpan.end;
  10273. valueSpan = valueToken.sourceSpan;
  10274. }
  10275. if (this._peek.type === TokenType.ATTR_QUOTE) {
  10276. var quoteToken = this._advance();
  10277. end = quoteToken.sourceSpan.end;
  10278. }
  10279. return new Attribute(fullName, value, new ParseSourceSpan(attrName.sourceSpan.start, end), valueSpan);
  10280. };
  10281. _TreeBuilder.prototype._getParentElement = function () {
  10282. return this._elementStack.length > 0 ? this._elementStack[this._elementStack.length - 1] : null;
  10283. };
  10284. /**
  10285. * Returns the parent in the DOM and the container.
  10286. *
  10287. * `<ng-container>` elements are skipped as they are not rendered as DOM element.
  10288. */
  10289. _TreeBuilder.prototype._getParentElementSkippingContainers = function () {
  10290. var container = null;
  10291. for (var i = this._elementStack.length - 1; i >= 0; i--) {
  10292. if (!isNgContainer(this._elementStack[i].name)) {
  10293. return { parent: this._elementStack[i], container: container };
  10294. }
  10295. container = this._elementStack[i];
  10296. }
  10297. return { parent: null, container: container };
  10298. };
  10299. _TreeBuilder.prototype._addToParent = function (node) {
  10300. var parent = this._getParentElement();
  10301. if (parent != null) {
  10302. parent.children.push(node);
  10303. }
  10304. else {
  10305. this._rootNodes.push(node);
  10306. }
  10307. };
  10308. /**
  10309. * Insert a node between the parent and the container.
  10310. * When no container is given, the node is appended as a child of the parent.
  10311. * Also updates the element stack accordingly.
  10312. *
  10313. * @internal
  10314. */
  10315. _TreeBuilder.prototype._insertBeforeContainer = function (parent, container, node) {
  10316. if (!container) {
  10317. this._addToParent(node);
  10318. this._elementStack.push(node);
  10319. }
  10320. else {
  10321. if (parent) {
  10322. // replace the container with the new node in the children
  10323. var index = parent.children.indexOf(container);
  10324. parent.children[index] = node;
  10325. }
  10326. else {
  10327. this._rootNodes.push(node);
  10328. }
  10329. node.children.push(container);
  10330. this._elementStack.splice(this._elementStack.indexOf(container), 0, node);
  10331. }
  10332. };
  10333. _TreeBuilder.prototype._getElementFullName = function (prefix, localName, parentElement) {
  10334. if (prefix === '') {
  10335. prefix = this.getTagDefinition(localName).implicitNamespacePrefix || '';
  10336. if (prefix === '' && parentElement != null) {
  10337. prefix = getNsPrefix(parentElement.name);
  10338. }
  10339. }
  10340. return mergeNsAndName(prefix, localName);
  10341. };
  10342. return _TreeBuilder;
  10343. }());
  10344. function lastOnStack(stack, element) {
  10345. return stack.length > 0 && stack[stack.length - 1] === element;
  10346. }
  10347. /**
  10348. * @license
  10349. * Copyright Google Inc. All Rights Reserved.
  10350. *
  10351. * Use of this source code is governed by an MIT-style license that can be
  10352. * found in the LICENSE file at https://angular.io/license
  10353. */
  10354. var HtmlParser = /** @class */ (function (_super) {
  10355. __extends(HtmlParser, _super);
  10356. function HtmlParser() {
  10357. return _super.call(this, getHtmlTagDefinition) || this;
  10358. }
  10359. HtmlParser.prototype.parse = function (source, url, options) {
  10360. return _super.prototype.parse.call(this, source, url, options);
  10361. };
  10362. return HtmlParser;
  10363. }(Parser));
  10364. /**
  10365. * @license
  10366. * Copyright Google Inc. All Rights Reserved.
  10367. *
  10368. * Use of this source code is governed by an MIT-style license that can be
  10369. * found in the LICENSE file at https://angular.io/license
  10370. */
  10371. var PRESERVE_WS_ATTR_NAME = 'ngPreserveWhitespaces';
  10372. var SKIP_WS_TRIM_TAGS = new Set(['pre', 'template', 'textarea', 'script', 'style']);
  10373. // Equivalent to \s with \u00a0 (non-breaking space) excluded.
  10374. // Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
  10375. var WS_CHARS = ' \f\n\r\t\v\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff';
  10376. var NO_WS_REGEXP = new RegExp("[^" + WS_CHARS + "]");
  10377. var WS_REPLACE_REGEXP = new RegExp("[" + WS_CHARS + "]{2,}", 'g');
  10378. function hasPreserveWhitespacesAttr(attrs) {
  10379. return attrs.some(function (attr) { return attr.name === PRESERVE_WS_ATTR_NAME; });
  10380. }
  10381. /**
  10382. * Angular Dart introduced &ngsp; as a placeholder for non-removable space, see:
  10383. * https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart#L25-L32
  10384. * In Angular Dart &ngsp; is converted to the 0xE500 PUA (Private Use Areas) unicode character
  10385. * and later on replaced by a space. We are re-implementing the same idea here.
  10386. */
  10387. function replaceNgsp(value) {
  10388. // lexer is replacing the &ngsp; pseudo-entity with NGSP_UNICODE
  10389. return value.replace(new RegExp(NGSP_UNICODE, 'g'), ' ');
  10390. }
  10391. /**
  10392. * This visitor can walk HTML parse tree and remove / trim text nodes using the following rules:
  10393. * - consider spaces, tabs and new lines as whitespace characters;
  10394. * - drop text nodes consisting of whitespace characters only;
  10395. * - for all other text nodes replace consecutive whitespace characters with one space;
  10396. * - convert &ngsp; pseudo-entity to a single space;
  10397. *
  10398. * Removal and trimming of whitespaces have positive performance impact (less code to generate
  10399. * while compiling templates, faster view creation). At the same time it can be "destructive"
  10400. * in some cases (whitespaces can influence layout). Because of the potential of breaking layout
  10401. * this visitor is not activated by default in Angular 5 and people need to explicitly opt-in for
  10402. * whitespace removal. The default option for whitespace removal will be revisited in Angular 6
  10403. * and might be changed to "on" by default.
  10404. */
  10405. var WhitespaceVisitor = /** @class */ (function () {
  10406. function WhitespaceVisitor() {
  10407. }
  10408. WhitespaceVisitor.prototype.visitElement = function (element, context) {
  10409. if (SKIP_WS_TRIM_TAGS.has(element.name) || hasPreserveWhitespacesAttr(element.attrs)) {
  10410. // don't descent into elements where we need to preserve whitespaces
  10411. // but still visit all attributes to eliminate one used as a market to preserve WS
  10412. return new Element$1(element.name, visitAll$1(this, element.attrs), element.children, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  10413. }
  10414. return new Element$1(element.name, element.attrs, visitAll$1(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  10415. };
  10416. WhitespaceVisitor.prototype.visitAttribute = function (attribute, context) {
  10417. return attribute.name !== PRESERVE_WS_ATTR_NAME ? attribute : null;
  10418. };
  10419. WhitespaceVisitor.prototype.visitText = function (text, context) {
  10420. var isNotBlank = text.value.match(NO_WS_REGEXP);
  10421. if (isNotBlank) {
  10422. return new Text$3(replaceNgsp(text.value).replace(WS_REPLACE_REGEXP, ' '), text.sourceSpan, text.i18n);
  10423. }
  10424. return null;
  10425. };
  10426. WhitespaceVisitor.prototype.visitComment = function (comment, context) { return comment; };
  10427. WhitespaceVisitor.prototype.visitExpansion = function (expansion, context) { return expansion; };
  10428. WhitespaceVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return expansionCase; };
  10429. return WhitespaceVisitor;
  10430. }());
  10431. function removeWhitespaces(htmlAstWithErrors) {
  10432. return new ParseTreeResult(visitAll$1(new WhitespaceVisitor(), htmlAstWithErrors.rootNodes), htmlAstWithErrors.errors);
  10433. }
  10434. /**
  10435. * @license
  10436. * Copyright Google Inc. All Rights Reserved.
  10437. *
  10438. * Use of this source code is governed by an MIT-style license that can be
  10439. * found in the LICENSE file at https://angular.io/license
  10440. */
  10441. // http://cldr.unicode.org/index/cldr-spec/plural-rules
  10442. var PLURAL_CASES = ['zero', 'one', 'two', 'few', 'many', 'other'];
  10443. /**
  10444. * Expands special forms into elements.
  10445. *
  10446. * For example,
  10447. *
  10448. * ```
  10449. * { messages.length, plural,
  10450. * =0 {zero}
  10451. * =1 {one}
  10452. * other {more than one}
  10453. * }
  10454. * ```
  10455. *
  10456. * will be expanded into
  10457. *
  10458. * ```
  10459. * <ng-container [ngPlural]="messages.length">
  10460. * <ng-template ngPluralCase="=0">zero</ng-template>
  10461. * <ng-template ngPluralCase="=1">one</ng-template>
  10462. * <ng-template ngPluralCase="other">more than one</ng-template>
  10463. * </ng-container>
  10464. * ```
  10465. */
  10466. function expandNodes(nodes) {
  10467. var expander = new _Expander();
  10468. return new ExpansionResult(visitAll$1(expander, nodes), expander.isExpanded, expander.errors);
  10469. }
  10470. var ExpansionResult = /** @class */ (function () {
  10471. function ExpansionResult(nodes, expanded, errors) {
  10472. this.nodes = nodes;
  10473. this.expanded = expanded;
  10474. this.errors = errors;
  10475. }
  10476. return ExpansionResult;
  10477. }());
  10478. var ExpansionError = /** @class */ (function (_super) {
  10479. __extends(ExpansionError, _super);
  10480. function ExpansionError(span, errorMsg) {
  10481. return _super.call(this, span, errorMsg) || this;
  10482. }
  10483. return ExpansionError;
  10484. }(ParseError));
  10485. /**
  10486. * Expand expansion forms (plural, select) to directives
  10487. *
  10488. * @internal
  10489. */
  10490. var _Expander = /** @class */ (function () {
  10491. function _Expander() {
  10492. this.isExpanded = false;
  10493. this.errors = [];
  10494. }
  10495. _Expander.prototype.visitElement = function (element, context) {
  10496. return new Element$1(element.name, element.attrs, visitAll$1(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan);
  10497. };
  10498. _Expander.prototype.visitAttribute = function (attribute, context) { return attribute; };
  10499. _Expander.prototype.visitText = function (text, context) { return text; };
  10500. _Expander.prototype.visitComment = function (comment, context) { return comment; };
  10501. _Expander.prototype.visitExpansion = function (icu, context) {
  10502. this.isExpanded = true;
  10503. return icu.type == 'plural' ? _expandPluralForm(icu, this.errors) :
  10504. _expandDefaultForm(icu, this.errors);
  10505. };
  10506. _Expander.prototype.visitExpansionCase = function (icuCase, context) {
  10507. throw new Error('Should not be reached');
  10508. };
  10509. return _Expander;
  10510. }());
  10511. // Plural forms are expanded to `NgPlural` and `NgPluralCase`s
  10512. function _expandPluralForm(ast, errors) {
  10513. var children = ast.cases.map(function (c) {
  10514. if (PLURAL_CASES.indexOf(c.value) == -1 && !c.value.match(/^=\d+$/)) {
  10515. errors.push(new ExpansionError(c.valueSourceSpan, "Plural cases should be \"=<number>\" or one of " + PLURAL_CASES.join(", ")));
  10516. }
  10517. var expansionResult = expandNodes(c.expression);
  10518. errors.push.apply(errors, __spread(expansionResult.errors));
  10519. return new Element$1("ng-template", [new Attribute('ngPluralCase', "" + c.value, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
  10520. });
  10521. var switchAttr = new Attribute('[ngPlural]', ast.switchValue, ast.switchValueSourceSpan);
  10522. return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan);
  10523. }
  10524. // ICU messages (excluding plural form) are expanded to `NgSwitch` and `NgSwitchCase`s
  10525. function _expandDefaultForm(ast, errors) {
  10526. var children = ast.cases.map(function (c) {
  10527. var expansionResult = expandNodes(c.expression);
  10528. errors.push.apply(errors, __spread(expansionResult.errors));
  10529. if (c.value === 'other') {
  10530. // other is the default case when no values match
  10531. return new Element$1("ng-template", [new Attribute('ngSwitchDefault', '', c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
  10532. }
  10533. return new Element$1("ng-template", [new Attribute('ngSwitchCase', "" + c.value, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
  10534. });
  10535. var switchAttr = new Attribute('[ngSwitch]', ast.switchValue, ast.switchValueSourceSpan);
  10536. return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan);
  10537. }
  10538. /**
  10539. * @license
  10540. * Copyright Google Inc. All Rights Reserved.
  10541. *
  10542. * Use of this source code is governed by an MIT-style license that can be
  10543. * found in the LICENSE file at https://angular.io/license
  10544. */
  10545. var _a;
  10546. /**
  10547. * A segment of text within the template.
  10548. */
  10549. var TextAst = /** @class */ (function () {
  10550. function TextAst(value, ngContentIndex, sourceSpan) {
  10551. this.value = value;
  10552. this.ngContentIndex = ngContentIndex;
  10553. this.sourceSpan = sourceSpan;
  10554. }
  10555. TextAst.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
  10556. return TextAst;
  10557. }());
  10558. /**
  10559. * A bound expression within the text of a template.
  10560. */
  10561. var BoundTextAst = /** @class */ (function () {
  10562. function BoundTextAst(value, ngContentIndex, sourceSpan) {
  10563. this.value = value;
  10564. this.ngContentIndex = ngContentIndex;
  10565. this.sourceSpan = sourceSpan;
  10566. }
  10567. BoundTextAst.prototype.visit = function (visitor, context) {
  10568. return visitor.visitBoundText(this, context);
  10569. };
  10570. return BoundTextAst;
  10571. }());
  10572. /**
  10573. * A plain attribute on an element.
  10574. */
  10575. var AttrAst = /** @class */ (function () {
  10576. function AttrAst(name, value, sourceSpan) {
  10577. this.name = name;
  10578. this.value = value;
  10579. this.sourceSpan = sourceSpan;
  10580. }
  10581. AttrAst.prototype.visit = function (visitor, context) { return visitor.visitAttr(this, context); };
  10582. return AttrAst;
  10583. }());
  10584. var BoundPropertyMapping = (_a = {},
  10585. _a[4 /* Animation */] = 4 /* Animation */,
  10586. _a[1 /* Attribute */] = 1 /* Attribute */,
  10587. _a[2 /* Class */] = 2 /* Class */,
  10588. _a[0 /* Property */] = 0 /* Property */,
  10589. _a[3 /* Style */] = 3 /* Style */,
  10590. _a);
  10591. /**
  10592. * A binding for an element property (e.g. `[property]="expression"`) or an animation trigger (e.g.
  10593. * `[@trigger]="stateExp"`)
  10594. */
  10595. var BoundElementPropertyAst = /** @class */ (function () {
  10596. function BoundElementPropertyAst(name, type, securityContext, value, unit, sourceSpan) {
  10597. this.name = name;
  10598. this.type = type;
  10599. this.securityContext = securityContext;
  10600. this.value = value;
  10601. this.unit = unit;
  10602. this.sourceSpan = sourceSpan;
  10603. this.isAnimation = this.type === 4 /* Animation */;
  10604. }
  10605. BoundElementPropertyAst.fromBoundProperty = function (prop) {
  10606. var type = BoundPropertyMapping[prop.type];
  10607. return new BoundElementPropertyAst(prop.name, type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan);
  10608. };
  10609. BoundElementPropertyAst.prototype.visit = function (visitor, context) {
  10610. return visitor.visitElementProperty(this, context);
  10611. };
  10612. return BoundElementPropertyAst;
  10613. }());
  10614. /**
  10615. * A binding for an element event (e.g. `(event)="handler()"`) or an animation trigger event (e.g.
  10616. * `(@trigger.phase)="callback($event)"`).
  10617. */
  10618. var BoundEventAst = /** @class */ (function () {
  10619. function BoundEventAst(name, target, phase, handler, sourceSpan, handlerSpan) {
  10620. this.name = name;
  10621. this.target = target;
  10622. this.phase = phase;
  10623. this.handler = handler;
  10624. this.sourceSpan = sourceSpan;
  10625. this.handlerSpan = handlerSpan;
  10626. this.fullName = BoundEventAst.calcFullName(this.name, this.target, this.phase);
  10627. this.isAnimation = !!this.phase;
  10628. }
  10629. BoundEventAst.calcFullName = function (name, target, phase) {
  10630. if (target) {
  10631. return target + ":" + name;
  10632. }
  10633. if (phase) {
  10634. return "@" + name + "." + phase;
  10635. }
  10636. return name;
  10637. };
  10638. BoundEventAst.fromParsedEvent = function (event) {
  10639. var target = event.type === 0 /* Regular */ ? event.targetOrPhase : null;
  10640. var phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null;
  10641. return new BoundEventAst(event.name, target, phase, event.handler, event.sourceSpan, event.handlerSpan);
  10642. };
  10643. BoundEventAst.prototype.visit = function (visitor, context) {
  10644. return visitor.visitEvent(this, context);
  10645. };
  10646. return BoundEventAst;
  10647. }());
  10648. /**
  10649. * A reference declaration on an element (e.g. `let someName="expression"`).
  10650. */
  10651. var ReferenceAst = /** @class */ (function () {
  10652. function ReferenceAst(name, value, originalValue, sourceSpan) {
  10653. this.name = name;
  10654. this.value = value;
  10655. this.originalValue = originalValue;
  10656. this.sourceSpan = sourceSpan;
  10657. }
  10658. ReferenceAst.prototype.visit = function (visitor, context) {
  10659. return visitor.visitReference(this, context);
  10660. };
  10661. return ReferenceAst;
  10662. }());
  10663. /**
  10664. * A variable declaration on a <ng-template> (e.g. `var-someName="someLocalName"`).
  10665. */
  10666. var VariableAst = /** @class */ (function () {
  10667. function VariableAst(name, value, sourceSpan) {
  10668. this.name = name;
  10669. this.value = value;
  10670. this.sourceSpan = sourceSpan;
  10671. }
  10672. VariableAst.fromParsedVariable = function (v) {
  10673. return new VariableAst(v.name, v.value, v.sourceSpan);
  10674. };
  10675. VariableAst.prototype.visit = function (visitor, context) {
  10676. return visitor.visitVariable(this, context);
  10677. };
  10678. return VariableAst;
  10679. }());
  10680. /**
  10681. * An element declaration in a template.
  10682. */
  10683. var ElementAst = /** @class */ (function () {
  10684. function ElementAst(name, attrs, inputs, outputs, references, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan, endSourceSpan) {
  10685. this.name = name;
  10686. this.attrs = attrs;
  10687. this.inputs = inputs;
  10688. this.outputs = outputs;
  10689. this.references = references;
  10690. this.directives = directives;
  10691. this.providers = providers;
  10692. this.hasViewContainer = hasViewContainer;
  10693. this.queryMatches = queryMatches;
  10694. this.children = children;
  10695. this.ngContentIndex = ngContentIndex;
  10696. this.sourceSpan = sourceSpan;
  10697. this.endSourceSpan = endSourceSpan;
  10698. }
  10699. ElementAst.prototype.visit = function (visitor, context) {
  10700. return visitor.visitElement(this, context);
  10701. };
  10702. return ElementAst;
  10703. }());
  10704. /**
  10705. * A `<ng-template>` element included in an Angular template.
  10706. */
  10707. var EmbeddedTemplateAst = /** @class */ (function () {
  10708. function EmbeddedTemplateAst(attrs, outputs, references, variables, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan) {
  10709. this.attrs = attrs;
  10710. this.outputs = outputs;
  10711. this.references = references;
  10712. this.variables = variables;
  10713. this.directives = directives;
  10714. this.providers = providers;
  10715. this.hasViewContainer = hasViewContainer;
  10716. this.queryMatches = queryMatches;
  10717. this.children = children;
  10718. this.ngContentIndex = ngContentIndex;
  10719. this.sourceSpan = sourceSpan;
  10720. }
  10721. EmbeddedTemplateAst.prototype.visit = function (visitor, context) {
  10722. return visitor.visitEmbeddedTemplate(this, context);
  10723. };
  10724. return EmbeddedTemplateAst;
  10725. }());
  10726. /**
  10727. * A directive property with a bound value (e.g. `*ngIf="condition").
  10728. */
  10729. var BoundDirectivePropertyAst = /** @class */ (function () {
  10730. function BoundDirectivePropertyAst(directiveName, templateName, value, sourceSpan) {
  10731. this.directiveName = directiveName;
  10732. this.templateName = templateName;
  10733. this.value = value;
  10734. this.sourceSpan = sourceSpan;
  10735. }
  10736. BoundDirectivePropertyAst.prototype.visit = function (visitor, context) {
  10737. return visitor.visitDirectiveProperty(this, context);
  10738. };
  10739. return BoundDirectivePropertyAst;
  10740. }());
  10741. /**
  10742. * A directive declared on an element.
  10743. */
  10744. var DirectiveAst = /** @class */ (function () {
  10745. function DirectiveAst(directive, inputs, hostProperties, hostEvents, contentQueryStartId, sourceSpan) {
  10746. this.directive = directive;
  10747. this.inputs = inputs;
  10748. this.hostProperties = hostProperties;
  10749. this.hostEvents = hostEvents;
  10750. this.contentQueryStartId = contentQueryStartId;
  10751. this.sourceSpan = sourceSpan;
  10752. }
  10753. DirectiveAst.prototype.visit = function (visitor, context) {
  10754. return visitor.visitDirective(this, context);
  10755. };
  10756. return DirectiveAst;
  10757. }());
  10758. /**
  10759. * A provider declared on an element
  10760. */
  10761. var ProviderAst = /** @class */ (function () {
  10762. function ProviderAst(token, multiProvider, eager, providers, providerType, lifecycleHooks, sourceSpan, isModule) {
  10763. this.token = token;
  10764. this.multiProvider = multiProvider;
  10765. this.eager = eager;
  10766. this.providers = providers;
  10767. this.providerType = providerType;
  10768. this.lifecycleHooks = lifecycleHooks;
  10769. this.sourceSpan = sourceSpan;
  10770. this.isModule = isModule;
  10771. }
  10772. ProviderAst.prototype.visit = function (visitor, context) {
  10773. // No visit method in the visitor for now...
  10774. return null;
  10775. };
  10776. return ProviderAst;
  10777. }());
  10778. (function (ProviderAstType) {
  10779. ProviderAstType[ProviderAstType["PublicService"] = 0] = "PublicService";
  10780. ProviderAstType[ProviderAstType["PrivateService"] = 1] = "PrivateService";
  10781. ProviderAstType[ProviderAstType["Component"] = 2] = "Component";
  10782. ProviderAstType[ProviderAstType["Directive"] = 3] = "Directive";
  10783. ProviderAstType[ProviderAstType["Builtin"] = 4] = "Builtin";
  10784. })(exports.ProviderAstType || (exports.ProviderAstType = {}));
  10785. /**
  10786. * Position where content is to be projected (instance of `<ng-content>` in a template).
  10787. */
  10788. var NgContentAst = /** @class */ (function () {
  10789. function NgContentAst(index, ngContentIndex, sourceSpan) {
  10790. this.index = index;
  10791. this.ngContentIndex = ngContentIndex;
  10792. this.sourceSpan = sourceSpan;
  10793. }
  10794. NgContentAst.prototype.visit = function (visitor, context) {
  10795. return visitor.visitNgContent(this, context);
  10796. };
  10797. return NgContentAst;
  10798. }());
  10799. /**
  10800. * A visitor that accepts each node but doesn't do anything. It is intended to be used
  10801. * as the base class for a visitor that is only interested in a subset of the node types.
  10802. */
  10803. var NullTemplateVisitor = /** @class */ (function () {
  10804. function NullTemplateVisitor() {
  10805. }
  10806. NullTemplateVisitor.prototype.visitNgContent = function (ast, context) { };
  10807. NullTemplateVisitor.prototype.visitEmbeddedTemplate = function (ast, context) { };
  10808. NullTemplateVisitor.prototype.visitElement = function (ast, context) { };
  10809. NullTemplateVisitor.prototype.visitReference = function (ast, context) { };
  10810. NullTemplateVisitor.prototype.visitVariable = function (ast, context) { };
  10811. NullTemplateVisitor.prototype.visitEvent = function (ast, context) { };
  10812. NullTemplateVisitor.prototype.visitElementProperty = function (ast, context) { };
  10813. NullTemplateVisitor.prototype.visitAttr = function (ast, context) { };
  10814. NullTemplateVisitor.prototype.visitBoundText = function (ast, context) { };
  10815. NullTemplateVisitor.prototype.visitText = function (ast, context) { };
  10816. NullTemplateVisitor.prototype.visitDirective = function (ast, context) { };
  10817. NullTemplateVisitor.prototype.visitDirectiveProperty = function (ast, context) { };
  10818. return NullTemplateVisitor;
  10819. }());
  10820. /**
  10821. * Base class that can be used to build a visitor that visits each node
  10822. * in an template ast recursively.
  10823. */
  10824. var RecursiveTemplateAstVisitor = /** @class */ (function (_super) {
  10825. __extends(RecursiveTemplateAstVisitor, _super);
  10826. function RecursiveTemplateAstVisitor() {
  10827. return _super.call(this) || this;
  10828. }
  10829. // Nodes with children
  10830. RecursiveTemplateAstVisitor.prototype.visitEmbeddedTemplate = function (ast, context) {
  10831. return this.visitChildren(context, function (visit) {
  10832. visit(ast.attrs);
  10833. visit(ast.references);
  10834. visit(ast.variables);
  10835. visit(ast.directives);
  10836. visit(ast.providers);
  10837. visit(ast.children);
  10838. });
  10839. };
  10840. RecursiveTemplateAstVisitor.prototype.visitElement = function (ast, context) {
  10841. return this.visitChildren(context, function (visit) {
  10842. visit(ast.attrs);
  10843. visit(ast.inputs);
  10844. visit(ast.outputs);
  10845. visit(ast.references);
  10846. visit(ast.directives);
  10847. visit(ast.providers);
  10848. visit(ast.children);
  10849. });
  10850. };
  10851. RecursiveTemplateAstVisitor.prototype.visitDirective = function (ast, context) {
  10852. return this.visitChildren(context, function (visit) {
  10853. visit(ast.inputs);
  10854. visit(ast.hostProperties);
  10855. visit(ast.hostEvents);
  10856. });
  10857. };
  10858. RecursiveTemplateAstVisitor.prototype.visitChildren = function (context, cb) {
  10859. var results = [];
  10860. var t = this;
  10861. function visit(children) {
  10862. if (children && children.length)
  10863. results.push(templateVisitAll(t, children, context));
  10864. }
  10865. cb(visit);
  10866. return [].concat.apply([], results);
  10867. };
  10868. return RecursiveTemplateAstVisitor;
  10869. }(NullTemplateVisitor));
  10870. /**
  10871. * Visit every node in a list of {@link TemplateAst}s with the given {@link TemplateAstVisitor}.
  10872. */
  10873. function templateVisitAll(visitor, asts, context) {
  10874. if (context === void 0) { context = null; }
  10875. var result = [];
  10876. var visit = visitor.visit ?
  10877. function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } :
  10878. function (ast) { return ast.visit(visitor, context); };
  10879. asts.forEach(function (ast) {
  10880. var astResult = visit(ast);
  10881. if (astResult) {
  10882. result.push(astResult);
  10883. }
  10884. });
  10885. return result;
  10886. }
  10887. /**
  10888. * @license
  10889. * Copyright Google Inc. All Rights Reserved.
  10890. *
  10891. * Use of this source code is governed by an MIT-style license that can be
  10892. * found in the LICENSE file at https://angular.io/license
  10893. */
  10894. var ProviderError = /** @class */ (function (_super) {
  10895. __extends(ProviderError, _super);
  10896. function ProviderError(message, span) {
  10897. return _super.call(this, span, message) || this;
  10898. }
  10899. return ProviderError;
  10900. }(ParseError));
  10901. var ProviderViewContext = /** @class */ (function () {
  10902. function ProviderViewContext(reflector, component) {
  10903. var _this = this;
  10904. this.reflector = reflector;
  10905. this.component = component;
  10906. this.errors = [];
  10907. this.viewQueries = _getViewQueries(component);
  10908. this.viewProviders = new Map();
  10909. component.viewProviders.forEach(function (provider) {
  10910. if (_this.viewProviders.get(tokenReference(provider.token)) == null) {
  10911. _this.viewProviders.set(tokenReference(provider.token), true);
  10912. }
  10913. });
  10914. }
  10915. return ProviderViewContext;
  10916. }());
  10917. var ProviderElementContext = /** @class */ (function () {
  10918. function ProviderElementContext(viewContext, _parent, _isViewRoot, _directiveAsts, attrs, refs, isTemplate, contentQueryStartId, _sourceSpan) {
  10919. var _this = this;
  10920. this.viewContext = viewContext;
  10921. this._parent = _parent;
  10922. this._isViewRoot = _isViewRoot;
  10923. this._directiveAsts = _directiveAsts;
  10924. this._sourceSpan = _sourceSpan;
  10925. this._transformedProviders = new Map();
  10926. this._seenProviders = new Map();
  10927. this._queriedTokens = new Map();
  10928. this.transformedHasViewContainer = false;
  10929. this._attrs = {};
  10930. attrs.forEach(function (attrAst) { return _this._attrs[attrAst.name] = attrAst.value; });
  10931. var directivesMeta = _directiveAsts.map(function (directiveAst) { return directiveAst.directive; });
  10932. this._allProviders =
  10933. _resolveProvidersFromDirectives(directivesMeta, _sourceSpan, viewContext.errors);
  10934. this._contentQueries = _getContentQueries(contentQueryStartId, directivesMeta);
  10935. Array.from(this._allProviders.values()).forEach(function (provider) {
  10936. _this._addQueryReadsTo(provider.token, provider.token, _this._queriedTokens);
  10937. });
  10938. if (isTemplate) {
  10939. var templateRefId = createTokenForExternalReference(this.viewContext.reflector, Identifiers.TemplateRef);
  10940. this._addQueryReadsTo(templateRefId, templateRefId, this._queriedTokens);
  10941. }
  10942. refs.forEach(function (refAst) {
  10943. var defaultQueryValue = refAst.value ||
  10944. createTokenForExternalReference(_this.viewContext.reflector, Identifiers.ElementRef);
  10945. _this._addQueryReadsTo({ value: refAst.name }, defaultQueryValue, _this._queriedTokens);
  10946. });
  10947. if (this._queriedTokens.get(this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef))) {
  10948. this.transformedHasViewContainer = true;
  10949. }
  10950. // create the providers that we know are eager first
  10951. Array.from(this._allProviders.values()).forEach(function (provider) {
  10952. var eager = provider.eager || _this._queriedTokens.get(tokenReference(provider.token));
  10953. if (eager) {
  10954. _this._getOrCreateLocalProvider(provider.providerType, provider.token, true);
  10955. }
  10956. });
  10957. }
  10958. ProviderElementContext.prototype.afterElement = function () {
  10959. var _this = this;
  10960. // collect lazy providers
  10961. Array.from(this._allProviders.values()).forEach(function (provider) {
  10962. _this._getOrCreateLocalProvider(provider.providerType, provider.token, false);
  10963. });
  10964. };
  10965. Object.defineProperty(ProviderElementContext.prototype, "transformProviders", {
  10966. get: function () {
  10967. // Note: Maps keep their insertion order.
  10968. var lazyProviders = [];
  10969. var eagerProviders = [];
  10970. this._transformedProviders.forEach(function (provider) {
  10971. if (provider.eager) {
  10972. eagerProviders.push(provider);
  10973. }
  10974. else {
  10975. lazyProviders.push(provider);
  10976. }
  10977. });
  10978. return lazyProviders.concat(eagerProviders);
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(ProviderElementContext.prototype, "transformedDirectiveAsts", {
  10984. get: function () {
  10985. var sortedProviderTypes = this.transformProviders.map(function (provider) { return provider.token.identifier; });
  10986. var sortedDirectives = this._directiveAsts.slice();
  10987. sortedDirectives.sort(function (dir1, dir2) { return sortedProviderTypes.indexOf(dir1.directive.type) -
  10988. sortedProviderTypes.indexOf(dir2.directive.type); });
  10989. return sortedDirectives;
  10990. },
  10991. enumerable: true,
  10992. configurable: true
  10993. });
  10994. Object.defineProperty(ProviderElementContext.prototype, "queryMatches", {
  10995. get: function () {
  10996. var allMatches = [];
  10997. this._queriedTokens.forEach(function (matches) { allMatches.push.apply(allMatches, __spread(matches)); });
  10998. return allMatches;
  10999. },
  11000. enumerable: true,
  11001. configurable: true
  11002. });
  11003. ProviderElementContext.prototype._addQueryReadsTo = function (token, defaultValue, queryReadTokens) {
  11004. this._getQueriesFor(token).forEach(function (query) {
  11005. var queryValue = query.meta.read || defaultValue;
  11006. var tokenRef = tokenReference(queryValue);
  11007. var queryMatches = queryReadTokens.get(tokenRef);
  11008. if (!queryMatches) {
  11009. queryMatches = [];
  11010. queryReadTokens.set(tokenRef, queryMatches);
  11011. }
  11012. queryMatches.push({ queryId: query.queryId, value: queryValue });
  11013. });
  11014. };
  11015. ProviderElementContext.prototype._getQueriesFor = function (token) {
  11016. var result = [];
  11017. var currentEl = this;
  11018. var distance = 0;
  11019. var queries;
  11020. while (currentEl !== null) {
  11021. queries = currentEl._contentQueries.get(tokenReference(token));
  11022. if (queries) {
  11023. result.push.apply(result, __spread(queries.filter(function (query) { return query.meta.descendants || distance <= 1; })));
  11024. }
  11025. if (currentEl._directiveAsts.length > 0) {
  11026. distance++;
  11027. }
  11028. currentEl = currentEl._parent;
  11029. }
  11030. queries = this.viewContext.viewQueries.get(tokenReference(token));
  11031. if (queries) {
  11032. result.push.apply(result, __spread(queries));
  11033. }
  11034. return result;
  11035. };
  11036. ProviderElementContext.prototype._getOrCreateLocalProvider = function (requestingProviderType, token, eager) {
  11037. var _this = this;
  11038. var resolvedProvider = this._allProviders.get(tokenReference(token));
  11039. if (!resolvedProvider || ((requestingProviderType === exports.ProviderAstType.Directive ||
  11040. requestingProviderType === exports.ProviderAstType.PublicService) &&
  11041. resolvedProvider.providerType === exports.ProviderAstType.PrivateService) ||
  11042. ((requestingProviderType === exports.ProviderAstType.PrivateService ||
  11043. requestingProviderType === exports.ProviderAstType.PublicService) &&
  11044. resolvedProvider.providerType === exports.ProviderAstType.Builtin)) {
  11045. return null;
  11046. }
  11047. var transformedProviderAst = this._transformedProviders.get(tokenReference(token));
  11048. if (transformedProviderAst) {
  11049. return transformedProviderAst;
  11050. }
  11051. if (this._seenProviders.get(tokenReference(token)) != null) {
  11052. this.viewContext.errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), this._sourceSpan));
  11053. return null;
  11054. }
  11055. this._seenProviders.set(tokenReference(token), true);
  11056. var transformedProviders = resolvedProvider.providers.map(function (provider) {
  11057. var transformedUseValue = provider.useValue;
  11058. var transformedUseExisting = provider.useExisting;
  11059. var transformedDeps = undefined;
  11060. if (provider.useExisting != null) {
  11061. var existingDiDep = _this._getDependency(resolvedProvider.providerType, { token: provider.useExisting }, eager);
  11062. if (existingDiDep.token != null) {
  11063. transformedUseExisting = existingDiDep.token;
  11064. }
  11065. else {
  11066. transformedUseExisting = null;
  11067. transformedUseValue = existingDiDep.value;
  11068. }
  11069. }
  11070. else if (provider.useFactory) {
  11071. var deps = provider.deps || provider.useFactory.diDeps;
  11072. transformedDeps =
  11073. deps.map(function (dep) { return _this._getDependency(resolvedProvider.providerType, dep, eager); });
  11074. }
  11075. else if (provider.useClass) {
  11076. var deps = provider.deps || provider.useClass.diDeps;
  11077. transformedDeps =
  11078. deps.map(function (dep) { return _this._getDependency(resolvedProvider.providerType, dep, eager); });
  11079. }
  11080. return _transformProvider(provider, {
  11081. useExisting: transformedUseExisting,
  11082. useValue: transformedUseValue,
  11083. deps: transformedDeps
  11084. });
  11085. });
  11086. transformedProviderAst =
  11087. _transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders });
  11088. this._transformedProviders.set(tokenReference(token), transformedProviderAst);
  11089. return transformedProviderAst;
  11090. };
  11091. ProviderElementContext.prototype._getLocalDependency = function (requestingProviderType, dep, eager) {
  11092. if (eager === void 0) { eager = false; }
  11093. if (dep.isAttribute) {
  11094. var attrValue = this._attrs[dep.token.value];
  11095. return { isValue: true, value: attrValue == null ? null : attrValue };
  11096. }
  11097. if (dep.token != null) {
  11098. // access builtints
  11099. if ((requestingProviderType === exports.ProviderAstType.Directive ||
  11100. requestingProviderType === exports.ProviderAstType.Component)) {
  11101. if (tokenReference(dep.token) ===
  11102. this.viewContext.reflector.resolveExternalReference(Identifiers.Renderer) ||
  11103. tokenReference(dep.token) ===
  11104. this.viewContext.reflector.resolveExternalReference(Identifiers.ElementRef) ||
  11105. tokenReference(dep.token) ===
  11106. this.viewContext.reflector.resolveExternalReference(Identifiers.ChangeDetectorRef) ||
  11107. tokenReference(dep.token) ===
  11108. this.viewContext.reflector.resolveExternalReference(Identifiers.TemplateRef)) {
  11109. return dep;
  11110. }
  11111. if (tokenReference(dep.token) ===
  11112. this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef)) {
  11113. this.transformedHasViewContainer = true;
  11114. }
  11115. }
  11116. // access the injector
  11117. if (tokenReference(dep.token) ===
  11118. this.viewContext.reflector.resolveExternalReference(Identifiers.Injector)) {
  11119. return dep;
  11120. }
  11121. // access providers
  11122. if (this._getOrCreateLocalProvider(requestingProviderType, dep.token, eager) != null) {
  11123. return dep;
  11124. }
  11125. }
  11126. return null;
  11127. };
  11128. ProviderElementContext.prototype._getDependency = function (requestingProviderType, dep, eager) {
  11129. if (eager === void 0) { eager = false; }
  11130. var currElement = this;
  11131. var currEager = eager;
  11132. var result = null;
  11133. if (!dep.isSkipSelf) {
  11134. result = this._getLocalDependency(requestingProviderType, dep, eager);
  11135. }
  11136. if (dep.isSelf) {
  11137. if (!result && dep.isOptional) {
  11138. result = { isValue: true, value: null };
  11139. }
  11140. }
  11141. else {
  11142. // check parent elements
  11143. while (!result && currElement._parent) {
  11144. var prevElement = currElement;
  11145. currElement = currElement._parent;
  11146. if (prevElement._isViewRoot) {
  11147. currEager = false;
  11148. }
  11149. result = currElement._getLocalDependency(exports.ProviderAstType.PublicService, dep, currEager);
  11150. }
  11151. // check @Host restriction
  11152. if (!result) {
  11153. if (!dep.isHost || this.viewContext.component.isHost ||
  11154. this.viewContext.component.type.reference === tokenReference(dep.token) ||
  11155. this.viewContext.viewProviders.get(tokenReference(dep.token)) != null) {
  11156. result = dep;
  11157. }
  11158. else {
  11159. result = dep.isOptional ? { isValue: true, value: null } : null;
  11160. }
  11161. }
  11162. }
  11163. if (!result) {
  11164. this.viewContext.errors.push(new ProviderError("No provider for " + tokenName(dep.token), this._sourceSpan));
  11165. }
  11166. return result;
  11167. };
  11168. return ProviderElementContext;
  11169. }());
  11170. var NgModuleProviderAnalyzer = /** @class */ (function () {
  11171. function NgModuleProviderAnalyzer(reflector, ngModule, extraProviders, sourceSpan) {
  11172. var _this = this;
  11173. this.reflector = reflector;
  11174. this._transformedProviders = new Map();
  11175. this._seenProviders = new Map();
  11176. this._errors = [];
  11177. this._allProviders = new Map();
  11178. ngModule.transitiveModule.modules.forEach(function (ngModuleType) {
  11179. var ngModuleProvider = { token: { identifier: ngModuleType }, useClass: ngModuleType };
  11180. _resolveProviders([ngModuleProvider], exports.ProviderAstType.PublicService, true, sourceSpan, _this._errors, _this._allProviders, /* isModule */ true);
  11181. });
  11182. _resolveProviders(ngModule.transitiveModule.providers.map(function (entry) { return entry.provider; }).concat(extraProviders), exports.ProviderAstType.PublicService, false, sourceSpan, this._errors, this._allProviders,
  11183. /* isModule */ false);
  11184. }
  11185. NgModuleProviderAnalyzer.prototype.parse = function () {
  11186. var _this = this;
  11187. Array.from(this._allProviders.values()).forEach(function (provider) {
  11188. _this._getOrCreateLocalProvider(provider.token, provider.eager);
  11189. });
  11190. if (this._errors.length > 0) {
  11191. var errorString = this._errors.join('\n');
  11192. throw new Error("Provider parse errors:\n" + errorString);
  11193. }
  11194. // Note: Maps keep their insertion order.
  11195. var lazyProviders = [];
  11196. var eagerProviders = [];
  11197. this._transformedProviders.forEach(function (provider) {
  11198. if (provider.eager) {
  11199. eagerProviders.push(provider);
  11200. }
  11201. else {
  11202. lazyProviders.push(provider);
  11203. }
  11204. });
  11205. return lazyProviders.concat(eagerProviders);
  11206. };
  11207. NgModuleProviderAnalyzer.prototype._getOrCreateLocalProvider = function (token, eager) {
  11208. var _this = this;
  11209. var resolvedProvider = this._allProviders.get(tokenReference(token));
  11210. if (!resolvedProvider) {
  11211. return null;
  11212. }
  11213. var transformedProviderAst = this._transformedProviders.get(tokenReference(token));
  11214. if (transformedProviderAst) {
  11215. return transformedProviderAst;
  11216. }
  11217. if (this._seenProviders.get(tokenReference(token)) != null) {
  11218. this._errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), resolvedProvider.sourceSpan));
  11219. return null;
  11220. }
  11221. this._seenProviders.set(tokenReference(token), true);
  11222. var transformedProviders = resolvedProvider.providers.map(function (provider) {
  11223. var transformedUseValue = provider.useValue;
  11224. var transformedUseExisting = provider.useExisting;
  11225. var transformedDeps = undefined;
  11226. if (provider.useExisting != null) {
  11227. var existingDiDep = _this._getDependency({ token: provider.useExisting }, eager, resolvedProvider.sourceSpan);
  11228. if (existingDiDep.token != null) {
  11229. transformedUseExisting = existingDiDep.token;
  11230. }
  11231. else {
  11232. transformedUseExisting = null;
  11233. transformedUseValue = existingDiDep.value;
  11234. }
  11235. }
  11236. else if (provider.useFactory) {
  11237. var deps = provider.deps || provider.useFactory.diDeps;
  11238. transformedDeps =
  11239. deps.map(function (dep) { return _this._getDependency(dep, eager, resolvedProvider.sourceSpan); });
  11240. }
  11241. else if (provider.useClass) {
  11242. var deps = provider.deps || provider.useClass.diDeps;
  11243. transformedDeps =
  11244. deps.map(function (dep) { return _this._getDependency(dep, eager, resolvedProvider.sourceSpan); });
  11245. }
  11246. return _transformProvider(provider, {
  11247. useExisting: transformedUseExisting,
  11248. useValue: transformedUseValue,
  11249. deps: transformedDeps
  11250. });
  11251. });
  11252. transformedProviderAst =
  11253. _transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders });
  11254. this._transformedProviders.set(tokenReference(token), transformedProviderAst);
  11255. return transformedProviderAst;
  11256. };
  11257. NgModuleProviderAnalyzer.prototype._getDependency = function (dep, eager, requestorSourceSpan) {
  11258. if (eager === void 0) { eager = false; }
  11259. if (!dep.isSkipSelf && dep.token != null) {
  11260. // access the injector
  11261. if (tokenReference(dep.token) ===
  11262. this.reflector.resolveExternalReference(Identifiers.Injector) ||
  11263. tokenReference(dep.token) ===
  11264. this.reflector.resolveExternalReference(Identifiers.ComponentFactoryResolver)) ;
  11265. else if (this._getOrCreateLocalProvider(dep.token, eager) != null) ;
  11266. }
  11267. return dep;
  11268. };
  11269. return NgModuleProviderAnalyzer;
  11270. }());
  11271. function _transformProvider(provider, _a) {
  11272. var useExisting = _a.useExisting, useValue = _a.useValue, deps = _a.deps;
  11273. return {
  11274. token: provider.token,
  11275. useClass: provider.useClass,
  11276. useExisting: useExisting,
  11277. useFactory: provider.useFactory,
  11278. useValue: useValue,
  11279. deps: deps,
  11280. multi: provider.multi
  11281. };
  11282. }
  11283. function _transformProviderAst(provider, _a) {
  11284. var eager = _a.eager, providers = _a.providers;
  11285. return new ProviderAst(provider.token, provider.multiProvider, provider.eager || eager, providers, provider.providerType, provider.lifecycleHooks, provider.sourceSpan, provider.isModule);
  11286. }
  11287. function _resolveProvidersFromDirectives(directives, sourceSpan, targetErrors) {
  11288. var providersByToken = new Map();
  11289. directives.forEach(function (directive) {
  11290. var dirProvider = { token: { identifier: directive.type }, useClass: directive.type };
  11291. _resolveProviders([dirProvider], directive.isComponent ? exports.ProviderAstType.Component : exports.ProviderAstType.Directive, true, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
  11292. });
  11293. // Note: directives need to be able to overwrite providers of a component!
  11294. var directivesWithComponentFirst = directives.filter(function (dir) { return dir.isComponent; }).concat(directives.filter(function (dir) { return !dir.isComponent; }));
  11295. directivesWithComponentFirst.forEach(function (directive) {
  11296. _resolveProviders(directive.providers, exports.ProviderAstType.PublicService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
  11297. _resolveProviders(directive.viewProviders, exports.ProviderAstType.PrivateService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
  11298. });
  11299. return providersByToken;
  11300. }
  11301. function _resolveProviders(providers, providerType, eager, sourceSpan, targetErrors, targetProvidersByToken, isModule) {
  11302. providers.forEach(function (provider) {
  11303. var resolvedProvider = targetProvidersByToken.get(tokenReference(provider.token));
  11304. if (resolvedProvider != null && !!resolvedProvider.multiProvider !== !!provider.multi) {
  11305. targetErrors.push(new ProviderError("Mixing multi and non multi provider is not possible for token " + tokenName(resolvedProvider.token), sourceSpan));
  11306. }
  11307. if (!resolvedProvider) {
  11308. var lifecycleHooks = provider.token.identifier &&
  11309. provider.token.identifier.lifecycleHooks ?
  11310. provider.token.identifier.lifecycleHooks :
  11311. [];
  11312. var isUseValue = !(provider.useClass || provider.useExisting || provider.useFactory);
  11313. resolvedProvider = new ProviderAst(provider.token, !!provider.multi, eager || isUseValue, [provider], providerType, lifecycleHooks, sourceSpan, isModule);
  11314. targetProvidersByToken.set(tokenReference(provider.token), resolvedProvider);
  11315. }
  11316. else {
  11317. if (!provider.multi) {
  11318. resolvedProvider.providers.length = 0;
  11319. }
  11320. resolvedProvider.providers.push(provider);
  11321. }
  11322. });
  11323. }
  11324. function _getViewQueries(component) {
  11325. // Note: queries start with id 1 so we can use the number in a Bloom filter!
  11326. var viewQueryId = 1;
  11327. var viewQueries = new Map();
  11328. if (component.viewQueries) {
  11329. component.viewQueries.forEach(function (query) { return _addQueryToTokenMap(viewQueries, { meta: query, queryId: viewQueryId++ }); });
  11330. }
  11331. return viewQueries;
  11332. }
  11333. function _getContentQueries(contentQueryStartId, directives) {
  11334. var contentQueryId = contentQueryStartId;
  11335. var contentQueries = new Map();
  11336. directives.forEach(function (directive, directiveIndex) {
  11337. if (directive.queries) {
  11338. directive.queries.forEach(function (query) { return _addQueryToTokenMap(contentQueries, { meta: query, queryId: contentQueryId++ }); });
  11339. }
  11340. });
  11341. return contentQueries;
  11342. }
  11343. function _addQueryToTokenMap(map, query) {
  11344. query.meta.selectors.forEach(function (token) {
  11345. var entry = map.get(tokenReference(token));
  11346. if (!entry) {
  11347. entry = [];
  11348. map.set(tokenReference(token), entry);
  11349. }
  11350. entry.push(query);
  11351. });
  11352. }
  11353. /**
  11354. * @license
  11355. * Copyright Google Inc. All Rights Reserved.
  11356. *
  11357. * Use of this source code is governed by an MIT-style license that can be
  11358. * found in the LICENSE file at https://angular.io/license
  11359. */
  11360. var StyleWithImports = /** @class */ (function () {
  11361. function StyleWithImports(style, styleUrls) {
  11362. this.style = style;
  11363. this.styleUrls = styleUrls;
  11364. }
  11365. return StyleWithImports;
  11366. }());
  11367. function isStyleUrlResolvable(url) {
  11368. if (url == null || url.length === 0 || url[0] == '/')
  11369. return false;
  11370. var schemeMatch = url.match(URL_WITH_SCHEMA_REGEXP);
  11371. return schemeMatch === null || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset';
  11372. }
  11373. /**
  11374. * Rewrites stylesheets by resolving and removing the @import urls that
  11375. * are either relative or don't have a `package:` scheme
  11376. */
  11377. function extractStyleUrls(resolver, baseUrl, cssText) {
  11378. var foundUrls = [];
  11379. var modifiedCssText = cssText.replace(CSS_STRIPPABLE_COMMENT_REGEXP, '')
  11380. .replace(CSS_IMPORT_REGEXP, function () {
  11381. var m = [];
  11382. for (var _i = 0; _i < arguments.length; _i++) {
  11383. m[_i] = arguments[_i];
  11384. }
  11385. var url = m[1] || m[2];
  11386. if (!isStyleUrlResolvable(url)) {
  11387. // Do not attempt to resolve non-package absolute URLs with URI
  11388. // scheme
  11389. return m[0];
  11390. }
  11391. foundUrls.push(resolver.resolve(baseUrl, url));
  11392. return '';
  11393. });
  11394. return new StyleWithImports(modifiedCssText, foundUrls);
  11395. }
  11396. var CSS_IMPORT_REGEXP = /@import\s+(?:url\()?\s*(?:(?:['"]([^'"]*))|([^;\)\s]*))[^;]*;?/g;
  11397. var CSS_STRIPPABLE_COMMENT_REGEXP = /\/\*(?!#\s*(?:sourceURL|sourceMappingURL)=)[\s\S]+?\*\//g;
  11398. var URL_WITH_SCHEMA_REGEXP = /^([^:/?#]+):/;
  11399. /**
  11400. * @license
  11401. * Copyright Google Inc. All Rights Reserved.
  11402. *
  11403. * Use of this source code is governed by an MIT-style license that can be
  11404. * found in the LICENSE file at https://angular.io/license
  11405. */
  11406. var PROPERTY_PARTS_SEPARATOR = '.';
  11407. var ATTRIBUTE_PREFIX = 'attr';
  11408. var CLASS_PREFIX = 'class';
  11409. var STYLE_PREFIX = 'style';
  11410. var ANIMATE_PROP_PREFIX = 'animate-';
  11411. /**
  11412. * Parses bindings in templates and in the directive host area.
  11413. */
  11414. var BindingParser = /** @class */ (function () {
  11415. function BindingParser(_exprParser, _interpolationConfig, _schemaRegistry, pipes, errors) {
  11416. this._exprParser = _exprParser;
  11417. this._interpolationConfig = _interpolationConfig;
  11418. this._schemaRegistry = _schemaRegistry;
  11419. this.errors = errors;
  11420. this.pipesByName = null;
  11421. this._usedPipes = new Map();
  11422. // When the `pipes` parameter is `null`, do not check for used pipes
  11423. // This is used in IVY when we might not know the available pipes at compile time
  11424. if (pipes) {
  11425. var pipesByName_1 = new Map();
  11426. pipes.forEach(function (pipe) { return pipesByName_1.set(pipe.name, pipe); });
  11427. this.pipesByName = pipesByName_1;
  11428. }
  11429. }
  11430. Object.defineProperty(BindingParser.prototype, "interpolationConfig", {
  11431. get: function () { return this._interpolationConfig; },
  11432. enumerable: true,
  11433. configurable: true
  11434. });
  11435. BindingParser.prototype.getUsedPipes = function () { return Array.from(this._usedPipes.values()); };
  11436. BindingParser.prototype.createBoundHostProperties = function (dirMeta, sourceSpan) {
  11437. var _this = this;
  11438. if (dirMeta.hostProperties) {
  11439. var boundProps_1 = [];
  11440. Object.keys(dirMeta.hostProperties).forEach(function (propName) {
  11441. var expression = dirMeta.hostProperties[propName];
  11442. if (typeof expression === 'string') {
  11443. _this.parsePropertyBinding(propName, expression, true, sourceSpan, [], boundProps_1);
  11444. }
  11445. else {
  11446. _this._reportError("Value of the host property binding \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan);
  11447. }
  11448. });
  11449. return boundProps_1;
  11450. }
  11451. return null;
  11452. };
  11453. BindingParser.prototype.createDirectiveHostPropertyAsts = function (dirMeta, elementSelector, sourceSpan) {
  11454. var _this = this;
  11455. var boundProps = this.createBoundHostProperties(dirMeta, sourceSpan);
  11456. return boundProps &&
  11457. boundProps.map(function (prop) { return _this.createBoundElementProperty(elementSelector, prop); });
  11458. };
  11459. BindingParser.prototype.createDirectiveHostEventAsts = function (dirMeta, sourceSpan) {
  11460. var _this = this;
  11461. if (dirMeta.hostListeners) {
  11462. var targetEvents_1 = [];
  11463. Object.keys(dirMeta.hostListeners).forEach(function (propName) {
  11464. var expression = dirMeta.hostListeners[propName];
  11465. if (typeof expression === 'string') {
  11466. // TODO: pass a more accurate handlerSpan for this event.
  11467. _this.parseEvent(propName, expression, sourceSpan, sourceSpan, [], targetEvents_1);
  11468. }
  11469. else {
  11470. _this._reportError("Value of the host listener \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan);
  11471. }
  11472. });
  11473. return targetEvents_1;
  11474. }
  11475. return null;
  11476. };
  11477. BindingParser.prototype.parseInterpolation = function (value, sourceSpan) {
  11478. var sourceInfo = sourceSpan.start.toString();
  11479. try {
  11480. var ast = this._exprParser.parseInterpolation(value, sourceInfo, this._interpolationConfig);
  11481. if (ast)
  11482. this._reportExpressionParserErrors(ast.errors, sourceSpan);
  11483. this._checkPipes(ast, sourceSpan);
  11484. return ast;
  11485. }
  11486. catch (e) {
  11487. this._reportError("" + e, sourceSpan);
  11488. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
  11489. }
  11490. };
  11491. // Parse an inline template binding. ie `<tag *tplKey="<tplValue>">`
  11492. BindingParser.prototype.parseInlineTemplateBinding = function (tplKey, tplValue, sourceSpan, targetMatchableAttrs, targetProps, targetVars) {
  11493. var bindings = this._parseTemplateBindings(tplKey, tplValue, sourceSpan);
  11494. for (var i = 0; i < bindings.length; i++) {
  11495. var binding = bindings[i];
  11496. if (binding.keyIsVar) {
  11497. targetVars.push(new ParsedVariable(binding.key, binding.name, sourceSpan));
  11498. }
  11499. else if (binding.expression) {
  11500. this._parsePropertyAst(binding.key, binding.expression, sourceSpan, targetMatchableAttrs, targetProps);
  11501. }
  11502. else {
  11503. targetMatchableAttrs.push([binding.key, '']);
  11504. this.parseLiteralAttr(binding.key, null, sourceSpan, targetMatchableAttrs, targetProps);
  11505. }
  11506. }
  11507. };
  11508. BindingParser.prototype._parseTemplateBindings = function (tplKey, tplValue, sourceSpan) {
  11509. var _this = this;
  11510. var sourceInfo = sourceSpan.start.toString();
  11511. try {
  11512. var bindingsResult = this._exprParser.parseTemplateBindings(tplKey, tplValue, sourceInfo);
  11513. this._reportExpressionParserErrors(bindingsResult.errors, sourceSpan);
  11514. bindingsResult.templateBindings.forEach(function (binding) {
  11515. if (binding.expression) {
  11516. _this._checkPipes(binding.expression, sourceSpan);
  11517. }
  11518. });
  11519. bindingsResult.warnings.forEach(function (warning) { _this._reportError(warning, sourceSpan, exports.ParseErrorLevel.WARNING); });
  11520. return bindingsResult.templateBindings;
  11521. }
  11522. catch (e) {
  11523. this._reportError("" + e, sourceSpan);
  11524. return [];
  11525. }
  11526. };
  11527. BindingParser.prototype.parseLiteralAttr = function (name, value, sourceSpan, targetMatchableAttrs, targetProps) {
  11528. if (isAnimationLabel(name)) {
  11529. name = name.substring(1);
  11530. if (value) {
  11531. this._reportError("Assigning animation triggers via @prop=\"exp\" attributes with an expression is invalid." +
  11532. " Use property bindings (e.g. [@prop]=\"exp\") or use an attribute without a value (e.g. @prop) instead.", sourceSpan, exports.ParseErrorLevel.ERROR);
  11533. }
  11534. this._parseAnimation(name, value, sourceSpan, targetMatchableAttrs, targetProps);
  11535. }
  11536. else {
  11537. targetProps.push(new ParsedProperty(name, this._exprParser.wrapLiteralPrimitive(value, ''), exports.ParsedPropertyType.LITERAL_ATTR, sourceSpan));
  11538. }
  11539. };
  11540. BindingParser.prototype.parsePropertyBinding = function (name, expression, isHost, sourceSpan, targetMatchableAttrs, targetProps) {
  11541. var isAnimationProp = false;
  11542. if (name.startsWith(ANIMATE_PROP_PREFIX)) {
  11543. isAnimationProp = true;
  11544. name = name.substring(ANIMATE_PROP_PREFIX.length);
  11545. }
  11546. else if (isAnimationLabel(name)) {
  11547. isAnimationProp = true;
  11548. name = name.substring(1);
  11549. }
  11550. if (isAnimationProp) {
  11551. this._parseAnimation(name, expression, sourceSpan, targetMatchableAttrs, targetProps);
  11552. }
  11553. else {
  11554. this._parsePropertyAst(name, this._parseBinding(expression, isHost, sourceSpan), sourceSpan, targetMatchableAttrs, targetProps);
  11555. }
  11556. };
  11557. BindingParser.prototype.parsePropertyInterpolation = function (name, value, sourceSpan, targetMatchableAttrs, targetProps) {
  11558. var expr = this.parseInterpolation(value, sourceSpan);
  11559. if (expr) {
  11560. this._parsePropertyAst(name, expr, sourceSpan, targetMatchableAttrs, targetProps);
  11561. return true;
  11562. }
  11563. return false;
  11564. };
  11565. BindingParser.prototype._parsePropertyAst = function (name, ast, sourceSpan, targetMatchableAttrs, targetProps) {
  11566. targetMatchableAttrs.push([name, ast.source]);
  11567. targetProps.push(new ParsedProperty(name, ast, exports.ParsedPropertyType.DEFAULT, sourceSpan));
  11568. };
  11569. BindingParser.prototype._parseAnimation = function (name, expression, sourceSpan, targetMatchableAttrs, targetProps) {
  11570. // This will occur when a @trigger is not paired with an expression.
  11571. // For animations it is valid to not have an expression since */void
  11572. // states will be applied by angular when the element is attached/detached
  11573. var ast = this._parseBinding(expression || 'undefined', false, sourceSpan);
  11574. targetMatchableAttrs.push([name, ast.source]);
  11575. targetProps.push(new ParsedProperty(name, ast, exports.ParsedPropertyType.ANIMATION, sourceSpan));
  11576. };
  11577. BindingParser.prototype._parseBinding = function (value, isHostBinding, sourceSpan) {
  11578. var sourceInfo = (sourceSpan && sourceSpan.start || '(unknown)').toString();
  11579. try {
  11580. var ast = isHostBinding ?
  11581. this._exprParser.parseSimpleBinding(value, sourceInfo, this._interpolationConfig) :
  11582. this._exprParser.parseBinding(value, sourceInfo, this._interpolationConfig);
  11583. if (ast)
  11584. this._reportExpressionParserErrors(ast.errors, sourceSpan);
  11585. this._checkPipes(ast, sourceSpan);
  11586. return ast;
  11587. }
  11588. catch (e) {
  11589. this._reportError("" + e, sourceSpan);
  11590. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
  11591. }
  11592. };
  11593. BindingParser.prototype.createBoundElementProperty = function (elementSelector, boundProp, skipValidation, mapPropertyName) {
  11594. if (skipValidation === void 0) { skipValidation = false; }
  11595. if (mapPropertyName === void 0) { mapPropertyName = true; }
  11596. if (boundProp.isAnimation) {
  11597. return new BoundElementProperty(boundProp.name, 4 /* Animation */, SecurityContext.NONE, boundProp.expression, null, boundProp.sourceSpan);
  11598. }
  11599. var unit = null;
  11600. var bindingType = undefined;
  11601. var boundPropertyName = null;
  11602. var parts = boundProp.name.split(PROPERTY_PARTS_SEPARATOR);
  11603. var securityContexts = undefined;
  11604. // Check for special cases (prefix style, attr, class)
  11605. if (parts.length > 1) {
  11606. if (parts[0] == ATTRIBUTE_PREFIX) {
  11607. boundPropertyName = parts[1];
  11608. if (!skipValidation) {
  11609. this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, true);
  11610. }
  11611. securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, boundPropertyName, true);
  11612. var nsSeparatorIdx = boundPropertyName.indexOf(':');
  11613. if (nsSeparatorIdx > -1) {
  11614. var ns = boundPropertyName.substring(0, nsSeparatorIdx);
  11615. var name_1 = boundPropertyName.substring(nsSeparatorIdx + 1);
  11616. boundPropertyName = mergeNsAndName(ns, name_1);
  11617. }
  11618. bindingType = 1 /* Attribute */;
  11619. }
  11620. else if (parts[0] == CLASS_PREFIX) {
  11621. boundPropertyName = parts[1];
  11622. bindingType = 2 /* Class */;
  11623. securityContexts = [SecurityContext.NONE];
  11624. }
  11625. else if (parts[0] == STYLE_PREFIX) {
  11626. unit = parts.length > 2 ? parts[2] : null;
  11627. boundPropertyName = parts[1];
  11628. bindingType = 3 /* Style */;
  11629. securityContexts = [SecurityContext.STYLE];
  11630. }
  11631. }
  11632. // If not a special case, use the full property name
  11633. if (boundPropertyName === null) {
  11634. var mappedPropName = this._schemaRegistry.getMappedPropName(boundProp.name);
  11635. boundPropertyName = mapPropertyName ? mappedPropName : boundProp.name;
  11636. securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, mappedPropName, false);
  11637. bindingType = 0 /* Property */;
  11638. if (!skipValidation) {
  11639. this._validatePropertyOrAttributeName(mappedPropName, boundProp.sourceSpan, false);
  11640. }
  11641. }
  11642. return new BoundElementProperty(boundPropertyName, bindingType, securityContexts[0], boundProp.expression, unit, boundProp.sourceSpan);
  11643. };
  11644. BindingParser.prototype.parseEvent = function (name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents) {
  11645. if (isAnimationLabel(name)) {
  11646. name = name.substr(1);
  11647. this._parseAnimationEvent(name, expression, sourceSpan, handlerSpan, targetEvents);
  11648. }
  11649. else {
  11650. this._parseRegularEvent(name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents);
  11651. }
  11652. };
  11653. BindingParser.prototype.calcPossibleSecurityContexts = function (selector, propName, isAttribute) {
  11654. var prop = this._schemaRegistry.getMappedPropName(propName);
  11655. return calcPossibleSecurityContexts(this._schemaRegistry, selector, prop, isAttribute);
  11656. };
  11657. BindingParser.prototype._parseAnimationEvent = function (name, expression, sourceSpan, handlerSpan, targetEvents) {
  11658. var matches = splitAtPeriod(name, [name, '']);
  11659. var eventName = matches[0];
  11660. var phase = matches[1].toLowerCase();
  11661. if (phase) {
  11662. switch (phase) {
  11663. case 'start':
  11664. case 'done':
  11665. var ast = this._parseAction(expression, handlerSpan);
  11666. targetEvents.push(new ParsedEvent(eventName, phase, 1 /* Animation */, ast, sourceSpan, handlerSpan));
  11667. break;
  11668. default:
  11669. this._reportError("The provided animation output phase value \"" + phase + "\" for \"@" + eventName + "\" is not supported (use start or done)", sourceSpan);
  11670. break;
  11671. }
  11672. }
  11673. else {
  11674. this._reportError("The animation trigger output event (@" + eventName + ") is missing its phase value name (start or done are currently supported)", sourceSpan);
  11675. }
  11676. };
  11677. BindingParser.prototype._parseRegularEvent = function (name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents) {
  11678. // long format: 'target: eventName'
  11679. var _a = __read(splitAtColon(name, [null, name]), 2), target = _a[0], eventName = _a[1];
  11680. var ast = this._parseAction(expression, handlerSpan);
  11681. targetMatchableAttrs.push([name, ast.source]);
  11682. targetEvents.push(new ParsedEvent(eventName, target, 0 /* Regular */, ast, sourceSpan, handlerSpan));
  11683. // Don't detect directives for event names for now,
  11684. // so don't add the event name to the matchableAttrs
  11685. };
  11686. BindingParser.prototype._parseAction = function (value, sourceSpan) {
  11687. var sourceInfo = (sourceSpan && sourceSpan.start || '(unknown').toString();
  11688. try {
  11689. var ast = this._exprParser.parseAction(value, sourceInfo, this._interpolationConfig);
  11690. if (ast) {
  11691. this._reportExpressionParserErrors(ast.errors, sourceSpan);
  11692. }
  11693. if (!ast || ast.ast instanceof EmptyExpr) {
  11694. this._reportError("Empty expressions are not allowed", sourceSpan);
  11695. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
  11696. }
  11697. this._checkPipes(ast, sourceSpan);
  11698. return ast;
  11699. }
  11700. catch (e) {
  11701. this._reportError("" + e, sourceSpan);
  11702. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
  11703. }
  11704. };
  11705. BindingParser.prototype._reportError = function (message, sourceSpan, level) {
  11706. if (level === void 0) { level = exports.ParseErrorLevel.ERROR; }
  11707. this.errors.push(new ParseError(sourceSpan, message, level));
  11708. };
  11709. BindingParser.prototype._reportExpressionParserErrors = function (errors, sourceSpan) {
  11710. var e_1, _a;
  11711. try {
  11712. for (var errors_1 = __values(errors), errors_1_1 = errors_1.next(); !errors_1_1.done; errors_1_1 = errors_1.next()) {
  11713. var error = errors_1_1.value;
  11714. this._reportError(error.message, sourceSpan);
  11715. }
  11716. }
  11717. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  11718. finally {
  11719. try {
  11720. if (errors_1_1 && !errors_1_1.done && (_a = errors_1.return)) _a.call(errors_1);
  11721. }
  11722. finally { if (e_1) throw e_1.error; }
  11723. }
  11724. };
  11725. // Make sure all the used pipes are known in `this.pipesByName`
  11726. BindingParser.prototype._checkPipes = function (ast, sourceSpan) {
  11727. var _this = this;
  11728. if (ast && this.pipesByName) {
  11729. var collector = new PipeCollector();
  11730. ast.visit(collector);
  11731. collector.pipes.forEach(function (ast, pipeName) {
  11732. var pipeMeta = _this.pipesByName.get(pipeName);
  11733. if (!pipeMeta) {
  11734. _this._reportError("The pipe '" + pipeName + "' could not be found", new ParseSourceSpan(sourceSpan.start.moveBy(ast.span.start), sourceSpan.start.moveBy(ast.span.end)));
  11735. }
  11736. else {
  11737. _this._usedPipes.set(pipeName, pipeMeta);
  11738. }
  11739. });
  11740. }
  11741. };
  11742. /**
  11743. * @param propName the name of the property / attribute
  11744. * @param sourceSpan
  11745. * @param isAttr true when binding to an attribute
  11746. */
  11747. BindingParser.prototype._validatePropertyOrAttributeName = function (propName, sourceSpan, isAttr) {
  11748. var report = isAttr ? this._schemaRegistry.validateAttribute(propName) :
  11749. this._schemaRegistry.validateProperty(propName);
  11750. if (report.error) {
  11751. this._reportError(report.msg, sourceSpan, exports.ParseErrorLevel.ERROR);
  11752. }
  11753. };
  11754. return BindingParser;
  11755. }());
  11756. var PipeCollector = /** @class */ (function (_super) {
  11757. __extends(PipeCollector, _super);
  11758. function PipeCollector() {
  11759. var _this = _super !== null && _super.apply(this, arguments) || this;
  11760. _this.pipes = new Map();
  11761. return _this;
  11762. }
  11763. PipeCollector.prototype.visitPipe = function (ast, context) {
  11764. this.pipes.set(ast.name, ast);
  11765. ast.exp.visit(this);
  11766. this.visitAll(ast.args, context);
  11767. return null;
  11768. };
  11769. return PipeCollector;
  11770. }(RecursiveAstVisitor$1));
  11771. function isAnimationLabel(name) {
  11772. return name[0] == '@';
  11773. }
  11774. function calcPossibleSecurityContexts(registry, selector, propName, isAttribute) {
  11775. var ctxs = [];
  11776. CssSelector.parse(selector).forEach(function (selector) {
  11777. var elementNames = selector.element ? [selector.element] : registry.allKnownElementNames();
  11778. var notElementNames = new Set(selector.notSelectors.filter(function (selector) { return selector.isElementSelector(); })
  11779. .map(function (selector) { return selector.element; }));
  11780. var possibleElementNames = elementNames.filter(function (elementName) { return !notElementNames.has(elementName); });
  11781. ctxs.push.apply(ctxs, __spread(possibleElementNames.map(function (elementName) { return registry.securityContext(elementName, propName, isAttribute); })));
  11782. });
  11783. return ctxs.length === 0 ? [SecurityContext.NONE] : Array.from(new Set(ctxs)).sort();
  11784. }
  11785. /**
  11786. * @license
  11787. * Copyright Google Inc. All Rights Reserved.
  11788. *
  11789. * Use of this source code is governed by an MIT-style license that can be
  11790. * found in the LICENSE file at https://angular.io/license
  11791. */
  11792. var NG_CONTENT_SELECT_ATTR = 'select';
  11793. var LINK_ELEMENT = 'link';
  11794. var LINK_STYLE_REL_ATTR = 'rel';
  11795. var LINK_STYLE_HREF_ATTR = 'href';
  11796. var LINK_STYLE_REL_VALUE = 'stylesheet';
  11797. var STYLE_ELEMENT = 'style';
  11798. var SCRIPT_ELEMENT = 'script';
  11799. var NG_NON_BINDABLE_ATTR = 'ngNonBindable';
  11800. var NG_PROJECT_AS = 'ngProjectAs';
  11801. function preparseElement(ast) {
  11802. var selectAttr = null;
  11803. var hrefAttr = null;
  11804. var relAttr = null;
  11805. var nonBindable = false;
  11806. var projectAs = '';
  11807. ast.attrs.forEach(function (attr) {
  11808. var lcAttrName = attr.name.toLowerCase();
  11809. if (lcAttrName == NG_CONTENT_SELECT_ATTR) {
  11810. selectAttr = attr.value;
  11811. }
  11812. else if (lcAttrName == LINK_STYLE_HREF_ATTR) {
  11813. hrefAttr = attr.value;
  11814. }
  11815. else if (lcAttrName == LINK_STYLE_REL_ATTR) {
  11816. relAttr = attr.value;
  11817. }
  11818. else if (attr.name == NG_NON_BINDABLE_ATTR) {
  11819. nonBindable = true;
  11820. }
  11821. else if (attr.name == NG_PROJECT_AS) {
  11822. if (attr.value.length > 0) {
  11823. projectAs = attr.value;
  11824. }
  11825. }
  11826. });
  11827. selectAttr = normalizeNgContentSelect(selectAttr);
  11828. var nodeName = ast.name.toLowerCase();
  11829. var type = PreparsedElementType.OTHER;
  11830. if (isNgContent(nodeName)) {
  11831. type = PreparsedElementType.NG_CONTENT;
  11832. }
  11833. else if (nodeName == STYLE_ELEMENT) {
  11834. type = PreparsedElementType.STYLE;
  11835. }
  11836. else if (nodeName == SCRIPT_ELEMENT) {
  11837. type = PreparsedElementType.SCRIPT;
  11838. }
  11839. else if (nodeName == LINK_ELEMENT && relAttr == LINK_STYLE_REL_VALUE) {
  11840. type = PreparsedElementType.STYLESHEET;
  11841. }
  11842. return new PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs);
  11843. }
  11844. var PreparsedElementType;
  11845. (function (PreparsedElementType) {
  11846. PreparsedElementType[PreparsedElementType["NG_CONTENT"] = 0] = "NG_CONTENT";
  11847. PreparsedElementType[PreparsedElementType["STYLE"] = 1] = "STYLE";
  11848. PreparsedElementType[PreparsedElementType["STYLESHEET"] = 2] = "STYLESHEET";
  11849. PreparsedElementType[PreparsedElementType["SCRIPT"] = 3] = "SCRIPT";
  11850. PreparsedElementType[PreparsedElementType["OTHER"] = 4] = "OTHER";
  11851. })(PreparsedElementType || (PreparsedElementType = {}));
  11852. var PreparsedElement = /** @class */ (function () {
  11853. function PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs) {
  11854. this.type = type;
  11855. this.selectAttr = selectAttr;
  11856. this.hrefAttr = hrefAttr;
  11857. this.nonBindable = nonBindable;
  11858. this.projectAs = projectAs;
  11859. }
  11860. return PreparsedElement;
  11861. }());
  11862. function normalizeNgContentSelect(selectAttr) {
  11863. if (selectAttr === null || selectAttr.length === 0) {
  11864. return '*';
  11865. }
  11866. return selectAttr;
  11867. }
  11868. /**
  11869. * @license
  11870. * Copyright Google Inc. All Rights Reserved.
  11871. *
  11872. * Use of this source code is governed by an MIT-style license that can be
  11873. * found in the LICENSE file at https://angular.io/license
  11874. */
  11875. var BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/;
  11876. // Group 1 = "bind-"
  11877. var KW_BIND_IDX = 1;
  11878. // Group 2 = "let-"
  11879. var KW_LET_IDX = 2;
  11880. // Group 3 = "ref-/#"
  11881. var KW_REF_IDX = 3;
  11882. // Group 4 = "on-"
  11883. var KW_ON_IDX = 4;
  11884. // Group 5 = "bindon-"
  11885. var KW_BINDON_IDX = 5;
  11886. // Group 6 = "@"
  11887. var KW_AT_IDX = 6;
  11888. // Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
  11889. var IDENT_KW_IDX = 7;
  11890. // Group 8 = identifier inside [()]
  11891. var IDENT_BANANA_BOX_IDX = 8;
  11892. // Group 9 = identifier inside []
  11893. var IDENT_PROPERTY_IDX = 9;
  11894. // Group 10 = identifier inside ()
  11895. var IDENT_EVENT_IDX = 10;
  11896. var TEMPLATE_ATTR_PREFIX = '*';
  11897. var CLASS_ATTR = 'class';
  11898. var _TEXT_CSS_SELECTOR;
  11899. function TEXT_CSS_SELECTOR() {
  11900. if (!_TEXT_CSS_SELECTOR) {
  11901. _TEXT_CSS_SELECTOR = CssSelector.parse('*')[0];
  11902. }
  11903. return _TEXT_CSS_SELECTOR;
  11904. }
  11905. var TemplateParseError = /** @class */ (function (_super) {
  11906. __extends(TemplateParseError, _super);
  11907. function TemplateParseError(message, span, level) {
  11908. return _super.call(this, span, message, level) || this;
  11909. }
  11910. return TemplateParseError;
  11911. }(ParseError));
  11912. var TemplateParseResult = /** @class */ (function () {
  11913. function TemplateParseResult(templateAst, usedPipes, errors) {
  11914. this.templateAst = templateAst;
  11915. this.usedPipes = usedPipes;
  11916. this.errors = errors;
  11917. }
  11918. return TemplateParseResult;
  11919. }());
  11920. var TemplateParser = /** @class */ (function () {
  11921. function TemplateParser(_config, _reflector, _exprParser, _schemaRegistry, _htmlParser, _console, transforms) {
  11922. this._config = _config;
  11923. this._reflector = _reflector;
  11924. this._exprParser = _exprParser;
  11925. this._schemaRegistry = _schemaRegistry;
  11926. this._htmlParser = _htmlParser;
  11927. this._console = _console;
  11928. this.transforms = transforms;
  11929. }
  11930. Object.defineProperty(TemplateParser.prototype, "expressionParser", {
  11931. get: function () { return this._exprParser; },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. TemplateParser.prototype.parse = function (component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) {
  11936. var result = this.tryParse(component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces);
  11937. var warnings = result.errors.filter(function (error) { return error.level === exports.ParseErrorLevel.WARNING; });
  11938. var errors = result.errors.filter(function (error) { return error.level === exports.ParseErrorLevel.ERROR; });
  11939. if (warnings.length > 0) {
  11940. this._console.warn("Template parse warnings:\n" + warnings.join('\n'));
  11941. }
  11942. if (errors.length > 0) {
  11943. var errorString = errors.join('\n');
  11944. throw syntaxError("Template parse errors:\n" + errorString, errors);
  11945. }
  11946. return { template: result.templateAst, pipes: result.usedPipes };
  11947. };
  11948. TemplateParser.prototype.tryParse = function (component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) {
  11949. var htmlParseResult = typeof template === 'string' ?
  11950. this._htmlParser.parse(template, templateUrl, {
  11951. tokenizeExpansionForms: true,
  11952. interpolationConfig: this.getInterpolationConfig(component)
  11953. }) :
  11954. template;
  11955. if (!preserveWhitespaces) {
  11956. htmlParseResult = removeWhitespaces(htmlParseResult);
  11957. }
  11958. return this.tryParseHtml(this.expandHtml(htmlParseResult), component, directives, pipes, schemas);
  11959. };
  11960. TemplateParser.prototype.tryParseHtml = function (htmlAstWithErrors, component, directives, pipes, schemas) {
  11961. var result;
  11962. var errors = htmlAstWithErrors.errors;
  11963. var usedPipes = [];
  11964. if (htmlAstWithErrors.rootNodes.length > 0) {
  11965. var uniqDirectives = removeSummaryDuplicates(directives);
  11966. var uniqPipes = removeSummaryDuplicates(pipes);
  11967. var providerViewContext = new ProviderViewContext(this._reflector, component);
  11968. var interpolationConfig = undefined;
  11969. if (component.template && component.template.interpolation) {
  11970. interpolationConfig = {
  11971. start: component.template.interpolation[0],
  11972. end: component.template.interpolation[1]
  11973. };
  11974. }
  11975. var bindingParser = new BindingParser(this._exprParser, interpolationConfig, this._schemaRegistry, uniqPipes, errors);
  11976. var parseVisitor = new TemplateParseVisitor(this._reflector, this._config, providerViewContext, uniqDirectives, bindingParser, this._schemaRegistry, schemas, errors);
  11977. result = visitAll$1(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_ELEMENT_CONTEXT);
  11978. errors.push.apply(errors, __spread(providerViewContext.errors));
  11979. usedPipes.push.apply(usedPipes, __spread(bindingParser.getUsedPipes()));
  11980. }
  11981. else {
  11982. result = [];
  11983. }
  11984. this._assertNoReferenceDuplicationOnTemplate(result, errors);
  11985. if (errors.length > 0) {
  11986. return new TemplateParseResult(result, usedPipes, errors);
  11987. }
  11988. if (this.transforms) {
  11989. this.transforms.forEach(function (transform) { result = templateVisitAll(transform, result); });
  11990. }
  11991. return new TemplateParseResult(result, usedPipes, errors);
  11992. };
  11993. TemplateParser.prototype.expandHtml = function (htmlAstWithErrors, forced) {
  11994. if (forced === void 0) { forced = false; }
  11995. var errors = htmlAstWithErrors.errors;
  11996. if (errors.length == 0 || forced) {
  11997. // Transform ICU messages to angular directives
  11998. var expandedHtmlAst = expandNodes(htmlAstWithErrors.rootNodes);
  11999. errors.push.apply(errors, __spread(expandedHtmlAst.errors));
  12000. htmlAstWithErrors = new ParseTreeResult(expandedHtmlAst.nodes, errors);
  12001. }
  12002. return htmlAstWithErrors;
  12003. };
  12004. TemplateParser.prototype.getInterpolationConfig = function (component) {
  12005. if (component.template) {
  12006. return InterpolationConfig.fromArray(component.template.interpolation);
  12007. }
  12008. return undefined;
  12009. };
  12010. /** @internal */
  12011. TemplateParser.prototype._assertNoReferenceDuplicationOnTemplate = function (result, errors) {
  12012. var existingReferences = [];
  12013. result.filter(function (element) { return !!element.references; })
  12014. .forEach(function (element) { return element.references.forEach(function (reference) {
  12015. var name = reference.name;
  12016. if (existingReferences.indexOf(name) < 0) {
  12017. existingReferences.push(name);
  12018. }
  12019. else {
  12020. var error = new TemplateParseError("Reference \"#" + name + "\" is defined several times", reference.sourceSpan, exports.ParseErrorLevel.ERROR);
  12021. errors.push(error);
  12022. }
  12023. }); });
  12024. };
  12025. return TemplateParser;
  12026. }());
  12027. var TemplateParseVisitor = /** @class */ (function () {
  12028. function TemplateParseVisitor(reflector, config, providerViewContext, directives, _bindingParser, _schemaRegistry, _schemas, _targetErrors) {
  12029. var _this = this;
  12030. this.reflector = reflector;
  12031. this.config = config;
  12032. this.providerViewContext = providerViewContext;
  12033. this._bindingParser = _bindingParser;
  12034. this._schemaRegistry = _schemaRegistry;
  12035. this._schemas = _schemas;
  12036. this._targetErrors = _targetErrors;
  12037. this.selectorMatcher = new SelectorMatcher();
  12038. this.directivesIndex = new Map();
  12039. this.ngContentCount = 0;
  12040. // Note: queries start with id 1 so we can use the number in a Bloom filter!
  12041. this.contentQueryStartId = providerViewContext.component.viewQueries.length + 1;
  12042. directives.forEach(function (directive, index) {
  12043. var selector = CssSelector.parse(directive.selector);
  12044. _this.selectorMatcher.addSelectables(selector, directive);
  12045. _this.directivesIndex.set(directive, index);
  12046. });
  12047. }
  12048. TemplateParseVisitor.prototype.visitExpansion = function (expansion, context) { return null; };
  12049. TemplateParseVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return null; };
  12050. TemplateParseVisitor.prototype.visitText = function (text, parent) {
  12051. var ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR());
  12052. var valueNoNgsp = replaceNgsp(text.value);
  12053. var expr = this._bindingParser.parseInterpolation(valueNoNgsp, text.sourceSpan);
  12054. return expr ? new BoundTextAst(expr, ngContentIndex, text.sourceSpan) :
  12055. new TextAst(valueNoNgsp, ngContentIndex, text.sourceSpan);
  12056. };
  12057. TemplateParseVisitor.prototype.visitAttribute = function (attribute, context) {
  12058. return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
  12059. };
  12060. TemplateParseVisitor.prototype.visitComment = function (comment, context) { return null; };
  12061. TemplateParseVisitor.prototype.visitElement = function (element, parent) {
  12062. var _this = this;
  12063. var queryStartIndex = this.contentQueryStartId;
  12064. var elName = element.name;
  12065. var preparsedElement = preparseElement(element);
  12066. if (preparsedElement.type === PreparsedElementType.SCRIPT ||
  12067. preparsedElement.type === PreparsedElementType.STYLE) {
  12068. // Skipping <script> for security reasons
  12069. // Skipping <style> as we already processed them
  12070. // in the StyleCompiler
  12071. return null;
  12072. }
  12073. if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
  12074. isStyleUrlResolvable(preparsedElement.hrefAttr)) {
  12075. // Skipping stylesheets with either relative urls or package scheme as we already processed
  12076. // them in the StyleCompiler
  12077. return null;
  12078. }
  12079. var matchableAttrs = [];
  12080. var elementOrDirectiveProps = [];
  12081. var elementOrDirectiveRefs = [];
  12082. var elementVars = [];
  12083. var events = [];
  12084. var templateElementOrDirectiveProps = [];
  12085. var templateMatchableAttrs = [];
  12086. var templateElementVars = [];
  12087. var hasInlineTemplates = false;
  12088. var attrs = [];
  12089. var isTemplateElement = isNgTemplate(element.name);
  12090. element.attrs.forEach(function (attr) {
  12091. var parsedVariables = [];
  12092. var hasBinding = _this._parseAttr(isTemplateElement, attr, matchableAttrs, elementOrDirectiveProps, events, elementOrDirectiveRefs, elementVars);
  12093. elementVars.push.apply(elementVars, __spread(parsedVariables.map(function (v) { return VariableAst.fromParsedVariable(v); })));
  12094. var templateValue;
  12095. var templateKey;
  12096. var normalizedName = _this._normalizeAttributeName(attr.name);
  12097. if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX)) {
  12098. templateValue = attr.value;
  12099. templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX.length);
  12100. }
  12101. var hasTemplateBinding = templateValue != null;
  12102. if (hasTemplateBinding) {
  12103. if (hasInlineTemplates) {
  12104. _this._reportError("Can't have multiple template bindings on one element. Use only one attribute prefixed with *", attr.sourceSpan);
  12105. }
  12106. hasInlineTemplates = true;
  12107. var parsedVariables_1 = [];
  12108. _this._bindingParser.parseInlineTemplateBinding(templateKey, templateValue, attr.sourceSpan, templateMatchableAttrs, templateElementOrDirectiveProps, parsedVariables_1);
  12109. templateElementVars.push.apply(templateElementVars, __spread(parsedVariables_1.map(function (v) { return VariableAst.fromParsedVariable(v); })));
  12110. }
  12111. if (!hasBinding && !hasTemplateBinding) {
  12112. // don't include the bindings as attributes as well in the AST
  12113. attrs.push(_this.visitAttribute(attr, null));
  12114. matchableAttrs.push([attr.name, attr.value]);
  12115. }
  12116. });
  12117. var elementCssSelector = createElementCssSelector(elName, matchableAttrs);
  12118. var _a = this._parseDirectives(this.selectorMatcher, elementCssSelector), directiveMetas = _a.directives, matchElement = _a.matchElement;
  12119. var references = [];
  12120. var boundDirectivePropNames = new Set();
  12121. var directiveAsts = this._createDirectiveAsts(isTemplateElement, element.name, directiveMetas, elementOrDirectiveProps, elementOrDirectiveRefs, element.sourceSpan, references, boundDirectivePropNames);
  12122. var elementProps = this._createElementPropertyAsts(element.name, elementOrDirectiveProps, boundDirectivePropNames);
  12123. var isViewRoot = parent.isTemplateElement || hasInlineTemplates;
  12124. var providerContext = new ProviderElementContext(this.providerViewContext, parent.providerContext, isViewRoot, directiveAsts, attrs, references, isTemplateElement, queryStartIndex, element.sourceSpan);
  12125. var children = visitAll$1(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children, ElementContext.create(isTemplateElement, directiveAsts, isTemplateElement ? parent.providerContext : providerContext));
  12126. providerContext.afterElement();
  12127. // Override the actual selector when the `ngProjectAs` attribute is provided
  12128. var projectionSelector = preparsedElement.projectAs != '' ?
  12129. CssSelector.parse(preparsedElement.projectAs)[0] :
  12130. elementCssSelector;
  12131. var ngContentIndex = parent.findNgContentIndex(projectionSelector);
  12132. var parsedElement;
  12133. if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
  12134. // `<ng-content>` element
  12135. if (element.children && !element.children.every(_isEmptyTextNode)) {
  12136. this._reportError("<ng-content> element cannot have content.", element.sourceSpan);
  12137. }
  12138. parsedElement = new NgContentAst(this.ngContentCount++, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan);
  12139. }
  12140. else if (isTemplateElement) {
  12141. // `<ng-template>` element
  12142. this._assertAllEventsPublishedByDirectives(directiveAsts, events);
  12143. this._assertNoComponentsNorElementBindingsOnTemplate(directiveAsts, elementProps, element.sourceSpan);
  12144. parsedElement = new EmbeddedTemplateAst(attrs, events, references, elementVars, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, providerContext.queryMatches, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan);
  12145. }
  12146. else {
  12147. // element other than `<ng-content>` and `<ng-template>`
  12148. this._assertElementExists(matchElement, element);
  12149. this._assertOnlyOneComponent(directiveAsts, element.sourceSpan);
  12150. var ngContentIndex_1 = hasInlineTemplates ? null : parent.findNgContentIndex(projectionSelector);
  12151. 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);
  12152. }
  12153. if (hasInlineTemplates) {
  12154. // The element as a *-attribute
  12155. var templateQueryStartIndex = this.contentQueryStartId;
  12156. var templateSelector = createElementCssSelector('ng-template', templateMatchableAttrs);
  12157. var directives = this._parseDirectives(this.selectorMatcher, templateSelector).directives;
  12158. var templateBoundDirectivePropNames = new Set();
  12159. var templateDirectiveAsts = this._createDirectiveAsts(true, elName, directives, templateElementOrDirectiveProps, [], element.sourceSpan, [], templateBoundDirectivePropNames);
  12160. var templateElementProps = this._createElementPropertyAsts(elName, templateElementOrDirectiveProps, templateBoundDirectivePropNames);
  12161. this._assertNoComponentsNorElementBindingsOnTemplate(templateDirectiveAsts, templateElementProps, element.sourceSpan);
  12162. var templateProviderContext = new ProviderElementContext(this.providerViewContext, parent.providerContext, parent.isTemplateElement, templateDirectiveAsts, [], [], true, templateQueryStartIndex, element.sourceSpan);
  12163. templateProviderContext.afterElement();
  12164. parsedElement = new EmbeddedTemplateAst([], [], [], templateElementVars, templateProviderContext.transformedDirectiveAsts, templateProviderContext.transformProviders, templateProviderContext.transformedHasViewContainer, templateProviderContext.queryMatches, [parsedElement], ngContentIndex, element.sourceSpan);
  12165. }
  12166. return parsedElement;
  12167. };
  12168. TemplateParseVisitor.prototype._parseAttr = function (isTemplateElement, attr, targetMatchableAttrs, targetProps, targetEvents, targetRefs, targetVars) {
  12169. var name = this._normalizeAttributeName(attr.name);
  12170. var value = attr.value;
  12171. var srcSpan = attr.sourceSpan;
  12172. var boundEvents = [];
  12173. var bindParts = name.match(BIND_NAME_REGEXP);
  12174. var hasBinding = false;
  12175. if (bindParts !== null) {
  12176. hasBinding = true;
  12177. if (bindParts[KW_BIND_IDX] != null) {
  12178. this._bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
  12179. }
  12180. else if (bindParts[KW_LET_IDX]) {
  12181. if (isTemplateElement) {
  12182. var identifier = bindParts[IDENT_KW_IDX];
  12183. this._parseVariable(identifier, value, srcSpan, targetVars);
  12184. }
  12185. else {
  12186. this._reportError("\"let-\" is only supported on ng-template elements.", srcSpan);
  12187. }
  12188. }
  12189. else if (bindParts[KW_REF_IDX]) {
  12190. var identifier = bindParts[IDENT_KW_IDX];
  12191. this._parseReference(identifier, value, srcSpan, targetRefs);
  12192. }
  12193. else if (bindParts[KW_ON_IDX]) {
  12194. this._bindingParser.parseEvent(bindParts[IDENT_KW_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  12195. }
  12196. else if (bindParts[KW_BINDON_IDX]) {
  12197. this._bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
  12198. this._parseAssignmentEvent(bindParts[IDENT_KW_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  12199. }
  12200. else if (bindParts[KW_AT_IDX]) {
  12201. this._bindingParser.parseLiteralAttr(name, value, srcSpan, targetMatchableAttrs, targetProps);
  12202. }
  12203. else if (bindParts[IDENT_BANANA_BOX_IDX]) {
  12204. this._bindingParser.parsePropertyBinding(bindParts[IDENT_BANANA_BOX_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
  12205. this._parseAssignmentEvent(bindParts[IDENT_BANANA_BOX_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  12206. }
  12207. else if (bindParts[IDENT_PROPERTY_IDX]) {
  12208. this._bindingParser.parsePropertyBinding(bindParts[IDENT_PROPERTY_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
  12209. }
  12210. else if (bindParts[IDENT_EVENT_IDX]) {
  12211. this._bindingParser.parseEvent(bindParts[IDENT_EVENT_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  12212. }
  12213. }
  12214. else {
  12215. hasBinding = this._bindingParser.parsePropertyInterpolation(name, value, srcSpan, targetMatchableAttrs, targetProps);
  12216. }
  12217. if (!hasBinding) {
  12218. this._bindingParser.parseLiteralAttr(name, value, srcSpan, targetMatchableAttrs, targetProps);
  12219. }
  12220. targetEvents.push.apply(targetEvents, __spread(boundEvents.map(function (e) { return BoundEventAst.fromParsedEvent(e); })));
  12221. return hasBinding;
  12222. };
  12223. TemplateParseVisitor.prototype._normalizeAttributeName = function (attrName) {
  12224. return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
  12225. };
  12226. TemplateParseVisitor.prototype._parseVariable = function (identifier, value, sourceSpan, targetVars) {
  12227. if (identifier.indexOf('-') > -1) {
  12228. this._reportError("\"-\" is not allowed in variable names", sourceSpan);
  12229. }
  12230. targetVars.push(new VariableAst(identifier, value, sourceSpan));
  12231. };
  12232. TemplateParseVisitor.prototype._parseReference = function (identifier, value, sourceSpan, targetRefs) {
  12233. if (identifier.indexOf('-') > -1) {
  12234. this._reportError("\"-\" is not allowed in reference names", sourceSpan);
  12235. }
  12236. targetRefs.push(new ElementOrDirectiveRef(identifier, value, sourceSpan));
  12237. };
  12238. TemplateParseVisitor.prototype._parseAssignmentEvent = function (name, expression, sourceSpan, valueSpan, targetMatchableAttrs, targetEvents) {
  12239. this._bindingParser.parseEvent(name + "Change", expression + "=$event", sourceSpan, valueSpan, targetMatchableAttrs, targetEvents);
  12240. };
  12241. TemplateParseVisitor.prototype._parseDirectives = function (selectorMatcher, elementCssSelector) {
  12242. var _this = this;
  12243. // Need to sort the directives so that we get consistent results throughout,
  12244. // as selectorMatcher uses Maps inside.
  12245. // Also deduplicate directives as they might match more than one time!
  12246. var directives = new Array(this.directivesIndex.size);
  12247. // Whether any directive selector matches on the element name
  12248. var matchElement = false;
  12249. selectorMatcher.match(elementCssSelector, function (selector, directive) {
  12250. directives[_this.directivesIndex.get(directive)] = directive;
  12251. matchElement = matchElement || selector.hasElementSelector();
  12252. });
  12253. return {
  12254. directives: directives.filter(function (dir) { return !!dir; }),
  12255. matchElement: matchElement,
  12256. };
  12257. };
  12258. TemplateParseVisitor.prototype._createDirectiveAsts = function (isTemplateElement, elementName, directives, props, elementOrDirectiveRefs, elementSourceSpan, targetReferences, targetBoundDirectivePropNames) {
  12259. var _this = this;
  12260. var matchedReferences = new Set();
  12261. var component = null;
  12262. var directiveAsts = directives.map(function (directive) {
  12263. var sourceSpan = new ParseSourceSpan(elementSourceSpan.start, elementSourceSpan.end, "Directive " + identifierName(directive.type));
  12264. if (directive.isComponent) {
  12265. component = directive;
  12266. }
  12267. var directiveProperties = [];
  12268. var boundProperties = _this._bindingParser.createDirectiveHostPropertyAsts(directive, elementName, sourceSpan);
  12269. var hostProperties = boundProperties.map(function (prop) { return BoundElementPropertyAst.fromBoundProperty(prop); });
  12270. // Note: We need to check the host properties here as well,
  12271. // as we don't know the element name in the DirectiveWrapperCompiler yet.
  12272. hostProperties = _this._checkPropertiesInSchema(elementName, hostProperties);
  12273. var parsedEvents = _this._bindingParser.createDirectiveHostEventAsts(directive, sourceSpan);
  12274. _this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties, targetBoundDirectivePropNames);
  12275. elementOrDirectiveRefs.forEach(function (elOrDirRef) {
  12276. if ((elOrDirRef.value.length === 0 && directive.isComponent) ||
  12277. (elOrDirRef.isReferenceToDirective(directive))) {
  12278. targetReferences.push(new ReferenceAst(elOrDirRef.name, createTokenForReference(directive.type.reference), elOrDirRef.value, elOrDirRef.sourceSpan));
  12279. matchedReferences.add(elOrDirRef.name);
  12280. }
  12281. });
  12282. var hostEvents = parsedEvents.map(function (e) { return BoundEventAst.fromParsedEvent(e); });
  12283. var contentQueryStartId = _this.contentQueryStartId;
  12284. _this.contentQueryStartId += directive.queries.length;
  12285. return new DirectiveAst(directive, directiveProperties, hostProperties, hostEvents, contentQueryStartId, sourceSpan);
  12286. });
  12287. elementOrDirectiveRefs.forEach(function (elOrDirRef) {
  12288. if (elOrDirRef.value.length > 0) {
  12289. if (!matchedReferences.has(elOrDirRef.name)) {
  12290. _this._reportError("There is no directive with \"exportAs\" set to \"" + elOrDirRef.value + "\"", elOrDirRef.sourceSpan);
  12291. }
  12292. }
  12293. else if (!component) {
  12294. var refToken = null;
  12295. if (isTemplateElement) {
  12296. refToken = createTokenForExternalReference(_this.reflector, Identifiers.TemplateRef);
  12297. }
  12298. targetReferences.push(new ReferenceAst(elOrDirRef.name, refToken, elOrDirRef.value, elOrDirRef.sourceSpan));
  12299. }
  12300. });
  12301. return directiveAsts;
  12302. };
  12303. TemplateParseVisitor.prototype._createDirectivePropertyAsts = function (directiveProperties, boundProps, targetBoundDirectiveProps, targetBoundDirectivePropNames) {
  12304. if (directiveProperties) {
  12305. var boundPropsByName_1 = new Map();
  12306. boundProps.forEach(function (boundProp) {
  12307. var prevValue = boundPropsByName_1.get(boundProp.name);
  12308. if (!prevValue || prevValue.isLiteral) {
  12309. // give [a]="b" a higher precedence than a="b" on the same element
  12310. boundPropsByName_1.set(boundProp.name, boundProp);
  12311. }
  12312. });
  12313. Object.keys(directiveProperties).forEach(function (dirProp) {
  12314. var elProp = directiveProperties[dirProp];
  12315. var boundProp = boundPropsByName_1.get(elProp);
  12316. // Bindings are optional, so this binding only needs to be set up if an expression is given.
  12317. if (boundProp) {
  12318. targetBoundDirectivePropNames.add(boundProp.name);
  12319. if (!isEmptyExpression(boundProp.expression)) {
  12320. targetBoundDirectiveProps.push(new BoundDirectivePropertyAst(dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan));
  12321. }
  12322. }
  12323. });
  12324. }
  12325. };
  12326. TemplateParseVisitor.prototype._createElementPropertyAsts = function (elementName, props, boundDirectivePropNames) {
  12327. var _this = this;
  12328. var boundElementProps = [];
  12329. props.forEach(function (prop) {
  12330. if (!prop.isLiteral && !boundDirectivePropNames.has(prop.name)) {
  12331. var boundProp = _this._bindingParser.createBoundElementProperty(elementName, prop);
  12332. boundElementProps.push(BoundElementPropertyAst.fromBoundProperty(boundProp));
  12333. }
  12334. });
  12335. return this._checkPropertiesInSchema(elementName, boundElementProps);
  12336. };
  12337. TemplateParseVisitor.prototype._findComponentDirectives = function (directives) {
  12338. return directives.filter(function (directive) { return directive.directive.isComponent; });
  12339. };
  12340. TemplateParseVisitor.prototype._findComponentDirectiveNames = function (directives) {
  12341. return this._findComponentDirectives(directives)
  12342. .map(function (directive) { return identifierName(directive.directive.type); });
  12343. };
  12344. TemplateParseVisitor.prototype._assertOnlyOneComponent = function (directives, sourceSpan) {
  12345. var componentTypeNames = this._findComponentDirectiveNames(directives);
  12346. if (componentTypeNames.length > 1) {
  12347. this._reportError("More than one component matched on this element.\n" +
  12348. "Make sure that only one component's selector can match a given element.\n" +
  12349. ("Conflicting components: " + componentTypeNames.join(',')), sourceSpan);
  12350. }
  12351. };
  12352. /**
  12353. * Make sure that non-angular tags conform to the schemas.
  12354. *
  12355. * Note: An element is considered an angular tag when at least one directive selector matches the
  12356. * tag name.
  12357. *
  12358. * @param matchElement Whether any directive has matched on the tag name
  12359. * @param element the html element
  12360. */
  12361. TemplateParseVisitor.prototype._assertElementExists = function (matchElement, element) {
  12362. var elName = element.name.replace(/^:xhtml:/, '');
  12363. if (!matchElement && !this._schemaRegistry.hasElement(elName, this._schemas)) {
  12364. var errorMsg = "'" + elName + "' is not a known element:\n";
  12365. errorMsg +=
  12366. "1. If '" + elName + "' is an Angular component, then verify that it is part of this module.\n";
  12367. if (elName.indexOf('-') > -1) {
  12368. errorMsg +=
  12369. "2. If '" + elName + "' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.";
  12370. }
  12371. else {
  12372. errorMsg +=
  12373. "2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
  12374. }
  12375. this._reportError(errorMsg, element.sourceSpan);
  12376. }
  12377. };
  12378. TemplateParseVisitor.prototype._assertNoComponentsNorElementBindingsOnTemplate = function (directives, elementProps, sourceSpan) {
  12379. var _this = this;
  12380. var componentTypeNames = this._findComponentDirectiveNames(directives);
  12381. if (componentTypeNames.length > 0) {
  12382. this._reportError("Components on an embedded template: " + componentTypeNames.join(','), sourceSpan);
  12383. }
  12384. elementProps.forEach(function (prop) {
  12385. _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);
  12386. });
  12387. };
  12388. TemplateParseVisitor.prototype._assertAllEventsPublishedByDirectives = function (directives, events) {
  12389. var _this = this;
  12390. var allDirectiveEvents = new Set();
  12391. directives.forEach(function (directive) {
  12392. Object.keys(directive.directive.outputs).forEach(function (k) {
  12393. var eventName = directive.directive.outputs[k];
  12394. allDirectiveEvents.add(eventName);
  12395. });
  12396. });
  12397. events.forEach(function (event) {
  12398. if (event.target != null || !allDirectiveEvents.has(event.name)) {
  12399. _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);
  12400. }
  12401. });
  12402. };
  12403. TemplateParseVisitor.prototype._checkPropertiesInSchema = function (elementName, boundProps) {
  12404. var _this = this;
  12405. // Note: We can't filter out empty expressions before this method,
  12406. // as we still want to validate them!
  12407. return boundProps.filter(function (boundProp) {
  12408. if (boundProp.type === 0 /* Property */ &&
  12409. !_this._schemaRegistry.hasProperty(elementName, boundProp.name, _this._schemas)) {
  12410. var errorMsg = "Can't bind to '" + boundProp.name + "' since it isn't a known property of '" + elementName + "'.";
  12411. if (elementName.startsWith('ng-')) {
  12412. errorMsg +=
  12413. "\n1. If '" + boundProp.name + "' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component." +
  12414. "\n2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
  12415. }
  12416. else if (elementName.indexOf('-') > -1) {
  12417. errorMsg +=
  12418. "\n1. If '" + elementName + "' is an Angular component and it has '" + boundProp.name + "' input, then verify that it is part of this module." +
  12419. ("\n2. If '" + elementName + "' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.") +
  12420. "\n3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
  12421. }
  12422. _this._reportError(errorMsg, boundProp.sourceSpan);
  12423. }
  12424. return !isEmptyExpression(boundProp.value);
  12425. });
  12426. };
  12427. TemplateParseVisitor.prototype._reportError = function (message, sourceSpan, level) {
  12428. if (level === void 0) { level = exports.ParseErrorLevel.ERROR; }
  12429. this._targetErrors.push(new ParseError(sourceSpan, message, level));
  12430. };
  12431. return TemplateParseVisitor;
  12432. }());
  12433. var NonBindableVisitor = /** @class */ (function () {
  12434. function NonBindableVisitor() {
  12435. }
  12436. NonBindableVisitor.prototype.visitElement = function (ast, parent) {
  12437. var preparsedElement = preparseElement(ast);
  12438. if (preparsedElement.type === PreparsedElementType.SCRIPT ||
  12439. preparsedElement.type === PreparsedElementType.STYLE ||
  12440. preparsedElement.type === PreparsedElementType.STYLESHEET) {
  12441. // Skipping <script> for security reasons
  12442. // Skipping <style> and stylesheets as we already processed them
  12443. // in the StyleCompiler
  12444. return null;
  12445. }
  12446. var attrNameAndValues = ast.attrs.map(function (attr) { return [attr.name, attr.value]; });
  12447. var selector = createElementCssSelector(ast.name, attrNameAndValues);
  12448. var ngContentIndex = parent.findNgContentIndex(selector);
  12449. var children = visitAll$1(this, ast.children, EMPTY_ELEMENT_CONTEXT);
  12450. return new ElementAst(ast.name, visitAll$1(this, ast.attrs), [], [], [], [], [], false, [], children, ngContentIndex, ast.sourceSpan, ast.endSourceSpan);
  12451. };
  12452. NonBindableVisitor.prototype.visitComment = function (comment, context) { return null; };
  12453. NonBindableVisitor.prototype.visitAttribute = function (attribute, context) {
  12454. return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
  12455. };
  12456. NonBindableVisitor.prototype.visitText = function (text, parent) {
  12457. var ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR());
  12458. return new TextAst(text.value, ngContentIndex, text.sourceSpan);
  12459. };
  12460. NonBindableVisitor.prototype.visitExpansion = function (expansion, context) { return expansion; };
  12461. NonBindableVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return expansionCase; };
  12462. return NonBindableVisitor;
  12463. }());
  12464. /**
  12465. * A reference to an element or directive in a template. E.g., the reference in this template:
  12466. *
  12467. * <div #myMenu="coolMenu">
  12468. *
  12469. * would be {name: 'myMenu', value: 'coolMenu', sourceSpan: ...}
  12470. */
  12471. var ElementOrDirectiveRef = /** @class */ (function () {
  12472. function ElementOrDirectiveRef(name, value, sourceSpan) {
  12473. this.name = name;
  12474. this.value = value;
  12475. this.sourceSpan = sourceSpan;
  12476. }
  12477. /** Gets whether this is a reference to the given directive. */
  12478. ElementOrDirectiveRef.prototype.isReferenceToDirective = function (directive) {
  12479. return splitExportAs(directive.exportAs).indexOf(this.value) !== -1;
  12480. };
  12481. return ElementOrDirectiveRef;
  12482. }());
  12483. /** Splits a raw, potentially comma-delimited `exportAs` value into an array of names. */
  12484. function splitExportAs(exportAs) {
  12485. return exportAs ? exportAs.split(',').map(function (e) { return e.trim(); }) : [];
  12486. }
  12487. function splitClasses(classAttrValue) {
  12488. return classAttrValue.trim().split(/\s+/g);
  12489. }
  12490. var ElementContext = /** @class */ (function () {
  12491. function ElementContext(isTemplateElement, _ngContentIndexMatcher, _wildcardNgContentIndex, providerContext) {
  12492. this.isTemplateElement = isTemplateElement;
  12493. this._ngContentIndexMatcher = _ngContentIndexMatcher;
  12494. this._wildcardNgContentIndex = _wildcardNgContentIndex;
  12495. this.providerContext = providerContext;
  12496. }
  12497. ElementContext.create = function (isTemplateElement, directives, providerContext) {
  12498. var matcher = new SelectorMatcher();
  12499. var wildcardNgContentIndex = null;
  12500. var component = directives.find(function (directive) { return directive.directive.isComponent; });
  12501. if (component) {
  12502. var ngContentSelectors = component.directive.template.ngContentSelectors;
  12503. for (var i = 0; i < ngContentSelectors.length; i++) {
  12504. var selector = ngContentSelectors[i];
  12505. if (selector === '*') {
  12506. wildcardNgContentIndex = i;
  12507. }
  12508. else {
  12509. matcher.addSelectables(CssSelector.parse(ngContentSelectors[i]), i);
  12510. }
  12511. }
  12512. }
  12513. return new ElementContext(isTemplateElement, matcher, wildcardNgContentIndex, providerContext);
  12514. };
  12515. ElementContext.prototype.findNgContentIndex = function (selector) {
  12516. var ngContentIndices = [];
  12517. this._ngContentIndexMatcher.match(selector, function (selector, ngContentIndex) { ngContentIndices.push(ngContentIndex); });
  12518. ngContentIndices.sort();
  12519. if (this._wildcardNgContentIndex != null) {
  12520. ngContentIndices.push(this._wildcardNgContentIndex);
  12521. }
  12522. return ngContentIndices.length > 0 ? ngContentIndices[0] : null;
  12523. };
  12524. return ElementContext;
  12525. }());
  12526. function createElementCssSelector(elementName, attributes) {
  12527. var cssSelector = new CssSelector();
  12528. var elNameNoNs = splitNsName(elementName)[1];
  12529. cssSelector.setElement(elNameNoNs);
  12530. for (var i = 0; i < attributes.length; i++) {
  12531. var attrName = attributes[i][0];
  12532. var attrNameNoNs = splitNsName(attrName)[1];
  12533. var attrValue = attributes[i][1];
  12534. cssSelector.addAttribute(attrNameNoNs, attrValue);
  12535. if (attrName.toLowerCase() == CLASS_ATTR) {
  12536. var classes = splitClasses(attrValue);
  12537. classes.forEach(function (className) { return cssSelector.addClassName(className); });
  12538. }
  12539. }
  12540. return cssSelector;
  12541. }
  12542. var EMPTY_ELEMENT_CONTEXT = new ElementContext(true, new SelectorMatcher(), null, null);
  12543. var NON_BINDABLE_VISITOR = new NonBindableVisitor();
  12544. function _isEmptyTextNode(node) {
  12545. return node instanceof Text$3 && node.value.trim().length == 0;
  12546. }
  12547. function removeSummaryDuplicates(items) {
  12548. var map = new Map();
  12549. items.forEach(function (item) {
  12550. if (!map.get(item.type.reference)) {
  12551. map.set(item.type.reference, item);
  12552. }
  12553. });
  12554. return Array.from(map.values());
  12555. }
  12556. function isEmptyExpression(ast) {
  12557. if (ast instanceof ASTWithSource) {
  12558. ast = ast.ast;
  12559. }
  12560. return ast instanceof EmptyExpr;
  12561. }
  12562. /**
  12563. * @license
  12564. * Copyright Google Inc. All Rights Reserved.
  12565. *
  12566. * Use of this source code is governed by an MIT-style license that can be
  12567. * found in the LICENSE file at https://angular.io/license
  12568. */
  12569. /**
  12570. * Parses string representation of a style and converts it into object literal.
  12571. *
  12572. * @param value string representation of style as used in the `style` attribute in HTML.
  12573. * Example: `color: red; height: auto`.
  12574. * @returns An array of style property name and value pairs, e.g. `['color', 'red', 'height',
  12575. * 'auto']`
  12576. */
  12577. function parse(value) {
  12578. // we use a string array here instead of a string map
  12579. // because a string-map is not guaranteed to retain the
  12580. // order of the entries whereas a string array can be
  12581. // construted in a [key, value, key, value] format.
  12582. var styles = [];
  12583. var i = 0;
  12584. var parenDepth = 0;
  12585. var quote = 0 /* QuoteNone */;
  12586. var valueStart = 0;
  12587. var propStart = 0;
  12588. var currentProp = null;
  12589. var valueHasQuotes = false;
  12590. while (i < value.length) {
  12591. var token = value.charCodeAt(i++);
  12592. switch (token) {
  12593. case 40 /* OpenParen */:
  12594. parenDepth++;
  12595. break;
  12596. case 41 /* CloseParen */:
  12597. parenDepth--;
  12598. break;
  12599. case 39 /* QuoteSingle */:
  12600. // valueStart needs to be there since prop values don't
  12601. // have quotes in CSS
  12602. valueHasQuotes = valueHasQuotes || valueStart > 0;
  12603. if (quote === 0 /* QuoteNone */) {
  12604. quote = 39 /* QuoteSingle */;
  12605. }
  12606. else if (quote === 39 /* QuoteSingle */ && value.charCodeAt(i - 1) !== 92 /* BackSlash */) {
  12607. quote = 0 /* QuoteNone */;
  12608. }
  12609. break;
  12610. case 34 /* QuoteDouble */:
  12611. // same logic as above
  12612. valueHasQuotes = valueHasQuotes || valueStart > 0;
  12613. if (quote === 0 /* QuoteNone */) {
  12614. quote = 34 /* QuoteDouble */;
  12615. }
  12616. else if (quote === 34 /* QuoteDouble */ && value.charCodeAt(i - 1) !== 92 /* BackSlash */) {
  12617. quote = 0 /* QuoteNone */;
  12618. }
  12619. break;
  12620. case 58 /* Colon */:
  12621. if (!currentProp && parenDepth === 0 && quote === 0 /* QuoteNone */) {
  12622. currentProp = hyphenate(value.substring(propStart, i - 1).trim());
  12623. valueStart = i;
  12624. }
  12625. break;
  12626. case 59 /* Semicolon */:
  12627. if (currentProp && valueStart > 0 && parenDepth === 0 && quote === 0 /* QuoteNone */) {
  12628. var styleVal = value.substring(valueStart, i - 1).trim();
  12629. styles.push(currentProp, valueHasQuotes ? stripUnnecessaryQuotes(styleVal) : styleVal);
  12630. propStart = i;
  12631. valueStart = 0;
  12632. currentProp = null;
  12633. valueHasQuotes = false;
  12634. }
  12635. break;
  12636. }
  12637. }
  12638. if (currentProp && valueStart) {
  12639. var styleVal = value.substr(valueStart).trim();
  12640. styles.push(currentProp, valueHasQuotes ? stripUnnecessaryQuotes(styleVal) : styleVal);
  12641. }
  12642. return styles;
  12643. }
  12644. function stripUnnecessaryQuotes(value) {
  12645. var qS = value.charCodeAt(0);
  12646. var qE = value.charCodeAt(value.length - 1);
  12647. if (qS == qE && (qS == 39 /* QuoteSingle */ || qS == 34 /* QuoteDouble */)) {
  12648. var tempValue = value.substring(1, value.length - 1);
  12649. // special case to avoid using a multi-quoted string that was just chomped
  12650. // (e.g. `font-family: "Verdana", "sans-serif"`)
  12651. if (tempValue.indexOf('\'') == -1 && tempValue.indexOf('"') == -1) {
  12652. value = tempValue;
  12653. }
  12654. }
  12655. return value;
  12656. }
  12657. function hyphenate(value) {
  12658. return value.replace(/[a-z][A-Z]/g, function (v) {
  12659. return v.charAt(0) + '-' + v.charAt(1);
  12660. }).toLowerCase();
  12661. }
  12662. /**
  12663. * @license
  12664. * Copyright Google Inc. All Rights Reserved.
  12665. *
  12666. * Use of this source code is governed by an MIT-style license that can be
  12667. * found in the LICENSE file at https://angular.io/license
  12668. */
  12669. var _stylingMode = 0;
  12670. function compilerIsNewStylingInUse() {
  12671. return _stylingMode > 0 /* UseOld */;
  12672. }
  12673. var IMPORTANT_FLAG = '!important';
  12674. /**
  12675. * Produces creation/update instructions for all styling bindings (class and style)
  12676. *
  12677. * It also produces the creation instruction to register all initial styling values
  12678. * (which are all the static class="..." and style="..." attribute values that exist
  12679. * on an element within a template).
  12680. *
  12681. * The builder class below handles producing instructions for the following cases:
  12682. *
  12683. * - Static style/class attributes (style="..." and class="...")
  12684. * - Dynamic style/class map bindings ([style]="map" and [class]="map|string")
  12685. * - Dynamic style/class property bindings ([style.prop]="exp" and [class.name]="exp")
  12686. *
  12687. * Due to the complex relationship of all of these cases, the instructions generated
  12688. * for these attributes/properties/bindings must be done so in the correct order. The
  12689. * order which these must be generated is as follows:
  12690. *
  12691. * if (createMode) {
  12692. * styling(...)
  12693. * }
  12694. * if (updateMode) {
  12695. * styleMap(...)
  12696. * classMap(...)
  12697. * styleProp(...)
  12698. * classProp(...)
  12699. * stylingApp(...)
  12700. * }
  12701. *
  12702. * The creation/update methods within the builder class produce these instructions.
  12703. */
  12704. var StylingBuilder = /** @class */ (function () {
  12705. function StylingBuilder(_elementIndexExpr, _directiveExpr) {
  12706. this._elementIndexExpr = _elementIndexExpr;
  12707. this._directiveExpr = _directiveExpr;
  12708. /** Whether or not there are any static styling values present */
  12709. this._hasInitialValues = false;
  12710. /**
  12711. * Whether or not there are any styling bindings present
  12712. * (i.e. `[style]`, `[class]`, `[style.prop]` or `[class.name]`)
  12713. */
  12714. this.hasBindings = false;
  12715. /** the input for [class] (if it exists) */
  12716. this._classMapInput = null;
  12717. /** the input for [style] (if it exists) */
  12718. this._styleMapInput = null;
  12719. /** an array of each [style.prop] input */
  12720. this._singleStyleInputs = null;
  12721. /** an array of each [class.name] input */
  12722. this._singleClassInputs = null;
  12723. this._lastStylingInput = null;
  12724. this._firstStylingInput = null;
  12725. // maps are used instead of hash maps because a Map will
  12726. // retain the ordering of the keys
  12727. /**
  12728. * Represents the location of each style binding in the template
  12729. * (e.g. `<div [style.width]="w" [style.height]="h">` implies
  12730. * that `width=0` and `height=1`)
  12731. */
  12732. this._stylesIndex = new Map();
  12733. /**
  12734. * Represents the location of each class binding in the template
  12735. * (e.g. `<div [class.big]="b" [class.hidden]="h">` implies
  12736. * that `big=0` and `hidden=1`)
  12737. */
  12738. this._classesIndex = new Map();
  12739. this._initialStyleValues = [];
  12740. this._initialClassValues = [];
  12741. // certain style properties ALWAYS need sanitization
  12742. // this is checked each time new styles are encountered
  12743. this._useDefaultSanitizer = false;
  12744. }
  12745. /**
  12746. * Registers a given input to the styling builder to be later used when producing AOT code.
  12747. *
  12748. * The code below will only accept the input if it is somehow tied to styling (whether it be
  12749. * style/class bindings or static style/class attributes).
  12750. */
  12751. StylingBuilder.prototype.registerBoundInput = function (input) {
  12752. // [attr.style] or [attr.class] are skipped in the code below,
  12753. // they should not be treated as styling-based bindings since
  12754. // they are intended to be written directly to the attr and
  12755. // will therefore skip all style/class resolution that is present
  12756. // with style="", [style]="" and [style.prop]="", class="",
  12757. // [class.prop]="". [class]="" assignments
  12758. var binding = null;
  12759. var name = input.name;
  12760. switch (input.type) {
  12761. case 0 /* Property */:
  12762. binding = this.registerInputBasedOnName(name, input.value, input.sourceSpan);
  12763. break;
  12764. case 3 /* Style */:
  12765. binding = this.registerStyleInput(name, false, input.value, input.sourceSpan, input.unit);
  12766. break;
  12767. case 2 /* Class */:
  12768. binding = this.registerClassInput(name, false, input.value, input.sourceSpan);
  12769. break;
  12770. }
  12771. return binding ? true : false;
  12772. };
  12773. StylingBuilder.prototype.registerInputBasedOnName = function (name, expression, sourceSpan) {
  12774. var binding = null;
  12775. var nameToMatch = name.substring(0, 5); // class | style
  12776. var isStyle = nameToMatch === 'style';
  12777. var isClass = isStyle ? false : (nameToMatch === 'class');
  12778. if (isStyle || isClass) {
  12779. var isMapBased = name.charAt(5) !== '.'; // style.prop or class.prop makes this a no
  12780. var property = name.substr(isMapBased ? 5 : 6); // the dot explains why there's a +1
  12781. if (isStyle) {
  12782. binding = this.registerStyleInput(property, isMapBased, expression, sourceSpan);
  12783. }
  12784. else {
  12785. binding = this.registerClassInput(property, isMapBased, expression, sourceSpan);
  12786. }
  12787. }
  12788. return binding;
  12789. };
  12790. StylingBuilder.prototype.registerStyleInput = function (name, isMapBased, value, sourceSpan, unit) {
  12791. if (isEmptyExpression(value)) {
  12792. return null;
  12793. }
  12794. var _a = parseProperty(name), property = _a.property, hasOverrideFlag = _a.hasOverrideFlag, bindingUnit = _a.unit;
  12795. var entry = {
  12796. name: property,
  12797. unit: unit || bindingUnit, value: value, sourceSpan: sourceSpan, hasOverrideFlag: hasOverrideFlag
  12798. };
  12799. if (isMapBased) {
  12800. this._useDefaultSanitizer = true;
  12801. this._styleMapInput = entry;
  12802. }
  12803. else {
  12804. (this._singleStyleInputs = this._singleStyleInputs || []).push(entry);
  12805. this._useDefaultSanitizer = this._useDefaultSanitizer || isStyleSanitizable(name);
  12806. registerIntoMap(this._stylesIndex, property);
  12807. }
  12808. this._lastStylingInput = entry;
  12809. this._firstStylingInput = this._firstStylingInput || entry;
  12810. this.hasBindings = true;
  12811. return entry;
  12812. };
  12813. StylingBuilder.prototype.registerClassInput = function (name, isMapBased, value, sourceSpan) {
  12814. if (isEmptyExpression(value)) {
  12815. return null;
  12816. }
  12817. var _a = parseProperty(name), property = _a.property, hasOverrideFlag = _a.hasOverrideFlag;
  12818. var entry = { name: property, value: value, sourceSpan: sourceSpan, hasOverrideFlag: hasOverrideFlag, unit: null };
  12819. if (isMapBased) {
  12820. this._classMapInput = entry;
  12821. }
  12822. else {
  12823. (this._singleClassInputs = this._singleClassInputs || []).push(entry);
  12824. registerIntoMap(this._classesIndex, property);
  12825. }
  12826. this._lastStylingInput = entry;
  12827. this._firstStylingInput = this._firstStylingInput || entry;
  12828. this.hasBindings = true;
  12829. return entry;
  12830. };
  12831. /**
  12832. * Registers the element's static style string value to the builder.
  12833. *
  12834. * @param value the style string (e.g. `width:100px; height:200px;`)
  12835. */
  12836. StylingBuilder.prototype.registerStyleAttr = function (value) {
  12837. this._initialStyleValues = parse(value);
  12838. this._hasInitialValues = true;
  12839. };
  12840. /**
  12841. * Registers the element's static class string value to the builder.
  12842. *
  12843. * @param value the className string (e.g. `disabled gold zoom`)
  12844. */
  12845. StylingBuilder.prototype.registerClassAttr = function (value) {
  12846. this._initialClassValues = value.trim().split(/\s+/g);
  12847. this._hasInitialValues = true;
  12848. };
  12849. /**
  12850. * Appends all styling-related expressions to the provided attrs array.
  12851. *
  12852. * @param attrs an existing array where each of the styling expressions
  12853. * will be inserted into.
  12854. */
  12855. StylingBuilder.prototype.populateInitialStylingAttrs = function (attrs) {
  12856. // [CLASS_MARKER, 'foo', 'bar', 'baz' ...]
  12857. if (this._initialClassValues.length) {
  12858. attrs.push(literal(1 /* Classes */));
  12859. for (var i = 0; i < this._initialClassValues.length; i++) {
  12860. attrs.push(literal(this._initialClassValues[i]));
  12861. }
  12862. }
  12863. // [STYLE_MARKER, 'width', '200px', 'height', '100px', ...]
  12864. if (this._initialStyleValues.length) {
  12865. attrs.push(literal(2 /* Styles */));
  12866. for (var i = 0; i < this._initialStyleValues.length; i += 2) {
  12867. attrs.push(literal(this._initialStyleValues[i]), literal(this._initialStyleValues[i + 1]));
  12868. }
  12869. }
  12870. };
  12871. /**
  12872. * Builds an instruction with all the expressions and parameters for `elementHostAttrs`.
  12873. *
  12874. * The instruction generation code below is used for producing the AOT statement code which is
  12875. * responsible for registering initial styles (within a directive hostBindings' creation block),
  12876. * as well as any of the provided attribute values, to the directive host element.
  12877. */
  12878. StylingBuilder.prototype.buildHostAttrsInstruction = function (sourceSpan, attrs, constantPool) {
  12879. var _this = this;
  12880. if (this._directiveExpr && (attrs.length || this._hasInitialValues)) {
  12881. return {
  12882. sourceSpan: sourceSpan,
  12883. reference: Identifiers$1.elementHostAttrs,
  12884. allocateBindingSlots: 0,
  12885. buildParams: function () {
  12886. // params => elementHostAttrs(attrs)
  12887. _this.populateInitialStylingAttrs(attrs);
  12888. var attrArray = !attrs.some(function (attr) { return attr instanceof WrappedNodeExpr; }) ?
  12889. getConstantLiteralFromArray(constantPool, attrs) :
  12890. literalArr(attrs);
  12891. return [attrArray];
  12892. }
  12893. };
  12894. }
  12895. return null;
  12896. };
  12897. /**
  12898. * Builds an instruction with all the expressions and parameters for `styling`.
  12899. *
  12900. * The instruction generation code below is used for producing the AOT statement code which is
  12901. * responsible for registering style/class bindings to an element.
  12902. */
  12903. StylingBuilder.prototype.buildStylingInstruction = function (sourceSpan, constantPool) {
  12904. var _this = this;
  12905. if (this.hasBindings) {
  12906. return {
  12907. sourceSpan: sourceSpan,
  12908. allocateBindingSlots: 0,
  12909. reference: Identifiers$1.styling,
  12910. buildParams: function () {
  12911. // a string array of every style-based binding
  12912. var styleBindingProps = _this._singleStyleInputs ? _this._singleStyleInputs.map(function (i) { return literal(i.name); }) : [];
  12913. // a string array of every class-based binding
  12914. var classBindingNames = _this._singleClassInputs ? _this._singleClassInputs.map(function (i) { return literal(i.name); }) : [];
  12915. // to salvage space in the AOT generated code, there is no point in passing
  12916. // in `null` into a param if any follow-up params are not used. Therefore,
  12917. // only when a trailing param is used then it will be filled with nulls in between
  12918. // (otherwise a shorter amount of params will be filled). The code below helps
  12919. // determine how many params are required in the expression code.
  12920. //
  12921. // min params => styling()
  12922. // max params => styling(classBindings, styleBindings, sanitizer)
  12923. //
  12924. var params = [];
  12925. var expectedNumberOfArgs = 0;
  12926. if (_this._useDefaultSanitizer) {
  12927. expectedNumberOfArgs = 3;
  12928. }
  12929. else if (styleBindingProps.length) {
  12930. expectedNumberOfArgs = 2;
  12931. }
  12932. else if (classBindingNames.length) {
  12933. expectedNumberOfArgs = 1;
  12934. }
  12935. addParam(params, classBindingNames.length > 0, getConstantLiteralFromArray(constantPool, classBindingNames), 1, expectedNumberOfArgs);
  12936. addParam(params, styleBindingProps.length > 0, getConstantLiteralFromArray(constantPool, styleBindingProps), 2, expectedNumberOfArgs);
  12937. addParam(params, _this._useDefaultSanitizer, importExpr(Identifiers$1.defaultStyleSanitizer), 3, expectedNumberOfArgs);
  12938. return params;
  12939. }
  12940. };
  12941. }
  12942. return null;
  12943. };
  12944. /**
  12945. * Builds an instruction with all the expressions and parameters for `classMap`.
  12946. *
  12947. * The instruction data will contain all expressions for `classMap` to function
  12948. * which includes the `[class]` expression params.
  12949. */
  12950. StylingBuilder.prototype.buildClassMapInstruction = function (valueConverter) {
  12951. if (this._classMapInput) {
  12952. return this._buildMapBasedInstruction(valueConverter, true, this._classMapInput);
  12953. }
  12954. return null;
  12955. };
  12956. /**
  12957. * Builds an instruction with all the expressions and parameters for `styleMap`.
  12958. *
  12959. * The instruction data will contain all expressions for `styleMap` to function
  12960. * which includes the `[style]` expression params.
  12961. */
  12962. StylingBuilder.prototype.buildStyleMapInstruction = function (valueConverter) {
  12963. if (this._styleMapInput) {
  12964. return this._buildMapBasedInstruction(valueConverter, false, this._styleMapInput);
  12965. }
  12966. return null;
  12967. };
  12968. StylingBuilder.prototype._buildMapBasedInstruction = function (valueConverter, isClassBased, stylingInput) {
  12969. var totalBindingSlotsRequired = 0;
  12970. if (compilerIsNewStylingInUse()) {
  12971. // the old implementation does not reserve slot values for
  12972. // binding entries. The new one does.
  12973. totalBindingSlotsRequired++;
  12974. }
  12975. // these values must be outside of the update block so that they can
  12976. // be evaluated (the AST visit call) during creation time so that any
  12977. // pipes can be picked up in time before the template is built
  12978. var mapValue = stylingInput.value.visit(valueConverter);
  12979. if (mapValue instanceof Interpolation) {
  12980. totalBindingSlotsRequired += mapValue.expressions.length;
  12981. }
  12982. var reference = isClassBased ? Identifiers$1.classMap : Identifiers$1.styleMap;
  12983. return {
  12984. sourceSpan: stylingInput.sourceSpan,
  12985. reference: reference,
  12986. allocateBindingSlots: totalBindingSlotsRequired,
  12987. buildParams: function (convertFn) { return [convertFn(mapValue)]; }
  12988. };
  12989. };
  12990. StylingBuilder.prototype._buildSingleInputs = function (reference, inputs, mapIndex, allowUnits, valueConverter) {
  12991. var totalBindingSlotsRequired = 0;
  12992. return inputs.map(function (input) {
  12993. var bindingIndex = mapIndex.get(input.name);
  12994. var value = input.value.visit(valueConverter);
  12995. totalBindingSlotsRequired += (value instanceof Interpolation) ? value.expressions.length : 0;
  12996. if (compilerIsNewStylingInUse()) {
  12997. // the old implementation does not reserve slot values for
  12998. // binding entries. The new one does.
  12999. totalBindingSlotsRequired++;
  13000. }
  13001. return {
  13002. sourceSpan: input.sourceSpan,
  13003. allocateBindingSlots: totalBindingSlotsRequired, reference: reference,
  13004. buildParams: function (convertFn) {
  13005. // min params => stylingProp(elmIndex, bindingIndex, value)
  13006. // max params => stylingProp(elmIndex, bindingIndex, value, overrideFlag)
  13007. var params = [];
  13008. params.push(literal(bindingIndex));
  13009. params.push(convertFn(value));
  13010. if (allowUnits) {
  13011. if (input.unit) {
  13012. params.push(literal(input.unit));
  13013. }
  13014. else if (input.hasOverrideFlag) {
  13015. params.push(NULL_EXPR);
  13016. }
  13017. }
  13018. if (input.hasOverrideFlag) {
  13019. params.push(literal(true));
  13020. }
  13021. return params;
  13022. }
  13023. };
  13024. });
  13025. };
  13026. StylingBuilder.prototype._buildClassInputs = function (valueConverter) {
  13027. if (this._singleClassInputs) {
  13028. return this._buildSingleInputs(Identifiers$1.classProp, this._singleClassInputs, this._classesIndex, false, valueConverter);
  13029. }
  13030. return [];
  13031. };
  13032. StylingBuilder.prototype._buildStyleInputs = function (valueConverter) {
  13033. if (this._singleStyleInputs) {
  13034. return this._buildSingleInputs(Identifiers$1.styleProp, this._singleStyleInputs, this._stylesIndex, true, valueConverter);
  13035. }
  13036. return [];
  13037. };
  13038. StylingBuilder.prototype._buildApplyFn = function () {
  13039. return {
  13040. sourceSpan: this._lastStylingInput ? this._lastStylingInput.sourceSpan : null,
  13041. reference: Identifiers$1.stylingApply,
  13042. allocateBindingSlots: 0,
  13043. buildParams: function () { return []; }
  13044. };
  13045. };
  13046. StylingBuilder.prototype._buildSanitizerFn = function () {
  13047. return {
  13048. sourceSpan: this._firstStylingInput ? this._firstStylingInput.sourceSpan : null,
  13049. reference: Identifiers$1.styleSanitizer,
  13050. allocateBindingSlots: 0,
  13051. buildParams: function () { return [importExpr(Identifiers$1.defaultStyleSanitizer)]; }
  13052. };
  13053. };
  13054. /**
  13055. * Constructs all instructions which contain the expressions that will be placed
  13056. * into the update block of a template function or a directive hostBindings function.
  13057. */
  13058. StylingBuilder.prototype.buildUpdateLevelInstructions = function (valueConverter) {
  13059. var instructions = [];
  13060. if (this.hasBindings) {
  13061. if (compilerIsNewStylingInUse() && this._useDefaultSanitizer) {
  13062. instructions.push(this._buildSanitizerFn());
  13063. }
  13064. var styleMapInstruction = this.buildStyleMapInstruction(valueConverter);
  13065. if (styleMapInstruction) {
  13066. instructions.push(styleMapInstruction);
  13067. }
  13068. var classMapInstruction = this.buildClassMapInstruction(valueConverter);
  13069. if (classMapInstruction) {
  13070. instructions.push(classMapInstruction);
  13071. }
  13072. instructions.push.apply(instructions, __spread(this._buildStyleInputs(valueConverter)));
  13073. instructions.push.apply(instructions, __spread(this._buildClassInputs(valueConverter)));
  13074. instructions.push(this._buildApplyFn());
  13075. }
  13076. return instructions;
  13077. };
  13078. return StylingBuilder;
  13079. }());
  13080. function registerIntoMap(map, key) {
  13081. if (!map.has(key)) {
  13082. map.set(key, map.size);
  13083. }
  13084. }
  13085. function isStyleSanitizable(prop) {
  13086. // Note that browsers support both the dash case and
  13087. // camel case property names when setting through JS.
  13088. return prop === 'background-image' || prop === 'backgroundImage' || prop === 'background' ||
  13089. prop === 'border-image' || prop === 'borderImage' || prop === 'filter' ||
  13090. prop === 'list-style' || prop === 'listStyle' || prop === 'list-style-image' ||
  13091. prop === 'listStyleImage' || prop === 'clip-path' || prop === 'clipPath';
  13092. }
  13093. /**
  13094. * Simple helper function to either provide the constant literal that will house the value
  13095. * here or a null value if the provided values are empty.
  13096. */
  13097. function getConstantLiteralFromArray(constantPool, values) {
  13098. return values.length ? constantPool.getConstLiteral(literalArr(values), true) : NULL_EXPR;
  13099. }
  13100. /**
  13101. * Simple helper function that adds a parameter or does nothing at all depending on the provided
  13102. * predicate and totalExpectedArgs values
  13103. */
  13104. function addParam(params, predicate, value, argNumber, totalExpectedArgs) {
  13105. if (predicate && value) {
  13106. params.push(value);
  13107. }
  13108. else if (argNumber < totalExpectedArgs) {
  13109. params.push(NULL_EXPR);
  13110. }
  13111. }
  13112. function parseProperty(name) {
  13113. var hasOverrideFlag = false;
  13114. var overrideIndex = name.indexOf(IMPORTANT_FLAG);
  13115. if (overrideIndex !== -1) {
  13116. name = overrideIndex > 0 ? name.substring(0, overrideIndex) : '';
  13117. hasOverrideFlag = true;
  13118. }
  13119. var unit = '';
  13120. var property = name;
  13121. var unitIndex = name.lastIndexOf('.');
  13122. if (unitIndex > 0) {
  13123. unit = name.substr(unitIndex + 1);
  13124. property = name.substring(0, unitIndex);
  13125. }
  13126. return { property: property, unit: unit, hasOverrideFlag: hasOverrideFlag };
  13127. }
  13128. /**
  13129. * @license
  13130. * Copyright Google Inc. All Rights Reserved.
  13131. *
  13132. * Use of this source code is governed by an MIT-style license that can be
  13133. * found in the LICENSE file at https://angular.io/license
  13134. */
  13135. (function (TokenType) {
  13136. TokenType[TokenType["Character"] = 0] = "Character";
  13137. TokenType[TokenType["Identifier"] = 1] = "Identifier";
  13138. TokenType[TokenType["Keyword"] = 2] = "Keyword";
  13139. TokenType[TokenType["String"] = 3] = "String";
  13140. TokenType[TokenType["Operator"] = 4] = "Operator";
  13141. TokenType[TokenType["Number"] = 5] = "Number";
  13142. TokenType[TokenType["Error"] = 6] = "Error";
  13143. })(exports.TokenType || (exports.TokenType = {}));
  13144. var KEYWORDS = ['var', 'let', 'as', 'null', 'undefined', 'true', 'false', 'if', 'else', 'this'];
  13145. var Lexer = /** @class */ (function () {
  13146. function Lexer() {
  13147. }
  13148. Lexer.prototype.tokenize = function (text) {
  13149. var scanner = new _Scanner(text);
  13150. var tokens = [];
  13151. var token = scanner.scanToken();
  13152. while (token != null) {
  13153. tokens.push(token);
  13154. token = scanner.scanToken();
  13155. }
  13156. return tokens;
  13157. };
  13158. return Lexer;
  13159. }());
  13160. var Token$1 = /** @class */ (function () {
  13161. function Token(index, type, numValue, strValue) {
  13162. this.index = index;
  13163. this.type = type;
  13164. this.numValue = numValue;
  13165. this.strValue = strValue;
  13166. }
  13167. Token.prototype.isCharacter = function (code) {
  13168. return this.type == exports.TokenType.Character && this.numValue == code;
  13169. };
  13170. Token.prototype.isNumber = function () { return this.type == exports.TokenType.Number; };
  13171. Token.prototype.isString = function () { return this.type == exports.TokenType.String; };
  13172. Token.prototype.isOperator = function (operator) {
  13173. return this.type == exports.TokenType.Operator && this.strValue == operator;
  13174. };
  13175. Token.prototype.isIdentifier = function () { return this.type == exports.TokenType.Identifier; };
  13176. Token.prototype.isKeyword = function () { return this.type == exports.TokenType.Keyword; };
  13177. Token.prototype.isKeywordLet = function () { return this.type == exports.TokenType.Keyword && this.strValue == 'let'; };
  13178. Token.prototype.isKeywordAs = function () { return this.type == exports.TokenType.Keyword && this.strValue == 'as'; };
  13179. Token.prototype.isKeywordNull = function () { return this.type == exports.TokenType.Keyword && this.strValue == 'null'; };
  13180. Token.prototype.isKeywordUndefined = function () {
  13181. return this.type == exports.TokenType.Keyword && this.strValue == 'undefined';
  13182. };
  13183. Token.prototype.isKeywordTrue = function () { return this.type == exports.TokenType.Keyword && this.strValue == 'true'; };
  13184. Token.prototype.isKeywordFalse = function () { return this.type == exports.TokenType.Keyword && this.strValue == 'false'; };
  13185. Token.prototype.isKeywordThis = function () { return this.type == exports.TokenType.Keyword && this.strValue == 'this'; };
  13186. Token.prototype.isError = function () { return this.type == exports.TokenType.Error; };
  13187. Token.prototype.toNumber = function () { return this.type == exports.TokenType.Number ? this.numValue : -1; };
  13188. Token.prototype.toString = function () {
  13189. switch (this.type) {
  13190. case exports.TokenType.Character:
  13191. case exports.TokenType.Identifier:
  13192. case exports.TokenType.Keyword:
  13193. case exports.TokenType.Operator:
  13194. case exports.TokenType.String:
  13195. case exports.TokenType.Error:
  13196. return this.strValue;
  13197. case exports.TokenType.Number:
  13198. return this.numValue.toString();
  13199. default:
  13200. return null;
  13201. }
  13202. };
  13203. return Token;
  13204. }());
  13205. function newCharacterToken(index, code) {
  13206. return new Token$1(index, exports.TokenType.Character, code, String.fromCharCode(code));
  13207. }
  13208. function newIdentifierToken(index, text) {
  13209. return new Token$1(index, exports.TokenType.Identifier, 0, text);
  13210. }
  13211. function newKeywordToken(index, text) {
  13212. return new Token$1(index, exports.TokenType.Keyword, 0, text);
  13213. }
  13214. function newOperatorToken(index, text) {
  13215. return new Token$1(index, exports.TokenType.Operator, 0, text);
  13216. }
  13217. function newStringToken(index, text) {
  13218. return new Token$1(index, exports.TokenType.String, 0, text);
  13219. }
  13220. function newNumberToken(index, n) {
  13221. return new Token$1(index, exports.TokenType.Number, n, '');
  13222. }
  13223. function newErrorToken(index, message) {
  13224. return new Token$1(index, exports.TokenType.Error, 0, message);
  13225. }
  13226. var EOF = new Token$1(-1, exports.TokenType.Character, 0, '');
  13227. var _Scanner = /** @class */ (function () {
  13228. function _Scanner(input) {
  13229. this.input = input;
  13230. this.peek = 0;
  13231. this.index = -1;
  13232. this.length = input.length;
  13233. this.advance();
  13234. }
  13235. _Scanner.prototype.advance = function () {
  13236. this.peek = ++this.index >= this.length ? $EOF : this.input.charCodeAt(this.index);
  13237. };
  13238. _Scanner.prototype.scanToken = function () {
  13239. var input = this.input, length = this.length;
  13240. var peek = this.peek, index = this.index;
  13241. // Skip whitespace.
  13242. while (peek <= $SPACE) {
  13243. if (++index >= length) {
  13244. peek = $EOF;
  13245. break;
  13246. }
  13247. else {
  13248. peek = input.charCodeAt(index);
  13249. }
  13250. }
  13251. this.peek = peek;
  13252. this.index = index;
  13253. if (index >= length) {
  13254. return null;
  13255. }
  13256. // Handle identifiers and numbers.
  13257. if (isIdentifierStart(peek))
  13258. return this.scanIdentifier();
  13259. if (isDigit(peek))
  13260. return this.scanNumber(index);
  13261. var start = index;
  13262. switch (peek) {
  13263. case $PERIOD:
  13264. this.advance();
  13265. return isDigit(this.peek) ? this.scanNumber(start) :
  13266. newCharacterToken(start, $PERIOD);
  13267. case $LPAREN:
  13268. case $RPAREN:
  13269. case $LBRACE:
  13270. case $RBRACE:
  13271. case $LBRACKET:
  13272. case $RBRACKET:
  13273. case $COMMA:
  13274. case $COLON:
  13275. case $SEMICOLON:
  13276. return this.scanCharacter(start, peek);
  13277. case $SQ:
  13278. case $DQ:
  13279. return this.scanString();
  13280. case $HASH:
  13281. case $PLUS:
  13282. case $MINUS:
  13283. case $STAR:
  13284. case $SLASH:
  13285. case $PERCENT:
  13286. case $CARET:
  13287. return this.scanOperator(start, String.fromCharCode(peek));
  13288. case $QUESTION:
  13289. return this.scanComplexOperator(start, '?', $PERIOD, '.');
  13290. case $LT:
  13291. case $GT:
  13292. return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, '=');
  13293. case $BANG:
  13294. case $EQ:
  13295. return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, '=', $EQ, '=');
  13296. case $AMPERSAND:
  13297. return this.scanComplexOperator(start, '&', $AMPERSAND, '&');
  13298. case $BAR:
  13299. return this.scanComplexOperator(start, '|', $BAR, '|');
  13300. case $NBSP:
  13301. while (isWhitespace(this.peek))
  13302. this.advance();
  13303. return this.scanToken();
  13304. }
  13305. this.advance();
  13306. return this.error("Unexpected character [" + String.fromCharCode(peek) + "]", 0);
  13307. };
  13308. _Scanner.prototype.scanCharacter = function (start, code) {
  13309. this.advance();
  13310. return newCharacterToken(start, code);
  13311. };
  13312. _Scanner.prototype.scanOperator = function (start, str) {
  13313. this.advance();
  13314. return newOperatorToken(start, str);
  13315. };
  13316. /**
  13317. * Tokenize a 2/3 char long operator
  13318. *
  13319. * @param start start index in the expression
  13320. * @param one first symbol (always part of the operator)
  13321. * @param twoCode code point for the second symbol
  13322. * @param two second symbol (part of the operator when the second code point matches)
  13323. * @param threeCode code point for the third symbol
  13324. * @param three third symbol (part of the operator when provided and matches source expression)
  13325. */
  13326. _Scanner.prototype.scanComplexOperator = function (start, one, twoCode, two, threeCode, three) {
  13327. this.advance();
  13328. var str = one;
  13329. if (this.peek == twoCode) {
  13330. this.advance();
  13331. str += two;
  13332. }
  13333. if (threeCode != null && this.peek == threeCode) {
  13334. this.advance();
  13335. str += three;
  13336. }
  13337. return newOperatorToken(start, str);
  13338. };
  13339. _Scanner.prototype.scanIdentifier = function () {
  13340. var start = this.index;
  13341. this.advance();
  13342. while (isIdentifierPart(this.peek))
  13343. this.advance();
  13344. var str = this.input.substring(start, this.index);
  13345. return KEYWORDS.indexOf(str) > -1 ? newKeywordToken(start, str) :
  13346. newIdentifierToken(start, str);
  13347. };
  13348. _Scanner.prototype.scanNumber = function (start) {
  13349. var simple = (this.index === start);
  13350. this.advance(); // Skip initial digit.
  13351. while (true) {
  13352. if (isDigit(this.peek)) ;
  13353. else if (this.peek == $PERIOD) {
  13354. simple = false;
  13355. }
  13356. else if (isExponentStart(this.peek)) {
  13357. this.advance();
  13358. if (isExponentSign(this.peek))
  13359. this.advance();
  13360. if (!isDigit(this.peek))
  13361. return this.error('Invalid exponent', -1);
  13362. simple = false;
  13363. }
  13364. else {
  13365. break;
  13366. }
  13367. this.advance();
  13368. }
  13369. var str = this.input.substring(start, this.index);
  13370. var value = simple ? parseIntAutoRadix(str) : parseFloat(str);
  13371. return newNumberToken(start, value);
  13372. };
  13373. _Scanner.prototype.scanString = function () {
  13374. var start = this.index;
  13375. var quote = this.peek;
  13376. this.advance(); // Skip initial quote.
  13377. var buffer = '';
  13378. var marker = this.index;
  13379. var input = this.input;
  13380. while (this.peek != quote) {
  13381. if (this.peek == $BACKSLASH) {
  13382. buffer += input.substring(marker, this.index);
  13383. this.advance();
  13384. var unescapedCode = void 0;
  13385. // Workaround for TS2.1-introduced type strictness
  13386. this.peek = this.peek;
  13387. if (this.peek == $u) {
  13388. // 4 character hex code for unicode character.
  13389. var hex = input.substring(this.index + 1, this.index + 5);
  13390. if (/^[0-9a-f]+$/i.test(hex)) {
  13391. unescapedCode = parseInt(hex, 16);
  13392. }
  13393. else {
  13394. return this.error("Invalid unicode escape [\\u" + hex + "]", 0);
  13395. }
  13396. for (var i = 0; i < 5; i++) {
  13397. this.advance();
  13398. }
  13399. }
  13400. else {
  13401. unescapedCode = unescape(this.peek);
  13402. this.advance();
  13403. }
  13404. buffer += String.fromCharCode(unescapedCode);
  13405. marker = this.index;
  13406. }
  13407. else if (this.peek == $EOF) {
  13408. return this.error('Unterminated quote', 0);
  13409. }
  13410. else {
  13411. this.advance();
  13412. }
  13413. }
  13414. var last = input.substring(marker, this.index);
  13415. this.advance(); // Skip terminating quote.
  13416. return newStringToken(start, buffer + last);
  13417. };
  13418. _Scanner.prototype.error = function (message, offset) {
  13419. var position = this.index + offset;
  13420. return newErrorToken(position, "Lexer Error: " + message + " at column " + position + " in expression [" + this.input + "]");
  13421. };
  13422. return _Scanner;
  13423. }());
  13424. function isIdentifierStart(code) {
  13425. return ($a <= code && code <= $z) || ($A <= code && code <= $Z) ||
  13426. (code == $_) || (code == $$);
  13427. }
  13428. function isIdentifier(input) {
  13429. if (input.length == 0)
  13430. return false;
  13431. var scanner = new _Scanner(input);
  13432. if (!isIdentifierStart(scanner.peek))
  13433. return false;
  13434. scanner.advance();
  13435. while (scanner.peek !== $EOF) {
  13436. if (!isIdentifierPart(scanner.peek))
  13437. return false;
  13438. scanner.advance();
  13439. }
  13440. return true;
  13441. }
  13442. function isIdentifierPart(code) {
  13443. return isAsciiLetter(code) || isDigit(code) || (code == $_) ||
  13444. (code == $$);
  13445. }
  13446. function isExponentStart(code) {
  13447. return code == $e || code == $E;
  13448. }
  13449. function isExponentSign(code) {
  13450. return code == $MINUS || code == $PLUS;
  13451. }
  13452. function isQuote(code) {
  13453. return code === $SQ || code === $DQ || code === $BT;
  13454. }
  13455. function unescape(code) {
  13456. switch (code) {
  13457. case $n:
  13458. return $LF;
  13459. case $f:
  13460. return $FF;
  13461. case $r:
  13462. return $CR;
  13463. case $t:
  13464. return $TAB;
  13465. case $v:
  13466. return $VTAB;
  13467. default:
  13468. return code;
  13469. }
  13470. }
  13471. function parseIntAutoRadix(text) {
  13472. var result = parseInt(text);
  13473. if (isNaN(result)) {
  13474. throw new Error('Invalid integer literal when parsing ' + text);
  13475. }
  13476. return result;
  13477. }
  13478. /**
  13479. * @license
  13480. * Copyright Google Inc. All Rights Reserved.
  13481. *
  13482. * Use of this source code is governed by an MIT-style license that can be
  13483. * found in the LICENSE file at https://angular.io/license
  13484. */
  13485. var SplitInterpolation = /** @class */ (function () {
  13486. function SplitInterpolation(strings, expressions, offsets) {
  13487. this.strings = strings;
  13488. this.expressions = expressions;
  13489. this.offsets = offsets;
  13490. }
  13491. return SplitInterpolation;
  13492. }());
  13493. var TemplateBindingParseResult = /** @class */ (function () {
  13494. function TemplateBindingParseResult(templateBindings, warnings, errors) {
  13495. this.templateBindings = templateBindings;
  13496. this.warnings = warnings;
  13497. this.errors = errors;
  13498. }
  13499. return TemplateBindingParseResult;
  13500. }());
  13501. function _createInterpolateRegExp(config) {
  13502. var pattern = escapeRegExp(config.start) + '([\\s\\S]*?)' + escapeRegExp(config.end);
  13503. return new RegExp(pattern, 'g');
  13504. }
  13505. var Parser$1 = /** @class */ (function () {
  13506. function Parser(_lexer) {
  13507. this._lexer = _lexer;
  13508. this.errors = [];
  13509. }
  13510. Parser.prototype.parseAction = function (input, location, interpolationConfig) {
  13511. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  13512. this._checkNoInterpolation(input, location, interpolationConfig);
  13513. var sourceToLex = this._stripComments(input);
  13514. var tokens = this._lexer.tokenize(this._stripComments(input));
  13515. var ast = new _ParseAST(input, location, tokens, sourceToLex.length, true, this.errors, input.length - sourceToLex.length)
  13516. .parseChain();
  13517. return new ASTWithSource(ast, input, location, this.errors);
  13518. };
  13519. Parser.prototype.parseBinding = function (input, location, interpolationConfig) {
  13520. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  13521. var ast = this._parseBindingAst(input, location, interpolationConfig);
  13522. return new ASTWithSource(ast, input, location, this.errors);
  13523. };
  13524. Parser.prototype.parseSimpleBinding = function (input, location, interpolationConfig) {
  13525. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  13526. var ast = this._parseBindingAst(input, location, interpolationConfig);
  13527. var errors = SimpleExpressionChecker.check(ast);
  13528. if (errors.length > 0) {
  13529. this._reportError("Host binding expression cannot contain " + errors.join(' '), input, location);
  13530. }
  13531. return new ASTWithSource(ast, input, location, this.errors);
  13532. };
  13533. Parser.prototype._reportError = function (message, input, errLocation, ctxLocation) {
  13534. this.errors.push(new ParserError(message, input, errLocation, ctxLocation));
  13535. };
  13536. Parser.prototype._parseBindingAst = function (input, location, interpolationConfig) {
  13537. // Quotes expressions use 3rd-party expression language. We don't want to use
  13538. // our lexer or parser for that, so we check for that ahead of time.
  13539. var quote = this._parseQuote(input, location);
  13540. if (quote != null) {
  13541. return quote;
  13542. }
  13543. this._checkNoInterpolation(input, location, interpolationConfig);
  13544. var sourceToLex = this._stripComments(input);
  13545. var tokens = this._lexer.tokenize(sourceToLex);
  13546. return new _ParseAST(input, location, tokens, sourceToLex.length, false, this.errors, input.length - sourceToLex.length)
  13547. .parseChain();
  13548. };
  13549. Parser.prototype._parseQuote = function (input, location) {
  13550. if (input == null)
  13551. return null;
  13552. var prefixSeparatorIndex = input.indexOf(':');
  13553. if (prefixSeparatorIndex == -1)
  13554. return null;
  13555. var prefix = input.substring(0, prefixSeparatorIndex).trim();
  13556. if (!isIdentifier(prefix))
  13557. return null;
  13558. var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);
  13559. return new Quote(new ParseSpan(0, input.length), prefix, uninterpretedExpression, location);
  13560. };
  13561. Parser.prototype.parseTemplateBindings = function (tplKey, tplValue, location) {
  13562. var tokens = this._lexer.tokenize(tplValue);
  13563. return new _ParseAST(tplValue, location, tokens, tplValue.length, false, this.errors, 0)
  13564. .parseTemplateBindings(tplKey);
  13565. };
  13566. Parser.prototype.parseInterpolation = function (input, location, interpolationConfig) {
  13567. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  13568. var split = this.splitInterpolation(input, location, interpolationConfig);
  13569. if (split == null)
  13570. return null;
  13571. var expressions = [];
  13572. for (var i = 0; i < split.expressions.length; ++i) {
  13573. var expressionText = split.expressions[i];
  13574. var sourceToLex = this._stripComments(expressionText);
  13575. var tokens = this._lexer.tokenize(sourceToLex);
  13576. var ast = new _ParseAST(input, location, tokens, sourceToLex.length, false, this.errors, split.offsets[i] + (expressionText.length - sourceToLex.length))
  13577. .parseChain();
  13578. expressions.push(ast);
  13579. }
  13580. return new ASTWithSource(new Interpolation(new ParseSpan(0, input == null ? 0 : input.length), split.strings, expressions), input, location, this.errors);
  13581. };
  13582. Parser.prototype.splitInterpolation = function (input, location, interpolationConfig) {
  13583. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  13584. var regexp = _createInterpolateRegExp(interpolationConfig);
  13585. var parts = input.split(regexp);
  13586. if (parts.length <= 1) {
  13587. return null;
  13588. }
  13589. var strings = [];
  13590. var expressions = [];
  13591. var offsets = [];
  13592. var offset = 0;
  13593. for (var i = 0; i < parts.length; i++) {
  13594. var part = parts[i];
  13595. if (i % 2 === 0) {
  13596. // fixed string
  13597. strings.push(part);
  13598. offset += part.length;
  13599. }
  13600. else if (part.trim().length > 0) {
  13601. offset += interpolationConfig.start.length;
  13602. expressions.push(part);
  13603. offsets.push(offset);
  13604. offset += part.length + interpolationConfig.end.length;
  13605. }
  13606. else {
  13607. this._reportError('Blank expressions are not allowed in interpolated strings', input, "at column " + this._findInterpolationErrorColumn(parts, i, interpolationConfig) + " in", location);
  13608. expressions.push('$implict');
  13609. offsets.push(offset);
  13610. }
  13611. }
  13612. return new SplitInterpolation(strings, expressions, offsets);
  13613. };
  13614. Parser.prototype.wrapLiteralPrimitive = function (input, location) {
  13615. return new ASTWithSource(new LiteralPrimitive(new ParseSpan(0, input == null ? 0 : input.length), input), input, location, this.errors);
  13616. };
  13617. Parser.prototype._stripComments = function (input) {
  13618. var i = this._commentStart(input);
  13619. return i != null ? input.substring(0, i).trim() : input;
  13620. };
  13621. Parser.prototype._commentStart = function (input) {
  13622. var outerQuote = null;
  13623. for (var i = 0; i < input.length - 1; i++) {
  13624. var char = input.charCodeAt(i);
  13625. var nextChar = input.charCodeAt(i + 1);
  13626. if (char === $SLASH && nextChar == $SLASH && outerQuote == null)
  13627. return i;
  13628. if (outerQuote === char) {
  13629. outerQuote = null;
  13630. }
  13631. else if (outerQuote == null && isQuote(char)) {
  13632. outerQuote = char;
  13633. }
  13634. }
  13635. return null;
  13636. };
  13637. Parser.prototype._checkNoInterpolation = function (input, location, interpolationConfig) {
  13638. var regexp = _createInterpolateRegExp(interpolationConfig);
  13639. var parts = input.split(regexp);
  13640. if (parts.length > 1) {
  13641. this._reportError("Got interpolation (" + interpolationConfig.start + interpolationConfig.end + ") where expression was expected", input, "at column " + this._findInterpolationErrorColumn(parts, 1, interpolationConfig) + " in", location);
  13642. }
  13643. };
  13644. Parser.prototype._findInterpolationErrorColumn = function (parts, partInErrIdx, interpolationConfig) {
  13645. var errLocation = '';
  13646. for (var j = 0; j < partInErrIdx; j++) {
  13647. errLocation += j % 2 === 0 ?
  13648. parts[j] :
  13649. "" + interpolationConfig.start + parts[j] + interpolationConfig.end;
  13650. }
  13651. return errLocation.length;
  13652. };
  13653. return Parser;
  13654. }());
  13655. var _ParseAST = /** @class */ (function () {
  13656. function _ParseAST(input, location, tokens, inputLength, parseAction, errors, offset) {
  13657. this.input = input;
  13658. this.location = location;
  13659. this.tokens = tokens;
  13660. this.inputLength = inputLength;
  13661. this.parseAction = parseAction;
  13662. this.errors = errors;
  13663. this.offset = offset;
  13664. this.rparensExpected = 0;
  13665. this.rbracketsExpected = 0;
  13666. this.rbracesExpected = 0;
  13667. this.index = 0;
  13668. }
  13669. _ParseAST.prototype.peek = function (offset) {
  13670. var i = this.index + offset;
  13671. return i < this.tokens.length ? this.tokens[i] : EOF;
  13672. };
  13673. Object.defineProperty(_ParseAST.prototype, "next", {
  13674. get: function () { return this.peek(0); },
  13675. enumerable: true,
  13676. configurable: true
  13677. });
  13678. Object.defineProperty(_ParseAST.prototype, "inputIndex", {
  13679. get: function () {
  13680. return (this.index < this.tokens.length) ? this.next.index + this.offset :
  13681. this.inputLength + this.offset;
  13682. },
  13683. enumerable: true,
  13684. configurable: true
  13685. });
  13686. _ParseAST.prototype.span = function (start) { return new ParseSpan(start, this.inputIndex); };
  13687. _ParseAST.prototype.advance = function () { this.index++; };
  13688. _ParseAST.prototype.optionalCharacter = function (code) {
  13689. if (this.next.isCharacter(code)) {
  13690. this.advance();
  13691. return true;
  13692. }
  13693. else {
  13694. return false;
  13695. }
  13696. };
  13697. _ParseAST.prototype.peekKeywordLet = function () { return this.next.isKeywordLet(); };
  13698. _ParseAST.prototype.peekKeywordAs = function () { return this.next.isKeywordAs(); };
  13699. _ParseAST.prototype.expectCharacter = function (code) {
  13700. if (this.optionalCharacter(code))
  13701. return;
  13702. this.error("Missing expected " + String.fromCharCode(code));
  13703. };
  13704. _ParseAST.prototype.optionalOperator = function (op) {
  13705. if (this.next.isOperator(op)) {
  13706. this.advance();
  13707. return true;
  13708. }
  13709. else {
  13710. return false;
  13711. }
  13712. };
  13713. _ParseAST.prototype.expectOperator = function (operator) {
  13714. if (this.optionalOperator(operator))
  13715. return;
  13716. this.error("Missing expected operator " + operator);
  13717. };
  13718. _ParseAST.prototype.expectIdentifierOrKeyword = function () {
  13719. var n = this.next;
  13720. if (!n.isIdentifier() && !n.isKeyword()) {
  13721. this.error("Unexpected token " + n + ", expected identifier or keyword");
  13722. return '';
  13723. }
  13724. this.advance();
  13725. return n.toString();
  13726. };
  13727. _ParseAST.prototype.expectIdentifierOrKeywordOrString = function () {
  13728. var n = this.next;
  13729. if (!n.isIdentifier() && !n.isKeyword() && !n.isString()) {
  13730. this.error("Unexpected token " + n + ", expected identifier, keyword, or string");
  13731. return '';
  13732. }
  13733. this.advance();
  13734. return n.toString();
  13735. };
  13736. _ParseAST.prototype.parseChain = function () {
  13737. var exprs = [];
  13738. var start = this.inputIndex;
  13739. while (this.index < this.tokens.length) {
  13740. var expr = this.parsePipe();
  13741. exprs.push(expr);
  13742. if (this.optionalCharacter($SEMICOLON)) {
  13743. if (!this.parseAction) {
  13744. this.error('Binding expression cannot contain chained expression');
  13745. }
  13746. while (this.optionalCharacter($SEMICOLON)) {
  13747. } // read all semicolons
  13748. }
  13749. else if (this.index < this.tokens.length) {
  13750. this.error("Unexpected token '" + this.next + "'");
  13751. }
  13752. }
  13753. if (exprs.length == 0)
  13754. return new EmptyExpr(this.span(start));
  13755. if (exprs.length == 1)
  13756. return exprs[0];
  13757. return new Chain(this.span(start), exprs);
  13758. };
  13759. _ParseAST.prototype.parsePipe = function () {
  13760. var result = this.parseExpression();
  13761. if (this.optionalOperator('|')) {
  13762. if (this.parseAction) {
  13763. this.error('Cannot have a pipe in an action expression');
  13764. }
  13765. do {
  13766. var name_1 = this.expectIdentifierOrKeyword();
  13767. var args = [];
  13768. while (this.optionalCharacter($COLON)) {
  13769. args.push(this.parseExpression());
  13770. }
  13771. result = new BindingPipe(this.span(result.span.start), result, name_1, args);
  13772. } while (this.optionalOperator('|'));
  13773. }
  13774. return result;
  13775. };
  13776. _ParseAST.prototype.parseExpression = function () { return this.parseConditional(); };
  13777. _ParseAST.prototype.parseConditional = function () {
  13778. var start = this.inputIndex;
  13779. var result = this.parseLogicalOr();
  13780. if (this.optionalOperator('?')) {
  13781. var yes = this.parsePipe();
  13782. var no = void 0;
  13783. if (!this.optionalCharacter($COLON)) {
  13784. var end = this.inputIndex;
  13785. var expression = this.input.substring(start, end);
  13786. this.error("Conditional expression " + expression + " requires all 3 expressions");
  13787. no = new EmptyExpr(this.span(start));
  13788. }
  13789. else {
  13790. no = this.parsePipe();
  13791. }
  13792. return new Conditional(this.span(start), result, yes, no);
  13793. }
  13794. else {
  13795. return result;
  13796. }
  13797. };
  13798. _ParseAST.prototype.parseLogicalOr = function () {
  13799. // '||'
  13800. var result = this.parseLogicalAnd();
  13801. while (this.optionalOperator('||')) {
  13802. var right = this.parseLogicalAnd();
  13803. result = new Binary(this.span(result.span.start), '||', result, right);
  13804. }
  13805. return result;
  13806. };
  13807. _ParseAST.prototype.parseLogicalAnd = function () {
  13808. // '&&'
  13809. var result = this.parseEquality();
  13810. while (this.optionalOperator('&&')) {
  13811. var right = this.parseEquality();
  13812. result = new Binary(this.span(result.span.start), '&&', result, right);
  13813. }
  13814. return result;
  13815. };
  13816. _ParseAST.prototype.parseEquality = function () {
  13817. // '==','!=','===','!=='
  13818. var result = this.parseRelational();
  13819. while (this.next.type == exports.TokenType.Operator) {
  13820. var operator = this.next.strValue;
  13821. switch (operator) {
  13822. case '==':
  13823. case '===':
  13824. case '!=':
  13825. case '!==':
  13826. this.advance();
  13827. var right = this.parseRelational();
  13828. result = new Binary(this.span(result.span.start), operator, result, right);
  13829. continue;
  13830. }
  13831. break;
  13832. }
  13833. return result;
  13834. };
  13835. _ParseAST.prototype.parseRelational = function () {
  13836. // '<', '>', '<=', '>='
  13837. var result = this.parseAdditive();
  13838. while (this.next.type == exports.TokenType.Operator) {
  13839. var operator = this.next.strValue;
  13840. switch (operator) {
  13841. case '<':
  13842. case '>':
  13843. case '<=':
  13844. case '>=':
  13845. this.advance();
  13846. var right = this.parseAdditive();
  13847. result = new Binary(this.span(result.span.start), operator, result, right);
  13848. continue;
  13849. }
  13850. break;
  13851. }
  13852. return result;
  13853. };
  13854. _ParseAST.prototype.parseAdditive = function () {
  13855. // '+', '-'
  13856. var result = this.parseMultiplicative();
  13857. while (this.next.type == exports.TokenType.Operator) {
  13858. var operator = this.next.strValue;
  13859. switch (operator) {
  13860. case '+':
  13861. case '-':
  13862. this.advance();
  13863. var right = this.parseMultiplicative();
  13864. result = new Binary(this.span(result.span.start), operator, result, right);
  13865. continue;
  13866. }
  13867. break;
  13868. }
  13869. return result;
  13870. };
  13871. _ParseAST.prototype.parseMultiplicative = function () {
  13872. // '*', '%', '/'
  13873. var result = this.parsePrefix();
  13874. while (this.next.type == exports.TokenType.Operator) {
  13875. var operator = this.next.strValue;
  13876. switch (operator) {
  13877. case '*':
  13878. case '%':
  13879. case '/':
  13880. this.advance();
  13881. var right = this.parsePrefix();
  13882. result = new Binary(this.span(result.span.start), operator, result, right);
  13883. continue;
  13884. }
  13885. break;
  13886. }
  13887. return result;
  13888. };
  13889. _ParseAST.prototype.parsePrefix = function () {
  13890. if (this.next.type == exports.TokenType.Operator) {
  13891. var start = this.inputIndex;
  13892. var operator = this.next.strValue;
  13893. var result = void 0;
  13894. switch (operator) {
  13895. case '+':
  13896. this.advance();
  13897. result = this.parsePrefix();
  13898. return new Binary(this.span(start), '-', result, new LiteralPrimitive(new ParseSpan(start, start), 0));
  13899. case '-':
  13900. this.advance();
  13901. result = this.parsePrefix();
  13902. return new Binary(this.span(start), operator, new LiteralPrimitive(new ParseSpan(start, start), 0), result);
  13903. case '!':
  13904. this.advance();
  13905. result = this.parsePrefix();
  13906. return new PrefixNot(this.span(start), result);
  13907. }
  13908. }
  13909. return this.parseCallChain();
  13910. };
  13911. _ParseAST.prototype.parseCallChain = function () {
  13912. var result = this.parsePrimary();
  13913. while (true) {
  13914. if (this.optionalCharacter($PERIOD)) {
  13915. result = this.parseAccessMemberOrMethodCall(result, false);
  13916. }
  13917. else if (this.optionalOperator('?.')) {
  13918. result = this.parseAccessMemberOrMethodCall(result, true);
  13919. }
  13920. else if (this.optionalCharacter($LBRACKET)) {
  13921. this.rbracketsExpected++;
  13922. var key = this.parsePipe();
  13923. this.rbracketsExpected--;
  13924. this.expectCharacter($RBRACKET);
  13925. if (this.optionalOperator('=')) {
  13926. var value = this.parseConditional();
  13927. result = new KeyedWrite(this.span(result.span.start), result, key, value);
  13928. }
  13929. else {
  13930. result = new KeyedRead(this.span(result.span.start), result, key);
  13931. }
  13932. }
  13933. else if (this.optionalCharacter($LPAREN)) {
  13934. this.rparensExpected++;
  13935. var args = this.parseCallArguments();
  13936. this.rparensExpected--;
  13937. this.expectCharacter($RPAREN);
  13938. result = new FunctionCall(this.span(result.span.start), result, args);
  13939. }
  13940. else if (this.optionalOperator('!')) {
  13941. result = new NonNullAssert(this.span(result.span.start), result);
  13942. }
  13943. else {
  13944. return result;
  13945. }
  13946. }
  13947. };
  13948. _ParseAST.prototype.parsePrimary = function () {
  13949. var start = this.inputIndex;
  13950. if (this.optionalCharacter($LPAREN)) {
  13951. this.rparensExpected++;
  13952. var result = this.parsePipe();
  13953. this.rparensExpected--;
  13954. this.expectCharacter($RPAREN);
  13955. return result;
  13956. }
  13957. else if (this.next.isKeywordNull()) {
  13958. this.advance();
  13959. return new LiteralPrimitive(this.span(start), null);
  13960. }
  13961. else if (this.next.isKeywordUndefined()) {
  13962. this.advance();
  13963. return new LiteralPrimitive(this.span(start), void 0);
  13964. }
  13965. else if (this.next.isKeywordTrue()) {
  13966. this.advance();
  13967. return new LiteralPrimitive(this.span(start), true);
  13968. }
  13969. else if (this.next.isKeywordFalse()) {
  13970. this.advance();
  13971. return new LiteralPrimitive(this.span(start), false);
  13972. }
  13973. else if (this.next.isKeywordThis()) {
  13974. this.advance();
  13975. return new ImplicitReceiver(this.span(start));
  13976. }
  13977. else if (this.optionalCharacter($LBRACKET)) {
  13978. this.rbracketsExpected++;
  13979. var elements = this.parseExpressionList($RBRACKET);
  13980. this.rbracketsExpected--;
  13981. this.expectCharacter($RBRACKET);
  13982. return new LiteralArray(this.span(start), elements);
  13983. }
  13984. else if (this.next.isCharacter($LBRACE)) {
  13985. return this.parseLiteralMap();
  13986. }
  13987. else if (this.next.isIdentifier()) {
  13988. return this.parseAccessMemberOrMethodCall(new ImplicitReceiver(this.span(start)), false);
  13989. }
  13990. else if (this.next.isNumber()) {
  13991. var value = this.next.toNumber();
  13992. this.advance();
  13993. return new LiteralPrimitive(this.span(start), value);
  13994. }
  13995. else if (this.next.isString()) {
  13996. var literalValue = this.next.toString();
  13997. this.advance();
  13998. return new LiteralPrimitive(this.span(start), literalValue);
  13999. }
  14000. else if (this.index >= this.tokens.length) {
  14001. this.error("Unexpected end of expression: " + this.input);
  14002. return new EmptyExpr(this.span(start));
  14003. }
  14004. else {
  14005. this.error("Unexpected token " + this.next);
  14006. return new EmptyExpr(this.span(start));
  14007. }
  14008. };
  14009. _ParseAST.prototype.parseExpressionList = function (terminator) {
  14010. var result = [];
  14011. if (!this.next.isCharacter(terminator)) {
  14012. do {
  14013. result.push(this.parsePipe());
  14014. } while (this.optionalCharacter($COMMA));
  14015. }
  14016. return result;
  14017. };
  14018. _ParseAST.prototype.parseLiteralMap = function () {
  14019. var keys = [];
  14020. var values = [];
  14021. var start = this.inputIndex;
  14022. this.expectCharacter($LBRACE);
  14023. if (!this.optionalCharacter($RBRACE)) {
  14024. this.rbracesExpected++;
  14025. do {
  14026. var quoted = this.next.isString();
  14027. var key = this.expectIdentifierOrKeywordOrString();
  14028. keys.push({ key: key, quoted: quoted });
  14029. this.expectCharacter($COLON);
  14030. values.push(this.parsePipe());
  14031. } while (this.optionalCharacter($COMMA));
  14032. this.rbracesExpected--;
  14033. this.expectCharacter($RBRACE);
  14034. }
  14035. return new LiteralMap(this.span(start), keys, values);
  14036. };
  14037. _ParseAST.prototype.parseAccessMemberOrMethodCall = function (receiver, isSafe) {
  14038. if (isSafe === void 0) { isSafe = false; }
  14039. var start = receiver.span.start;
  14040. var id = this.expectIdentifierOrKeyword();
  14041. if (this.optionalCharacter($LPAREN)) {
  14042. this.rparensExpected++;
  14043. var args = this.parseCallArguments();
  14044. this.expectCharacter($RPAREN);
  14045. this.rparensExpected--;
  14046. var span = this.span(start);
  14047. return isSafe ? new SafeMethodCall(span, receiver, id, args) :
  14048. new MethodCall(span, receiver, id, args);
  14049. }
  14050. else {
  14051. if (isSafe) {
  14052. if (this.optionalOperator('=')) {
  14053. this.error('The \'?.\' operator cannot be used in the assignment');
  14054. return new EmptyExpr(this.span(start));
  14055. }
  14056. else {
  14057. return new SafePropertyRead(this.span(start), receiver, id);
  14058. }
  14059. }
  14060. else {
  14061. if (this.optionalOperator('=')) {
  14062. if (!this.parseAction) {
  14063. this.error('Bindings cannot contain assignments');
  14064. return new EmptyExpr(this.span(start));
  14065. }
  14066. var value = this.parseConditional();
  14067. return new PropertyWrite(this.span(start), receiver, id, value);
  14068. }
  14069. else {
  14070. return new PropertyRead(this.span(start), receiver, id);
  14071. }
  14072. }
  14073. }
  14074. };
  14075. _ParseAST.prototype.parseCallArguments = function () {
  14076. if (this.next.isCharacter($RPAREN))
  14077. return [];
  14078. var positionals = [];
  14079. do {
  14080. positionals.push(this.parsePipe());
  14081. } while (this.optionalCharacter($COMMA));
  14082. return positionals;
  14083. };
  14084. /**
  14085. * An identifier, a keyword, a string with an optional `-` in between.
  14086. */
  14087. _ParseAST.prototype.expectTemplateBindingKey = function () {
  14088. var result = '';
  14089. var operatorFound = false;
  14090. do {
  14091. result += this.expectIdentifierOrKeywordOrString();
  14092. operatorFound = this.optionalOperator('-');
  14093. if (operatorFound) {
  14094. result += '-';
  14095. }
  14096. } while (operatorFound);
  14097. return result.toString();
  14098. };
  14099. // Parses the AST for `<some-tag *tplKey=AST>`
  14100. _ParseAST.prototype.parseTemplateBindings = function (tplKey) {
  14101. var firstBinding = true;
  14102. var bindings = [];
  14103. var warnings = [];
  14104. do {
  14105. var start = this.inputIndex;
  14106. var rawKey = void 0;
  14107. var key = void 0;
  14108. var isVar = false;
  14109. if (firstBinding) {
  14110. rawKey = key = tplKey;
  14111. firstBinding = false;
  14112. }
  14113. else {
  14114. isVar = this.peekKeywordLet();
  14115. if (isVar)
  14116. this.advance();
  14117. rawKey = this.expectTemplateBindingKey();
  14118. key = isVar ? rawKey : tplKey + rawKey[0].toUpperCase() + rawKey.substring(1);
  14119. this.optionalCharacter($COLON);
  14120. }
  14121. var name_2 = null;
  14122. var expression = null;
  14123. if (isVar) {
  14124. if (this.optionalOperator('=')) {
  14125. name_2 = this.expectTemplateBindingKey();
  14126. }
  14127. else {
  14128. name_2 = '\$implicit';
  14129. }
  14130. }
  14131. else if (this.peekKeywordAs()) {
  14132. this.advance(); // consume `as`
  14133. name_2 = rawKey;
  14134. key = this.expectTemplateBindingKey(); // read local var name
  14135. isVar = true;
  14136. }
  14137. else if (this.next !== EOF && !this.peekKeywordLet()) {
  14138. var start_1 = this.inputIndex;
  14139. var ast = this.parsePipe();
  14140. var source = this.input.substring(start_1 - this.offset, this.inputIndex - this.offset);
  14141. expression = new ASTWithSource(ast, source, this.location, this.errors);
  14142. }
  14143. bindings.push(new TemplateBinding(this.span(start), key, isVar, name_2, expression));
  14144. if (this.peekKeywordAs() && !isVar) {
  14145. var letStart = this.inputIndex;
  14146. this.advance(); // consume `as`
  14147. var letName = this.expectTemplateBindingKey(); // read local var name
  14148. bindings.push(new TemplateBinding(this.span(letStart), letName, true, key, null));
  14149. }
  14150. if (!this.optionalCharacter($SEMICOLON)) {
  14151. this.optionalCharacter($COMMA);
  14152. }
  14153. } while (this.index < this.tokens.length);
  14154. return new TemplateBindingParseResult(bindings, warnings, this.errors);
  14155. };
  14156. _ParseAST.prototype.error = function (message, index) {
  14157. if (index === void 0) { index = null; }
  14158. this.errors.push(new ParserError(message, this.input, this.locationText(index), this.location));
  14159. this.skip();
  14160. };
  14161. _ParseAST.prototype.locationText = function (index) {
  14162. if (index === void 0) { index = null; }
  14163. if (index == null)
  14164. index = this.index;
  14165. return (index < this.tokens.length) ? "at column " + (this.tokens[index].index + 1) + " in" :
  14166. "at the end of the expression";
  14167. };
  14168. // Error recovery should skip tokens until it encounters a recovery point. skip() treats
  14169. // the end of input and a ';' as unconditionally a recovery point. It also treats ')',
  14170. // '}' and ']' as conditional recovery points if one of calling productions is expecting
  14171. // one of these symbols. This allows skip() to recover from errors such as '(a.) + 1' allowing
  14172. // more of the AST to be retained (it doesn't skip any tokens as the ')' is retained because
  14173. // of the '(' begins an '(' <expr> ')' production). The recovery points of grouping symbols
  14174. // must be conditional as they must be skipped if none of the calling productions are not
  14175. // expecting the closing token else we will never make progress in the case of an
  14176. // extraneous group closing symbol (such as a stray ')'). This is not the case for ';' because
  14177. // parseChain() is always the root production and it expects a ';'.
  14178. // If a production expects one of these token it increments the corresponding nesting count,
  14179. // and then decrements it just prior to checking if the token is in the input.
  14180. _ParseAST.prototype.skip = function () {
  14181. var n = this.next;
  14182. while (this.index < this.tokens.length && !n.isCharacter($SEMICOLON) &&
  14183. (this.rparensExpected <= 0 || !n.isCharacter($RPAREN)) &&
  14184. (this.rbracesExpected <= 0 || !n.isCharacter($RBRACE)) &&
  14185. (this.rbracketsExpected <= 0 || !n.isCharacter($RBRACKET))) {
  14186. if (this.next.isError()) {
  14187. this.errors.push(new ParserError(this.next.toString(), this.input, this.locationText(), this.location));
  14188. }
  14189. this.advance();
  14190. n = this.next;
  14191. }
  14192. };
  14193. return _ParseAST;
  14194. }());
  14195. var SimpleExpressionChecker = /** @class */ (function () {
  14196. function SimpleExpressionChecker() {
  14197. this.errors = [];
  14198. }
  14199. SimpleExpressionChecker.check = function (ast) {
  14200. var s = new SimpleExpressionChecker();
  14201. ast.visit(s);
  14202. return s.errors;
  14203. };
  14204. SimpleExpressionChecker.prototype.visitImplicitReceiver = function (ast, context) { };
  14205. SimpleExpressionChecker.prototype.visitInterpolation = function (ast, context) { };
  14206. SimpleExpressionChecker.prototype.visitLiteralPrimitive = function (ast, context) { };
  14207. SimpleExpressionChecker.prototype.visitPropertyRead = function (ast, context) { };
  14208. SimpleExpressionChecker.prototype.visitPropertyWrite = function (ast, context) { };
  14209. SimpleExpressionChecker.prototype.visitSafePropertyRead = function (ast, context) { };
  14210. SimpleExpressionChecker.prototype.visitMethodCall = function (ast, context) { };
  14211. SimpleExpressionChecker.prototype.visitSafeMethodCall = function (ast, context) { };
  14212. SimpleExpressionChecker.prototype.visitFunctionCall = function (ast, context) { };
  14213. SimpleExpressionChecker.prototype.visitLiteralArray = function (ast, context) { this.visitAll(ast.expressions); };
  14214. SimpleExpressionChecker.prototype.visitLiteralMap = function (ast, context) { this.visitAll(ast.values); };
  14215. SimpleExpressionChecker.prototype.visitBinary = function (ast, context) { };
  14216. SimpleExpressionChecker.prototype.visitPrefixNot = function (ast, context) { };
  14217. SimpleExpressionChecker.prototype.visitNonNullAssert = function (ast, context) { };
  14218. SimpleExpressionChecker.prototype.visitConditional = function (ast, context) { };
  14219. SimpleExpressionChecker.prototype.visitPipe = function (ast, context) { this.errors.push('pipes'); };
  14220. SimpleExpressionChecker.prototype.visitKeyedRead = function (ast, context) { };
  14221. SimpleExpressionChecker.prototype.visitKeyedWrite = function (ast, context) { };
  14222. SimpleExpressionChecker.prototype.visitAll = function (asts) {
  14223. var _this = this;
  14224. return asts.map(function (node) { return node.visit(_this); });
  14225. };
  14226. SimpleExpressionChecker.prototype.visitChain = function (ast, context) { };
  14227. SimpleExpressionChecker.prototype.visitQuote = function (ast, context) { };
  14228. return SimpleExpressionChecker;
  14229. }());
  14230. /**
  14231. * @license
  14232. * Copyright Google Inc. All Rights Reserved.
  14233. *
  14234. * Use of this source code is governed by an MIT-style license that can be
  14235. * found in the LICENSE file at https://angular.io/license
  14236. */
  14237. // =================================================================================================
  14238. // =================================================================================================
  14239. // =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P ===========
  14240. // =================================================================================================
  14241. // =================================================================================================
  14242. //
  14243. // DO NOT EDIT THIS LIST OF SECURITY SENSITIVE PROPERTIES WITHOUT A SECURITY REVIEW!
  14244. // Reach out to mprobst for details.
  14245. //
  14246. // =================================================================================================
  14247. /** Map from tagName|propertyName SecurityContext. Properties applying to all tags use '*'. */
  14248. var _SECURITY_SCHEMA;
  14249. function SECURITY_SCHEMA() {
  14250. if (!_SECURITY_SCHEMA) {
  14251. _SECURITY_SCHEMA = {};
  14252. // Case is insignificant below, all element and attribute names are lower-cased for lookup.
  14253. registerContext(SecurityContext.HTML, [
  14254. 'iframe|srcdoc',
  14255. '*|innerHTML',
  14256. '*|outerHTML',
  14257. ]);
  14258. registerContext(SecurityContext.STYLE, ['*|style']);
  14259. // NB: no SCRIPT contexts here, they are never allowed due to the parser stripping them.
  14260. registerContext(SecurityContext.URL, [
  14261. '*|formAction', 'area|href', 'area|ping', 'audio|src', 'a|href',
  14262. 'a|ping', 'blockquote|cite', 'body|background', 'del|cite', 'form|action',
  14263. 'img|src', 'img|srcset', 'input|src', 'ins|cite', 'q|cite',
  14264. 'source|src', 'source|srcset', 'track|src', 'video|poster', 'video|src',
  14265. ]);
  14266. registerContext(SecurityContext.RESOURCE_URL, [
  14267. 'applet|code',
  14268. 'applet|codebase',
  14269. 'base|href',
  14270. 'embed|src',
  14271. 'frame|src',
  14272. 'head|profile',
  14273. 'html|manifest',
  14274. 'iframe|src',
  14275. 'link|href',
  14276. 'media|src',
  14277. 'object|codebase',
  14278. 'object|data',
  14279. 'script|src',
  14280. ]);
  14281. }
  14282. return _SECURITY_SCHEMA;
  14283. }
  14284. function registerContext(ctx, specs) {
  14285. var e_1, _a;
  14286. try {
  14287. for (var specs_1 = __values(specs), specs_1_1 = specs_1.next(); !specs_1_1.done; specs_1_1 = specs_1.next()) {
  14288. var spec = specs_1_1.value;
  14289. _SECURITY_SCHEMA[spec.toLowerCase()] = ctx;
  14290. }
  14291. }
  14292. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  14293. finally {
  14294. try {
  14295. if (specs_1_1 && !specs_1_1.done && (_a = specs_1.return)) _a.call(specs_1);
  14296. }
  14297. finally { if (e_1) throw e_1.error; }
  14298. }
  14299. }
  14300. /**
  14301. * @license
  14302. * Copyright Google Inc. All Rights Reserved.
  14303. *
  14304. * Use of this source code is governed by an MIT-style license that can be
  14305. * found in the LICENSE file at https://angular.io/license
  14306. */
  14307. var ElementSchemaRegistry = /** @class */ (function () {
  14308. function ElementSchemaRegistry() {
  14309. }
  14310. return ElementSchemaRegistry;
  14311. }());
  14312. /**
  14313. * @license
  14314. * Copyright Google Inc. All Rights Reserved.
  14315. *
  14316. * Use of this source code is governed by an MIT-style license that can be
  14317. * found in the LICENSE file at https://angular.io/license
  14318. */
  14319. var BOOLEAN = 'boolean';
  14320. var NUMBER = 'number';
  14321. var STRING = 'string';
  14322. var OBJECT = 'object';
  14323. /**
  14324. * This array represents the DOM schema. It encodes inheritance, properties, and events.
  14325. *
  14326. * ## Overview
  14327. *
  14328. * Each line represents one kind of element. The `element_inheritance` and properties are joined
  14329. * using `element_inheritance|properties` syntax.
  14330. *
  14331. * ## Element Inheritance
  14332. *
  14333. * The `element_inheritance` can be further subdivided as `element1,element2,...^parentElement`.
  14334. * Here the individual elements are separated by `,` (commas). Every element in the list
  14335. * has identical properties.
  14336. *
  14337. * An `element` may inherit additional properties from `parentElement` If no `^parentElement` is
  14338. * specified then `""` (blank) element is assumed.
  14339. *
  14340. * NOTE: The blank element inherits from root `[Element]` element, the super element of all
  14341. * elements.
  14342. *
  14343. * NOTE an element prefix such as `:svg:` has no special meaning to the schema.
  14344. *
  14345. * ## Properties
  14346. *
  14347. * Each element has a set of properties separated by `,` (commas). Each property can be prefixed
  14348. * by a special character designating its type:
  14349. *
  14350. * - (no prefix): property is a string.
  14351. * - `*`: property represents an event.
  14352. * - `!`: property is a boolean.
  14353. * - `#`: property is a number.
  14354. * - `%`: property is an object.
  14355. *
  14356. * ## Query
  14357. *
  14358. * The class creates an internal squas representation which allows to easily answer the query of
  14359. * if a given property exist on a given element.
  14360. *
  14361. * NOTE: We don't yet support querying for types or events.
  14362. * NOTE: This schema is auto extracted from `schema_extractor.ts` located in the test folder,
  14363. * see dom_element_schema_registry_spec.ts
  14364. */
  14365. // =================================================================================================
  14366. // =================================================================================================
  14367. // =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P ===========
  14368. // =================================================================================================
  14369. // =================================================================================================
  14370. //
  14371. // DO NOT EDIT THIS DOM SCHEMA WITHOUT A SECURITY REVIEW!
  14372. //
  14373. // Newly added properties must be security reviewed and assigned an appropriate SecurityContext in
  14374. // dom_security_schema.ts. Reach out to mprobst & rjamet for details.
  14375. //
  14376. // =================================================================================================
  14377. var SCHEMA = [
  14378. '[Element]|textContent,%classList,className,id,innerHTML,*beforecopy,*beforecut,*beforepaste,*copy,*cut,*paste,*search,*selectstart,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerHTML,#scrollLeft,#scrollTop,slot' +
  14379. /* added manually to avoid breaking changes */
  14380. ',*message,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored',
  14381. '[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',
  14382. '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',
  14383. 'media^[HTMLElement]|!autoplay,!controls,%controlsList,%crossOrigin,#currentTime,!defaultMuted,#defaultPlaybackRate,!disableRemotePlayback,!loop,!muted,*encrypted,*waitingforkey,#playbackRate,preload,src,%srcObject,#volume',
  14384. ':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',
  14385. ':svg:graphics^:svg:|',
  14386. ':svg:animation^:svg:|*begin,*end,*repeat',
  14387. ':svg:geometry^:svg:|',
  14388. ':svg:componentTransferFunction^:svg:|',
  14389. ':svg:gradient^:svg:|',
  14390. ':svg:textContent^:svg:graphics|',
  14391. ':svg:textPositioning^:svg:textContent|',
  14392. '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',
  14393. 'area^[HTMLElement]|alt,coords,download,hash,host,hostname,href,!noHref,password,pathname,ping,port,protocol,referrerPolicy,rel,search,shape,target,username',
  14394. 'audio^media|',
  14395. 'br^[HTMLElement]|clear',
  14396. 'base^[HTMLElement]|href,target',
  14397. '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',
  14398. 'button^[HTMLElement]|!autofocus,!disabled,formAction,formEnctype,formMethod,!formNoValidate,formTarget,name,type,value',
  14399. 'canvas^[HTMLElement]|#height,#width',
  14400. 'content^[HTMLElement]|select',
  14401. 'dl^[HTMLElement]|!compact',
  14402. 'datalist^[HTMLElement]|',
  14403. 'details^[HTMLElement]|!open',
  14404. 'dialog^[HTMLElement]|!open,returnValue',
  14405. 'dir^[HTMLElement]|!compact',
  14406. 'div^[HTMLElement]|align',
  14407. 'embed^[HTMLElement]|align,height,name,src,type,width',
  14408. 'fieldset^[HTMLElement]|!disabled,name',
  14409. 'font^[HTMLElement]|color,face,size',
  14410. 'form^[HTMLElement]|acceptCharset,action,autocomplete,encoding,enctype,method,name,!noValidate,target',
  14411. 'frame^[HTMLElement]|frameBorder,longDesc,marginHeight,marginWidth,name,!noResize,scrolling,src',
  14412. 'frameset^[HTMLElement]|cols,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,rows',
  14413. 'hr^[HTMLElement]|align,color,!noShade,size,width',
  14414. 'head^[HTMLElement]|',
  14415. 'h1,h2,h3,h4,h5,h6^[HTMLElement]|align',
  14416. 'html^[HTMLElement]|version',
  14417. 'iframe^[HTMLElement]|align,!allowFullscreen,frameBorder,height,longDesc,marginHeight,marginWidth,name,referrerPolicy,%sandbox,scrolling,src,srcdoc,width',
  14418. 'img^[HTMLElement]|align,alt,border,%crossOrigin,#height,#hspace,!isMap,longDesc,lowsrc,name,referrerPolicy,sizes,src,srcset,useMap,#vspace,#width',
  14419. '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',
  14420. 'li^[HTMLElement]|type,#value',
  14421. 'label^[HTMLElement]|htmlFor',
  14422. 'legend^[HTMLElement]|align',
  14423. 'link^[HTMLElement]|as,charset,%crossOrigin,!disabled,href,hreflang,integrity,media,referrerPolicy,rel,%relList,rev,%sizes,target,type',
  14424. 'map^[HTMLElement]|name',
  14425. 'marquee^[HTMLElement]|behavior,bgColor,direction,height,#hspace,#loop,#scrollAmount,#scrollDelay,!trueSpeed,#vspace,width',
  14426. 'menu^[HTMLElement]|!compact',
  14427. 'meta^[HTMLElement]|content,httpEquiv,name,scheme',
  14428. 'meter^[HTMLElement]|#high,#low,#max,#min,#optimum,#value',
  14429. 'ins,del^[HTMLElement]|cite,dateTime',
  14430. 'ol^[HTMLElement]|!compact,!reversed,#start,type',
  14431. 'object^[HTMLElement]|align,archive,border,code,codeBase,codeType,data,!declare,height,#hspace,name,standby,type,useMap,#vspace,width',
  14432. 'optgroup^[HTMLElement]|!disabled,label',
  14433. 'option^[HTMLElement]|!defaultSelected,!disabled,label,!selected,text,value',
  14434. 'output^[HTMLElement]|defaultValue,%htmlFor,name,value',
  14435. 'p^[HTMLElement]|align',
  14436. 'param^[HTMLElement]|name,type,value,valueType',
  14437. 'picture^[HTMLElement]|',
  14438. 'pre^[HTMLElement]|#width',
  14439. 'progress^[HTMLElement]|#max,#value',
  14440. 'q,blockquote,cite^[HTMLElement]|',
  14441. 'script^[HTMLElement]|!async,charset,%crossOrigin,!defer,event,htmlFor,integrity,src,text,type',
  14442. 'select^[HTMLElement]|!autofocus,!disabled,#length,!multiple,name,!required,#selectedIndex,#size,value',
  14443. 'shadow^[HTMLElement]|',
  14444. 'slot^[HTMLElement]|name',
  14445. 'source^[HTMLElement]|media,sizes,src,srcset,type',
  14446. 'span^[HTMLElement]|',
  14447. 'style^[HTMLElement]|!disabled,media,type',
  14448. 'caption^[HTMLElement]|align',
  14449. 'th,td^[HTMLElement]|abbr,align,axis,bgColor,ch,chOff,#colSpan,headers,height,!noWrap,#rowSpan,scope,vAlign,width',
  14450. 'col,colgroup^[HTMLElement]|align,ch,chOff,#span,vAlign,width',
  14451. 'table^[HTMLElement]|align,bgColor,border,%caption,cellPadding,cellSpacing,frame,rules,summary,%tFoot,%tHead,width',
  14452. 'tr^[HTMLElement]|align,bgColor,ch,chOff,vAlign',
  14453. 'tfoot,thead,tbody^[HTMLElement]|align,ch,chOff,vAlign',
  14454. 'template^[HTMLElement]|',
  14455. 'textarea^[HTMLElement]|autocapitalize,!autofocus,#cols,defaultValue,dirName,!disabled,#maxLength,#minLength,name,placeholder,!readOnly,!required,#rows,selectionDirection,#selectionEnd,#selectionStart,value,wrap',
  14456. 'title^[HTMLElement]|text',
  14457. 'track^[HTMLElement]|!default,kind,label,src,srclang',
  14458. 'ul^[HTMLElement]|!compact,type',
  14459. 'unknown^[HTMLElement]|',
  14460. 'video^media|#height,poster,#width',
  14461. ':svg:a^:svg:graphics|',
  14462. ':svg:animate^:svg:animation|',
  14463. ':svg:animateMotion^:svg:animation|',
  14464. ':svg:animateTransform^:svg:animation|',
  14465. ':svg:circle^:svg:geometry|',
  14466. ':svg:clipPath^:svg:graphics|',
  14467. ':svg:defs^:svg:graphics|',
  14468. ':svg:desc^:svg:|',
  14469. ':svg:discard^:svg:|',
  14470. ':svg:ellipse^:svg:geometry|',
  14471. ':svg:feBlend^:svg:|',
  14472. ':svg:feColorMatrix^:svg:|',
  14473. ':svg:feComponentTransfer^:svg:|',
  14474. ':svg:feComposite^:svg:|',
  14475. ':svg:feConvolveMatrix^:svg:|',
  14476. ':svg:feDiffuseLighting^:svg:|',
  14477. ':svg:feDisplacementMap^:svg:|',
  14478. ':svg:feDistantLight^:svg:|',
  14479. ':svg:feDropShadow^:svg:|',
  14480. ':svg:feFlood^:svg:|',
  14481. ':svg:feFuncA^:svg:componentTransferFunction|',
  14482. ':svg:feFuncB^:svg:componentTransferFunction|',
  14483. ':svg:feFuncG^:svg:componentTransferFunction|',
  14484. ':svg:feFuncR^:svg:componentTransferFunction|',
  14485. ':svg:feGaussianBlur^:svg:|',
  14486. ':svg:feImage^:svg:|',
  14487. ':svg:feMerge^:svg:|',
  14488. ':svg:feMergeNode^:svg:|',
  14489. ':svg:feMorphology^:svg:|',
  14490. ':svg:feOffset^:svg:|',
  14491. ':svg:fePointLight^:svg:|',
  14492. ':svg:feSpecularLighting^:svg:|',
  14493. ':svg:feSpotLight^:svg:|',
  14494. ':svg:feTile^:svg:|',
  14495. ':svg:feTurbulence^:svg:|',
  14496. ':svg:filter^:svg:|',
  14497. ':svg:foreignObject^:svg:graphics|',
  14498. ':svg:g^:svg:graphics|',
  14499. ':svg:image^:svg:graphics|',
  14500. ':svg:line^:svg:geometry|',
  14501. ':svg:linearGradient^:svg:gradient|',
  14502. ':svg:mpath^:svg:|',
  14503. ':svg:marker^:svg:|',
  14504. ':svg:mask^:svg:|',
  14505. ':svg:metadata^:svg:|',
  14506. ':svg:path^:svg:geometry|',
  14507. ':svg:pattern^:svg:|',
  14508. ':svg:polygon^:svg:geometry|',
  14509. ':svg:polyline^:svg:geometry|',
  14510. ':svg:radialGradient^:svg:gradient|',
  14511. ':svg:rect^:svg:geometry|',
  14512. ':svg:svg^:svg:graphics|#currentScale,#zoomAndPan',
  14513. ':svg:script^:svg:|type',
  14514. ':svg:set^:svg:animation|',
  14515. ':svg:stop^:svg:|',
  14516. ':svg:style^:svg:|!disabled,media,title,type',
  14517. ':svg:switch^:svg:graphics|',
  14518. ':svg:symbol^:svg:|',
  14519. ':svg:tspan^:svg:textPositioning|',
  14520. ':svg:text^:svg:textPositioning|',
  14521. ':svg:textPath^:svg:textContent|',
  14522. ':svg:title^:svg:|',
  14523. ':svg:use^:svg:graphics|',
  14524. ':svg:view^:svg:|#zoomAndPan',
  14525. 'data^[HTMLElement]|value',
  14526. 'keygen^[HTMLElement]|!autofocus,challenge,!disabled,form,keytype,name',
  14527. 'menuitem^[HTMLElement]|type,label,icon,!disabled,!checked,radiogroup,!default',
  14528. 'summary^[HTMLElement]|',
  14529. 'time^[HTMLElement]|dateTime',
  14530. ':svg:cursor^:svg:|',
  14531. ];
  14532. var _ATTR_TO_PROP = {
  14533. 'class': 'className',
  14534. 'for': 'htmlFor',
  14535. 'formaction': 'formAction',
  14536. 'innerHtml': 'innerHTML',
  14537. 'readonly': 'readOnly',
  14538. 'tabindex': 'tabIndex',
  14539. };
  14540. var DomElementSchemaRegistry = /** @class */ (function (_super) {
  14541. __extends(DomElementSchemaRegistry, _super);
  14542. function DomElementSchemaRegistry() {
  14543. var _this = _super.call(this) || this;
  14544. _this._schema = {};
  14545. SCHEMA.forEach(function (encodedType) {
  14546. var type = {};
  14547. var _a = __read(encodedType.split('|'), 2), strType = _a[0], strProperties = _a[1];
  14548. var properties = strProperties.split(',');
  14549. var _b = __read(strType.split('^'), 2), typeNames = _b[0], superName = _b[1];
  14550. typeNames.split(',').forEach(function (tag) { return _this._schema[tag.toLowerCase()] = type; });
  14551. var superType = superName && _this._schema[superName.toLowerCase()];
  14552. if (superType) {
  14553. Object.keys(superType).forEach(function (prop) { type[prop] = superType[prop]; });
  14554. }
  14555. properties.forEach(function (property) {
  14556. if (property.length > 0) {
  14557. switch (property[0]) {
  14558. case '*':
  14559. // We don't yet support events.
  14560. // If ever allowing to bind to events, GO THROUGH A SECURITY REVIEW, allowing events
  14561. // will
  14562. // almost certainly introduce bad XSS vulnerabilities.
  14563. // type[property.substring(1)] = EVENT;
  14564. break;
  14565. case '!':
  14566. type[property.substring(1)] = BOOLEAN;
  14567. break;
  14568. case '#':
  14569. type[property.substring(1)] = NUMBER;
  14570. break;
  14571. case '%':
  14572. type[property.substring(1)] = OBJECT;
  14573. break;
  14574. default:
  14575. type[property] = STRING;
  14576. }
  14577. }
  14578. });
  14579. });
  14580. return _this;
  14581. }
  14582. DomElementSchemaRegistry.prototype.hasProperty = function (tagName, propName, schemaMetas) {
  14583. if (schemaMetas.some(function (schema) { return schema.name === NO_ERRORS_SCHEMA.name; })) {
  14584. return true;
  14585. }
  14586. if (tagName.indexOf('-') > -1) {
  14587. if (isNgContainer(tagName) || isNgContent(tagName)) {
  14588. return false;
  14589. }
  14590. if (schemaMetas.some(function (schema) { return schema.name === CUSTOM_ELEMENTS_SCHEMA.name; })) {
  14591. // Can't tell now as we don't know which properties a custom element will get
  14592. // once it is instantiated
  14593. return true;
  14594. }
  14595. }
  14596. var elementProperties = this._schema[tagName.toLowerCase()] || this._schema['unknown'];
  14597. return !!elementProperties[propName];
  14598. };
  14599. DomElementSchemaRegistry.prototype.hasElement = function (tagName, schemaMetas) {
  14600. if (schemaMetas.some(function (schema) { return schema.name === NO_ERRORS_SCHEMA.name; })) {
  14601. return true;
  14602. }
  14603. if (tagName.indexOf('-') > -1) {
  14604. if (isNgContainer(tagName) || isNgContent(tagName)) {
  14605. return true;
  14606. }
  14607. if (schemaMetas.some(function (schema) { return schema.name === CUSTOM_ELEMENTS_SCHEMA.name; })) {
  14608. // Allow any custom elements
  14609. return true;
  14610. }
  14611. }
  14612. return !!this._schema[tagName.toLowerCase()];
  14613. };
  14614. /**
  14615. * securityContext returns the security context for the given property on the given DOM tag.
  14616. *
  14617. * Tag and property name are statically known and cannot change at runtime, i.e. it is not
  14618. * possible to bind a value into a changing attribute or tag name.
  14619. *
  14620. * The filtering is based on a list of allowed tags|attributes. All attributes in the schema
  14621. * above are assumed to have the 'NONE' security context, i.e. that they are safe inert
  14622. * string values. Only specific well known attack vectors are assigned their appropriate context.
  14623. */
  14624. DomElementSchemaRegistry.prototype.securityContext = function (tagName, propName, isAttribute) {
  14625. if (isAttribute) {
  14626. // NB: For security purposes, use the mapped property name, not the attribute name.
  14627. propName = this.getMappedPropName(propName);
  14628. }
  14629. // Make sure comparisons are case insensitive, so that case differences between attribute and
  14630. // property names do not have a security impact.
  14631. tagName = tagName.toLowerCase();
  14632. propName = propName.toLowerCase();
  14633. var ctx = SECURITY_SCHEMA()[tagName + '|' + propName];
  14634. if (ctx) {
  14635. return ctx;
  14636. }
  14637. ctx = SECURITY_SCHEMA()['*|' + propName];
  14638. return ctx ? ctx : SecurityContext.NONE;
  14639. };
  14640. DomElementSchemaRegistry.prototype.getMappedPropName = function (propName) { return _ATTR_TO_PROP[propName] || propName; };
  14641. DomElementSchemaRegistry.prototype.getDefaultComponentElementName = function () { return 'ng-component'; };
  14642. DomElementSchemaRegistry.prototype.validateProperty = function (name) {
  14643. if (name.toLowerCase().startsWith('on')) {
  14644. var msg = "Binding to event property '" + name + "' is disallowed for security reasons, " +
  14645. ("please use (" + name.slice(2) + ")=...") +
  14646. ("\nIf '" + name + "' is a directive input, make sure the directive is imported by the") +
  14647. " current module.";
  14648. return { error: true, msg: msg };
  14649. }
  14650. else {
  14651. return { error: false };
  14652. }
  14653. };
  14654. DomElementSchemaRegistry.prototype.validateAttribute = function (name) {
  14655. if (name.toLowerCase().startsWith('on')) {
  14656. var msg = "Binding to event attribute '" + name + "' is disallowed for security reasons, " +
  14657. ("please use (" + name.slice(2) + ")=...");
  14658. return { error: true, msg: msg };
  14659. }
  14660. else {
  14661. return { error: false };
  14662. }
  14663. };
  14664. DomElementSchemaRegistry.prototype.allKnownElementNames = function () { return Object.keys(this._schema); };
  14665. DomElementSchemaRegistry.prototype.normalizeAnimationStyleProperty = function (propName) {
  14666. return dashCaseToCamelCase(propName);
  14667. };
  14668. DomElementSchemaRegistry.prototype.normalizeAnimationStyleValue = function (camelCaseProp, userProvidedProp, val) {
  14669. var unit = '';
  14670. var strVal = val.toString().trim();
  14671. var errorMsg = null;
  14672. if (_isPixelDimensionStyle(camelCaseProp) && val !== 0 && val !== '0') {
  14673. if (typeof val === 'number') {
  14674. unit = 'px';
  14675. }
  14676. else {
  14677. var valAndSuffixMatch = val.match(/^[+-]?[\d\.]+([a-z]*)$/);
  14678. if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {
  14679. errorMsg = "Please provide a CSS unit value for " + userProvidedProp + ":" + val;
  14680. }
  14681. }
  14682. }
  14683. return { error: errorMsg, value: strVal + unit };
  14684. };
  14685. return DomElementSchemaRegistry;
  14686. }(ElementSchemaRegistry));
  14687. function _isPixelDimensionStyle(prop) {
  14688. switch (prop) {
  14689. case 'width':
  14690. case 'height':
  14691. case 'minWidth':
  14692. case 'minHeight':
  14693. case 'maxWidth':
  14694. case 'maxHeight':
  14695. case 'left':
  14696. case 'top':
  14697. case 'bottom':
  14698. case 'right':
  14699. case 'fontSize':
  14700. case 'outlineWidth':
  14701. case 'outlineOffset':
  14702. case 'paddingTop':
  14703. case 'paddingLeft':
  14704. case 'paddingBottom':
  14705. case 'paddingRight':
  14706. case 'marginTop':
  14707. case 'marginLeft':
  14708. case 'marginBottom':
  14709. case 'marginRight':
  14710. case 'borderRadius':
  14711. case 'borderWidth':
  14712. case 'borderTopWidth':
  14713. case 'borderLeftWidth':
  14714. case 'borderRightWidth':
  14715. case 'borderBottomWidth':
  14716. case 'textIndent':
  14717. return true;
  14718. default:
  14719. return false;
  14720. }
  14721. }
  14722. /**
  14723. * @license
  14724. * Copyright Google Inc. All Rights Reserved.
  14725. *
  14726. * Use of this source code is governed by an MIT-style license that can be
  14727. * found in the LICENSE file at https://angular.io/license
  14728. */
  14729. var BIND_NAME_REGEXP$1 = /^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/;
  14730. // Group 1 = "bind-"
  14731. var KW_BIND_IDX$1 = 1;
  14732. // Group 2 = "let-"
  14733. var KW_LET_IDX$1 = 2;
  14734. // Group 3 = "ref-/#"
  14735. var KW_REF_IDX$1 = 3;
  14736. // Group 4 = "on-"
  14737. var KW_ON_IDX$1 = 4;
  14738. // Group 5 = "bindon-"
  14739. var KW_BINDON_IDX$1 = 5;
  14740. // Group 6 = "@"
  14741. var KW_AT_IDX$1 = 6;
  14742. // Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
  14743. var IDENT_KW_IDX$1 = 7;
  14744. // Group 8 = identifier inside [()]
  14745. var IDENT_BANANA_BOX_IDX$1 = 8;
  14746. // Group 9 = identifier inside []
  14747. var IDENT_PROPERTY_IDX$1 = 9;
  14748. // Group 10 = identifier inside ()
  14749. var IDENT_EVENT_IDX$1 = 10;
  14750. var TEMPLATE_ATTR_PREFIX$1 = '*';
  14751. function htmlAstToRender3Ast(htmlNodes, bindingParser) {
  14752. var transformer = new HtmlAstToIvyAst(bindingParser);
  14753. var ivyNodes = visitAll$1(transformer, htmlNodes);
  14754. // Errors might originate in either the binding parser or the html to ivy transformer
  14755. var allErrors = bindingParser.errors.concat(transformer.errors);
  14756. var errors = allErrors.filter(function (e) { return e.level === exports.ParseErrorLevel.ERROR; });
  14757. if (errors.length > 0) {
  14758. var errorString = errors.join('\n');
  14759. throw syntaxError("Template parse errors:\n" + errorString, errors);
  14760. }
  14761. return {
  14762. nodes: ivyNodes,
  14763. errors: allErrors,
  14764. styleUrls: transformer.styleUrls,
  14765. styles: transformer.styles,
  14766. };
  14767. }
  14768. var HtmlAstToIvyAst = /** @class */ (function () {
  14769. function HtmlAstToIvyAst(bindingParser) {
  14770. this.bindingParser = bindingParser;
  14771. this.errors = [];
  14772. this.styles = [];
  14773. this.styleUrls = [];
  14774. }
  14775. // HTML visitor
  14776. HtmlAstToIvyAst.prototype.visitElement = function (element) {
  14777. var _this = this;
  14778. var e_1, _a;
  14779. var preparsedElement = preparseElement(element);
  14780. if (preparsedElement.type === PreparsedElementType.SCRIPT) {
  14781. return null;
  14782. }
  14783. else if (preparsedElement.type === PreparsedElementType.STYLE) {
  14784. var contents = textContents(element);
  14785. if (contents !== null) {
  14786. this.styles.push(contents);
  14787. }
  14788. return null;
  14789. }
  14790. else if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
  14791. isStyleUrlResolvable(preparsedElement.hrefAttr)) {
  14792. this.styleUrls.push(preparsedElement.hrefAttr);
  14793. return null;
  14794. }
  14795. // Whether the element is a `<ng-template>`
  14796. var isTemplateElement = isNgTemplate(element.name);
  14797. var parsedProperties = [];
  14798. var boundEvents = [];
  14799. var variables = [];
  14800. var references = [];
  14801. var attributes = [];
  14802. var i18nAttrsMeta = {};
  14803. var templateParsedProperties = [];
  14804. var templateVariables = [];
  14805. // Whether the element has any *-attribute
  14806. var elementHasInlineTemplate = false;
  14807. try {
  14808. for (var _b = __values(element.attrs), _c = _b.next(); !_c.done; _c = _b.next()) {
  14809. var attribute = _c.value;
  14810. var hasBinding = false;
  14811. var normalizedName = normalizeAttributeName(attribute.name);
  14812. // `*attr` defines template bindings
  14813. var isTemplateBinding = false;
  14814. if (attribute.i18n) {
  14815. i18nAttrsMeta[attribute.name] = attribute.i18n;
  14816. }
  14817. if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX$1)) {
  14818. // *-attributes
  14819. if (elementHasInlineTemplate) {
  14820. this.reportError("Can't have multiple template bindings on one element. Use only one attribute prefixed with *", attribute.sourceSpan);
  14821. }
  14822. isTemplateBinding = true;
  14823. elementHasInlineTemplate = true;
  14824. var templateValue = attribute.value;
  14825. var templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX$1.length);
  14826. var parsedVariables = [];
  14827. this.bindingParser.parseInlineTemplateBinding(templateKey, templateValue, attribute.sourceSpan, [], templateParsedProperties, parsedVariables);
  14828. templateVariables.push.apply(templateVariables, __spread(parsedVariables.map(function (v) { return new Variable(v.name, v.value, v.sourceSpan); })));
  14829. }
  14830. else {
  14831. // Check for variables, events, property bindings, interpolation
  14832. hasBinding = this.parseAttribute(isTemplateElement, attribute, [], parsedProperties, boundEvents, variables, references);
  14833. }
  14834. if (!hasBinding && !isTemplateBinding) {
  14835. // don't include the bindings as attributes as well in the AST
  14836. attributes.push(this.visitAttribute(attribute));
  14837. }
  14838. }
  14839. }
  14840. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  14841. finally {
  14842. try {
  14843. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  14844. }
  14845. finally { if (e_1) throw e_1.error; }
  14846. }
  14847. var children = visitAll$1(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR$1 : this, element.children);
  14848. var parsedElement;
  14849. if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
  14850. // `<ng-content>`
  14851. if (element.children &&
  14852. !element.children.every(function (node) { return isEmptyTextNode(node) || isCommentNode(node); })) {
  14853. this.reportError("<ng-content> element cannot have content.", element.sourceSpan);
  14854. }
  14855. var selector = preparsedElement.selectAttr;
  14856. var attrs = element.attrs.map(function (attr) { return _this.visitAttribute(attr); });
  14857. parsedElement = new Content(selector, attrs, element.sourceSpan, element.i18n);
  14858. }
  14859. else if (isTemplateElement) {
  14860. // `<ng-template>`
  14861. var attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
  14862. parsedElement = new Template(element.name, attributes, attrs.bound, boundEvents, [ /* no template attributes */], children, references, variables, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  14863. }
  14864. else {
  14865. var attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
  14866. parsedElement = new Element(element.name, attributes, attrs.bound, boundEvents, children, references, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  14867. }
  14868. if (elementHasInlineTemplate) {
  14869. // If this node is an inline-template (e.g. has *ngFor) then we need to create a template
  14870. // node that contains this node.
  14871. // Moreover, if the node is an element, then we need to hoist its attributes to the template
  14872. // node for matching against content projection selectors.
  14873. var attrs = this.extractAttributes('ng-template', templateParsedProperties, i18nAttrsMeta);
  14874. var templateAttrs_1 = [];
  14875. attrs.literal.forEach(function (attr) { return templateAttrs_1.push(attr); });
  14876. attrs.bound.forEach(function (attr) { return templateAttrs_1.push(attr); });
  14877. var hoistedAttrs = parsedElement instanceof Element ?
  14878. {
  14879. attributes: parsedElement.attributes,
  14880. inputs: parsedElement.inputs,
  14881. outputs: parsedElement.outputs,
  14882. } :
  14883. { attributes: [], inputs: [], outputs: [] };
  14884. // TODO(pk): test for this case
  14885. 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);
  14886. }
  14887. return parsedElement;
  14888. };
  14889. HtmlAstToIvyAst.prototype.visitAttribute = function (attribute) {
  14890. return new TextAttribute(attribute.name, attribute.value, attribute.sourceSpan, attribute.valueSpan, attribute.i18n);
  14891. };
  14892. HtmlAstToIvyAst.prototype.visitText = function (text) {
  14893. return this._visitTextWithInterpolation(text.value, text.sourceSpan, text.i18n);
  14894. };
  14895. HtmlAstToIvyAst.prototype.visitExpansion = function (expansion) {
  14896. var _this = this;
  14897. var meta = expansion.i18n;
  14898. // do not generate Icu in case it was created
  14899. // outside of i18n block in a template
  14900. if (!meta) {
  14901. return null;
  14902. }
  14903. var vars = {};
  14904. var placeholders = {};
  14905. // extract VARs from ICUs - we process them separately while
  14906. // assembling resulting message via goog.getMsg function, since
  14907. // we need to pass them to top-level goog.getMsg call
  14908. Object.keys(meta.placeholders).forEach(function (key) {
  14909. var value = meta.placeholders[key];
  14910. if (key.startsWith(I18N_ICU_VAR_PREFIX)) {
  14911. var config = _this.bindingParser.interpolationConfig;
  14912. // ICU expression is a plain string, not wrapped into start
  14913. // and end tags, so we wrap it before passing to binding parser
  14914. var wrapped = "" + config.start + value + config.end;
  14915. vars[key] = _this._visitTextWithInterpolation(wrapped, expansion.sourceSpan);
  14916. }
  14917. else {
  14918. placeholders[key] = _this._visitTextWithInterpolation(value, expansion.sourceSpan);
  14919. }
  14920. });
  14921. return new Icu(vars, placeholders, expansion.sourceSpan, meta);
  14922. };
  14923. HtmlAstToIvyAst.prototype.visitExpansionCase = function (expansionCase) { return null; };
  14924. HtmlAstToIvyAst.prototype.visitComment = function (comment) { return null; };
  14925. // convert view engine `ParsedProperty` to a format suitable for IVY
  14926. HtmlAstToIvyAst.prototype.extractAttributes = function (elementName, properties, i18nPropsMeta) {
  14927. var _this = this;
  14928. var bound = [];
  14929. var literal = [];
  14930. properties.forEach(function (prop) {
  14931. var i18n = i18nPropsMeta[prop.name];
  14932. if (prop.isLiteral) {
  14933. literal.push(new TextAttribute(prop.name, prop.expression.source || '', prop.sourceSpan, undefined, i18n));
  14934. }
  14935. else {
  14936. // Note that validation is skipped and property mapping is disabled
  14937. // due to the fact that we need to make sure a given prop is not an
  14938. // input of a directive and directive matching happens at runtime.
  14939. var bep = _this.bindingParser.createBoundElementProperty(elementName, prop, /* skipValidation */ true, /* mapPropertyName */ false);
  14940. bound.push(BoundAttribute.fromBoundElementProperty(bep, i18n));
  14941. }
  14942. });
  14943. return { bound: bound, literal: literal };
  14944. };
  14945. HtmlAstToIvyAst.prototype.parseAttribute = function (isTemplateElement, attribute, matchableAttributes, parsedProperties, boundEvents, variables, references) {
  14946. var name = normalizeAttributeName(attribute.name);
  14947. var value = attribute.value;
  14948. var srcSpan = attribute.sourceSpan;
  14949. var bindParts = name.match(BIND_NAME_REGEXP$1);
  14950. var hasBinding = false;
  14951. if (bindParts) {
  14952. hasBinding = true;
  14953. if (bindParts[KW_BIND_IDX$1] != null) {
  14954. this.bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX$1], value, false, srcSpan, matchableAttributes, parsedProperties);
  14955. }
  14956. else if (bindParts[KW_LET_IDX$1]) {
  14957. if (isTemplateElement) {
  14958. var identifier = bindParts[IDENT_KW_IDX$1];
  14959. this.parseVariable(identifier, value, srcSpan, variables);
  14960. }
  14961. else {
  14962. this.reportError("\"let-\" is only supported on ng-template elements.", srcSpan);
  14963. }
  14964. }
  14965. else if (bindParts[KW_REF_IDX$1]) {
  14966. var identifier = bindParts[IDENT_KW_IDX$1];
  14967. this.parseReference(identifier, value, srcSpan, references);
  14968. }
  14969. else if (bindParts[KW_ON_IDX$1]) {
  14970. var events = [];
  14971. this.bindingParser.parseEvent(bindParts[IDENT_KW_IDX$1], value, srcSpan, attribute.valueSpan || srcSpan, matchableAttributes, events);
  14972. addEvents(events, boundEvents);
  14973. }
  14974. else if (bindParts[KW_BINDON_IDX$1]) {
  14975. this.bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX$1], value, false, srcSpan, matchableAttributes, parsedProperties);
  14976. this.parseAssignmentEvent(bindParts[IDENT_KW_IDX$1], value, srcSpan, attribute.valueSpan, matchableAttributes, boundEvents);
  14977. }
  14978. else if (bindParts[KW_AT_IDX$1]) {
  14979. this.bindingParser.parseLiteralAttr(name, value, srcSpan, matchableAttributes, parsedProperties);
  14980. }
  14981. else if (bindParts[IDENT_BANANA_BOX_IDX$1]) {
  14982. this.bindingParser.parsePropertyBinding(bindParts[IDENT_BANANA_BOX_IDX$1], value, false, srcSpan, matchableAttributes, parsedProperties);
  14983. this.parseAssignmentEvent(bindParts[IDENT_BANANA_BOX_IDX$1], value, srcSpan, attribute.valueSpan, matchableAttributes, boundEvents);
  14984. }
  14985. else if (bindParts[IDENT_PROPERTY_IDX$1]) {
  14986. this.bindingParser.parsePropertyBinding(bindParts[IDENT_PROPERTY_IDX$1], value, false, srcSpan, matchableAttributes, parsedProperties);
  14987. }
  14988. else if (bindParts[IDENT_EVENT_IDX$1]) {
  14989. var events = [];
  14990. this.bindingParser.parseEvent(bindParts[IDENT_EVENT_IDX$1], value, srcSpan, attribute.valueSpan || srcSpan, matchableAttributes, events);
  14991. addEvents(events, boundEvents);
  14992. }
  14993. }
  14994. else {
  14995. hasBinding = this.bindingParser.parsePropertyInterpolation(name, value, srcSpan, matchableAttributes, parsedProperties);
  14996. }
  14997. return hasBinding;
  14998. };
  14999. HtmlAstToIvyAst.prototype._visitTextWithInterpolation = function (value, sourceSpan, i18n) {
  15000. var valueNoNgsp = replaceNgsp(value);
  15001. var expr = this.bindingParser.parseInterpolation(valueNoNgsp, sourceSpan);
  15002. return expr ? new BoundText(expr, sourceSpan, i18n) : new Text(valueNoNgsp, sourceSpan);
  15003. };
  15004. HtmlAstToIvyAst.prototype.parseVariable = function (identifier, value, sourceSpan, variables) {
  15005. if (identifier.indexOf('-') > -1) {
  15006. this.reportError("\"-\" is not allowed in variable names", sourceSpan);
  15007. }
  15008. variables.push(new Variable(identifier, value, sourceSpan));
  15009. };
  15010. HtmlAstToIvyAst.prototype.parseReference = function (identifier, value, sourceSpan, references) {
  15011. if (identifier.indexOf('-') > -1) {
  15012. this.reportError("\"-\" is not allowed in reference names", sourceSpan);
  15013. }
  15014. references.push(new Reference(identifier, value, sourceSpan));
  15015. };
  15016. HtmlAstToIvyAst.prototype.parseAssignmentEvent = function (name, expression, sourceSpan, valueSpan, targetMatchableAttrs, boundEvents) {
  15017. var events = [];
  15018. this.bindingParser.parseEvent(name + "Change", expression + "=$event", sourceSpan, valueSpan || sourceSpan, targetMatchableAttrs, events);
  15019. addEvents(events, boundEvents);
  15020. };
  15021. HtmlAstToIvyAst.prototype.reportError = function (message, sourceSpan, level) {
  15022. if (level === void 0) { level = exports.ParseErrorLevel.ERROR; }
  15023. this.errors.push(new ParseError(sourceSpan, message, level));
  15024. };
  15025. return HtmlAstToIvyAst;
  15026. }());
  15027. var NonBindableVisitor$1 = /** @class */ (function () {
  15028. function NonBindableVisitor() {
  15029. }
  15030. NonBindableVisitor.prototype.visitElement = function (ast) {
  15031. var preparsedElement = preparseElement(ast);
  15032. if (preparsedElement.type === PreparsedElementType.SCRIPT ||
  15033. preparsedElement.type === PreparsedElementType.STYLE ||
  15034. preparsedElement.type === PreparsedElementType.STYLESHEET) {
  15035. // Skipping <script> for security reasons
  15036. // Skipping <style> and stylesheets as we already processed them
  15037. // in the StyleCompiler
  15038. return null;
  15039. }
  15040. var children = visitAll$1(this, ast.children, null);
  15041. return new Element(ast.name, visitAll$1(this, ast.attrs),
  15042. /* inputs */ [], /* outputs */ [], children, /* references */ [], ast.sourceSpan, ast.startSourceSpan, ast.endSourceSpan);
  15043. };
  15044. NonBindableVisitor.prototype.visitComment = function (comment) { return null; };
  15045. NonBindableVisitor.prototype.visitAttribute = function (attribute) {
  15046. return new TextAttribute(attribute.name, attribute.value, attribute.sourceSpan, undefined, attribute.i18n);
  15047. };
  15048. NonBindableVisitor.prototype.visitText = function (text) { return new Text(text.value, text.sourceSpan); };
  15049. NonBindableVisitor.prototype.visitExpansion = function (expansion) { return null; };
  15050. NonBindableVisitor.prototype.visitExpansionCase = function (expansionCase) { return null; };
  15051. return NonBindableVisitor;
  15052. }());
  15053. var NON_BINDABLE_VISITOR$1 = new NonBindableVisitor$1();
  15054. function normalizeAttributeName(attrName) {
  15055. return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
  15056. }
  15057. function addEvents(events, boundEvents) {
  15058. boundEvents.push.apply(boundEvents, __spread(events.map(function (e) { return BoundEvent.fromParsedEvent(e); })));
  15059. }
  15060. function isEmptyTextNode(node) {
  15061. return node instanceof Text$3 && node.value.trim().length == 0;
  15062. }
  15063. function isCommentNode(node) {
  15064. return node instanceof Comment;
  15065. }
  15066. function textContents(node) {
  15067. if (node.children.length !== 1 || !(node.children[0] instanceof Text$3)) {
  15068. return null;
  15069. }
  15070. else {
  15071. return node.children[0].value;
  15072. }
  15073. }
  15074. /**
  15075. * @license
  15076. * Copyright Google Inc. All Rights Reserved.
  15077. *
  15078. * Use of this source code is governed by an MIT-style license that can be
  15079. * found in the LICENSE file at https://angular.io/license
  15080. */
  15081. var TagType;
  15082. (function (TagType) {
  15083. TagType[TagType["ELEMENT"] = 0] = "ELEMENT";
  15084. TagType[TagType["TEMPLATE"] = 1] = "TEMPLATE";
  15085. TagType[TagType["PROJECTION"] = 2] = "PROJECTION";
  15086. })(TagType || (TagType = {}));
  15087. /**
  15088. * Generates an object that is used as a shared state between parent and all child contexts.
  15089. */
  15090. function setupRegistry() {
  15091. return { getUniqueId: getSeqNumberGenerator(), icus: new Map() };
  15092. }
  15093. /**
  15094. * I18nContext is a helper class which keeps track of all i18n-related aspects
  15095. * (accumulates placeholders, bindings, etc) between i18nStart and i18nEnd instructions.
  15096. *
  15097. * When we enter a nested template, the top-level context is being passed down
  15098. * to the nested component, which uses this context to generate a child instance
  15099. * of I18nContext class (to handle nested template) and at the end, reconciles it back
  15100. * with the parent context.
  15101. *
  15102. * @param index Instruction index of i18nStart, which initiates this context
  15103. * @param ref Reference to a translation const that represents the content if thus context
  15104. * @param level Nestng level defined for child contexts
  15105. * @param templateIndex Instruction index of a template which this context belongs to
  15106. * @param meta Meta information (id, meaning, description, etc) associated with this context
  15107. */
  15108. var I18nContext = /** @class */ (function () {
  15109. function I18nContext(index, ref, level, templateIndex, meta, registry) {
  15110. if (level === void 0) { level = 0; }
  15111. if (templateIndex === void 0) { templateIndex = null; }
  15112. this.index = index;
  15113. this.ref = ref;
  15114. this.level = level;
  15115. this.templateIndex = templateIndex;
  15116. this.meta = meta;
  15117. this.registry = registry;
  15118. this.bindings = new Set();
  15119. this.placeholders = new Map();
  15120. this.isEmitted = false;
  15121. this._unresolvedCtxCount = 0;
  15122. this._registry = registry || setupRegistry();
  15123. this.id = this._registry.getUniqueId();
  15124. }
  15125. I18nContext.prototype.appendTag = function (type, node, index, closed) {
  15126. if (node.isVoid && closed) {
  15127. return; // ignore "close" for void tags
  15128. }
  15129. var ph = node.isVoid || !closed ? node.startName : node.closeName;
  15130. var content = { type: type, index: index, ctx: this.id, isVoid: node.isVoid, closed: closed };
  15131. updatePlaceholderMap(this.placeholders, ph, content);
  15132. };
  15133. Object.defineProperty(I18nContext.prototype, "icus", {
  15134. get: function () { return this._registry.icus; },
  15135. enumerable: true,
  15136. configurable: true
  15137. });
  15138. Object.defineProperty(I18nContext.prototype, "isRoot", {
  15139. get: function () { return this.level === 0; },
  15140. enumerable: true,
  15141. configurable: true
  15142. });
  15143. Object.defineProperty(I18nContext.prototype, "isResolved", {
  15144. get: function () { return this._unresolvedCtxCount === 0; },
  15145. enumerable: true,
  15146. configurable: true
  15147. });
  15148. I18nContext.prototype.getSerializedPlaceholders = function () {
  15149. var result = new Map();
  15150. this.placeholders.forEach(function (values, key) { return result.set(key, values.map(serializePlaceholderValue)); });
  15151. return result;
  15152. };
  15153. // public API to accumulate i18n-related content
  15154. I18nContext.prototype.appendBinding = function (binding) { this.bindings.add(binding); };
  15155. I18nContext.prototype.appendIcu = function (name, ref) {
  15156. updatePlaceholderMap(this._registry.icus, name, ref);
  15157. };
  15158. I18nContext.prototype.appendBoundText = function (node) {
  15159. var _this = this;
  15160. var phs = assembleBoundTextPlaceholders(node, this.bindings.size, this.id);
  15161. phs.forEach(function (values, key) { return updatePlaceholderMap.apply(void 0, __spread([_this.placeholders, key], values)); });
  15162. };
  15163. I18nContext.prototype.appendTemplate = function (node, index) {
  15164. // add open and close tags at the same time,
  15165. // since we process nested templates separately
  15166. this.appendTag(TagType.TEMPLATE, node, index, false);
  15167. this.appendTag(TagType.TEMPLATE, node, index, true);
  15168. this._unresolvedCtxCount++;
  15169. };
  15170. I18nContext.prototype.appendElement = function (node, index, closed) {
  15171. this.appendTag(TagType.ELEMENT, node, index, closed);
  15172. };
  15173. I18nContext.prototype.appendProjection = function (node, index) {
  15174. // add open and close tags at the same time,
  15175. // since we process projected content separately
  15176. this.appendTag(TagType.PROJECTION, node, index, false);
  15177. this.appendTag(TagType.PROJECTION, node, index, true);
  15178. };
  15179. /**
  15180. * Generates an instance of a child context based on the root one,
  15181. * when we enter a nested template within I18n section.
  15182. *
  15183. * @param index Instruction index of corresponding i18nStart, which initiates this context
  15184. * @param templateIndex Instruction index of a template which this context belongs to
  15185. * @param meta Meta information (id, meaning, description, etc) associated with this context
  15186. *
  15187. * @returns I18nContext instance
  15188. */
  15189. I18nContext.prototype.forkChildContext = function (index, templateIndex, meta) {
  15190. return new I18nContext(index, this.ref, this.level + 1, templateIndex, meta, this._registry);
  15191. };
  15192. /**
  15193. * Reconciles child context into parent one once the end of the i18n block is reached (i18nEnd).
  15194. *
  15195. * @param context Child I18nContext instance to be reconciled with parent context.
  15196. */
  15197. I18nContext.prototype.reconcileChildContext = function (context) {
  15198. var _this = this;
  15199. // set the right context id for open and close
  15200. // template tags, so we can use it as sub-block ids
  15201. ['start', 'close'].forEach(function (op) {
  15202. var key = context.meta[op + "Name"];
  15203. var phs = _this.placeholders.get(key) || [];
  15204. var tag = phs.find(findTemplateFn(_this.id, context.templateIndex));
  15205. if (tag) {
  15206. tag.ctx = context.id;
  15207. }
  15208. });
  15209. // reconcile placeholders
  15210. var childPhs = context.placeholders;
  15211. childPhs.forEach(function (values, key) {
  15212. var phs = _this.placeholders.get(key);
  15213. if (!phs) {
  15214. _this.placeholders.set(key, values);
  15215. return;
  15216. }
  15217. // try to find matching template...
  15218. var tmplIdx = findIndex(phs, findTemplateFn(context.id, context.templateIndex));
  15219. if (tmplIdx >= 0) {
  15220. // ... if found - replace it with nested template content
  15221. var isCloseTag = key.startsWith('CLOSE');
  15222. var isTemplateTag = key.endsWith('NG-TEMPLATE');
  15223. if (isTemplateTag) {
  15224. // current template's content is placed before or after
  15225. // parent template tag, depending on the open/close atrribute
  15226. phs.splice.apply(phs, __spread([tmplIdx + (isCloseTag ? 0 : 1), 0], values));
  15227. }
  15228. else {
  15229. var idx = isCloseTag ? values.length - 1 : 0;
  15230. values[idx].tmpl = phs[tmplIdx];
  15231. phs.splice.apply(phs, __spread([tmplIdx, 1], values));
  15232. }
  15233. }
  15234. else {
  15235. // ... otherwise just append content to placeholder value
  15236. phs.push.apply(phs, __spread(values));
  15237. }
  15238. _this.placeholders.set(key, phs);
  15239. });
  15240. this._unresolvedCtxCount--;
  15241. };
  15242. return I18nContext;
  15243. }());
  15244. //
  15245. // Helper methods
  15246. //
  15247. function wrap(symbol, index, contextId, closed) {
  15248. var state = closed ? '/' : '';
  15249. return wrapI18nPlaceholder("" + state + symbol + index, contextId);
  15250. }
  15251. function wrapTag(symbol, _a, closed) {
  15252. var index = _a.index, ctx = _a.ctx, isVoid = _a.isVoid;
  15253. return isVoid ? wrap(symbol, index, ctx) + wrap(symbol, index, ctx, true) :
  15254. wrap(symbol, index, ctx, closed);
  15255. }
  15256. function findTemplateFn(ctx, templateIndex) {
  15257. return function (token) { return typeof token === 'object' && token.type === TagType.TEMPLATE &&
  15258. token.index === templateIndex && token.ctx === ctx; };
  15259. }
  15260. function serializePlaceholderValue(value) {
  15261. var element = function (data, closed) { return wrapTag('#', data, closed); };
  15262. var template = function (data, closed) { return wrapTag('*', data, closed); };
  15263. var projection = function (data, closed) { return wrapTag('!', data, closed); };
  15264. switch (value.type) {
  15265. case TagType.ELEMENT:
  15266. // close element tag
  15267. if (value.closed) {
  15268. return element(value, true) + (value.tmpl ? template(value.tmpl, true) : '');
  15269. }
  15270. // open element tag that also initiates a template
  15271. if (value.tmpl) {
  15272. return template(value.tmpl) + element(value) +
  15273. (value.isVoid ? template(value.tmpl, true) : '');
  15274. }
  15275. return element(value);
  15276. case TagType.TEMPLATE:
  15277. return template(value, value.closed);
  15278. case TagType.PROJECTION:
  15279. return projection(value, value.closed);
  15280. default:
  15281. return value;
  15282. }
  15283. }
  15284. /**
  15285. * @license
  15286. * Copyright Google Inc. All Rights Reserved.
  15287. *
  15288. * Use of this source code is governed by an MIT-style license that can be
  15289. * found in the LICENSE file at https://angular.io/license
  15290. */
  15291. var TAG_TO_PLACEHOLDER_NAMES = {
  15292. 'A': 'LINK',
  15293. 'B': 'BOLD_TEXT',
  15294. 'BR': 'LINE_BREAK',
  15295. 'EM': 'EMPHASISED_TEXT',
  15296. 'H1': 'HEADING_LEVEL1',
  15297. 'H2': 'HEADING_LEVEL2',
  15298. 'H3': 'HEADING_LEVEL3',
  15299. 'H4': 'HEADING_LEVEL4',
  15300. 'H5': 'HEADING_LEVEL5',
  15301. 'H6': 'HEADING_LEVEL6',
  15302. 'HR': 'HORIZONTAL_RULE',
  15303. 'I': 'ITALIC_TEXT',
  15304. 'LI': 'LIST_ITEM',
  15305. 'LINK': 'MEDIA_LINK',
  15306. 'OL': 'ORDERED_LIST',
  15307. 'P': 'PARAGRAPH',
  15308. 'Q': 'QUOTATION',
  15309. 'S': 'STRIKETHROUGH_TEXT',
  15310. 'SMALL': 'SMALL_TEXT',
  15311. 'SUB': 'SUBSTRIPT',
  15312. 'SUP': 'SUPERSCRIPT',
  15313. 'TBODY': 'TABLE_BODY',
  15314. 'TD': 'TABLE_CELL',
  15315. 'TFOOT': 'TABLE_FOOTER',
  15316. 'TH': 'TABLE_HEADER_CELL',
  15317. 'THEAD': 'TABLE_HEADER',
  15318. 'TR': 'TABLE_ROW',
  15319. 'TT': 'MONOSPACED_TEXT',
  15320. 'U': 'UNDERLINED_TEXT',
  15321. 'UL': 'UNORDERED_LIST',
  15322. };
  15323. /**
  15324. * Creates unique names for placeholder with different content.
  15325. *
  15326. * Returns the same placeholder name when the content is identical.
  15327. */
  15328. var PlaceholderRegistry = /** @class */ (function () {
  15329. function PlaceholderRegistry() {
  15330. // Count the occurrence of the base name top generate a unique name
  15331. this._placeHolderNameCounts = {};
  15332. // Maps signature to placeholder names
  15333. this._signatureToName = {};
  15334. }
  15335. PlaceholderRegistry.prototype.getStartTagPlaceholderName = function (tag, attrs, isVoid) {
  15336. var signature = this._hashTag(tag, attrs, isVoid);
  15337. if (this._signatureToName[signature]) {
  15338. return this._signatureToName[signature];
  15339. }
  15340. var upperTag = tag.toUpperCase();
  15341. var baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || "TAG_" + upperTag;
  15342. var name = this._generateUniqueName(isVoid ? baseName : "START_" + baseName);
  15343. this._signatureToName[signature] = name;
  15344. return name;
  15345. };
  15346. PlaceholderRegistry.prototype.getCloseTagPlaceholderName = function (tag) {
  15347. var signature = this._hashClosingTag(tag);
  15348. if (this._signatureToName[signature]) {
  15349. return this._signatureToName[signature];
  15350. }
  15351. var upperTag = tag.toUpperCase();
  15352. var baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || "TAG_" + upperTag;
  15353. var name = this._generateUniqueName("CLOSE_" + baseName);
  15354. this._signatureToName[signature] = name;
  15355. return name;
  15356. };
  15357. PlaceholderRegistry.prototype.getPlaceholderName = function (name, content) {
  15358. var upperName = name.toUpperCase();
  15359. var signature = "PH: " + upperName + "=" + content;
  15360. if (this._signatureToName[signature]) {
  15361. return this._signatureToName[signature];
  15362. }
  15363. var uniqueName = this._generateUniqueName(upperName);
  15364. this._signatureToName[signature] = uniqueName;
  15365. return uniqueName;
  15366. };
  15367. PlaceholderRegistry.prototype.getUniquePlaceholder = function (name) {
  15368. return this._generateUniqueName(name.toUpperCase());
  15369. };
  15370. // Generate a hash for a tag - does not take attribute order into account
  15371. PlaceholderRegistry.prototype._hashTag = function (tag, attrs, isVoid) {
  15372. var start = "<" + tag;
  15373. var strAttrs = Object.keys(attrs).sort().map(function (name) { return " " + name + "=" + attrs[name]; }).join('');
  15374. var end = isVoid ? '/>' : "></" + tag + ">";
  15375. return start + strAttrs + end;
  15376. };
  15377. PlaceholderRegistry.prototype._hashClosingTag = function (tag) { return this._hashTag("/" + tag, {}, false); };
  15378. PlaceholderRegistry.prototype._generateUniqueName = function (base) {
  15379. var seen = this._placeHolderNameCounts.hasOwnProperty(base);
  15380. if (!seen) {
  15381. this._placeHolderNameCounts[base] = 1;
  15382. return base;
  15383. }
  15384. var id = this._placeHolderNameCounts[base];
  15385. this._placeHolderNameCounts[base] = id + 1;
  15386. return base + "_" + id;
  15387. };
  15388. return PlaceholderRegistry;
  15389. }());
  15390. /**
  15391. * @license
  15392. * Copyright Google Inc. All Rights Reserved.
  15393. *
  15394. * Use of this source code is governed by an MIT-style license that can be
  15395. * found in the LICENSE file at https://angular.io/license
  15396. */
  15397. var _expParser = new Parser$1(new Lexer());
  15398. /**
  15399. * Returns a function converting html nodes to an i18n Message given an interpolationConfig
  15400. */
  15401. function createI18nMessageFactory(interpolationConfig) {
  15402. var visitor = new _I18nVisitor(_expParser, interpolationConfig);
  15403. return function (nodes, meaning, description, id, visitNodeFn) {
  15404. return visitor.toI18nMessage(nodes, meaning, description, id, visitNodeFn);
  15405. };
  15406. }
  15407. var _I18nVisitor = /** @class */ (function () {
  15408. function _I18nVisitor(_expressionParser, _interpolationConfig) {
  15409. this._expressionParser = _expressionParser;
  15410. this._interpolationConfig = _interpolationConfig;
  15411. }
  15412. _I18nVisitor.prototype.toI18nMessage = function (nodes, meaning, description, id, visitNodeFn) {
  15413. this._isIcu = nodes.length == 1 && nodes[0] instanceof Expansion;
  15414. this._icuDepth = 0;
  15415. this._placeholderRegistry = new PlaceholderRegistry();
  15416. this._placeholderToContent = {};
  15417. this._placeholderToMessage = {};
  15418. this._visitNodeFn = visitNodeFn;
  15419. var i18nodes = visitAll$1(this, nodes, {});
  15420. return new Message(i18nodes, this._placeholderToContent, this._placeholderToMessage, meaning, description, id);
  15421. };
  15422. _I18nVisitor.prototype._visitNode = function (html, i18n) {
  15423. if (this._visitNodeFn) {
  15424. this._visitNodeFn(html, i18n);
  15425. }
  15426. return i18n;
  15427. };
  15428. _I18nVisitor.prototype.visitElement = function (el, context) {
  15429. var children = visitAll$1(this, el.children);
  15430. var attrs = {};
  15431. el.attrs.forEach(function (attr) {
  15432. // Do not visit the attributes, translatable ones are top-level ASTs
  15433. attrs[attr.name] = attr.value;
  15434. });
  15435. var isVoid = getHtmlTagDefinition(el.name).isVoid;
  15436. var startPhName = this._placeholderRegistry.getStartTagPlaceholderName(el.name, attrs, isVoid);
  15437. this._placeholderToContent[startPhName] = el.sourceSpan.toString();
  15438. var closePhName = '';
  15439. if (!isVoid) {
  15440. closePhName = this._placeholderRegistry.getCloseTagPlaceholderName(el.name);
  15441. this._placeholderToContent[closePhName] = "</" + el.name + ">";
  15442. }
  15443. var node = new TagPlaceholder(el.name, attrs, startPhName, closePhName, children, isVoid, el.sourceSpan);
  15444. return this._visitNode(el, node);
  15445. };
  15446. _I18nVisitor.prototype.visitAttribute = function (attribute, context) {
  15447. var node = this._visitTextWithInterpolation(attribute.value, attribute.sourceSpan);
  15448. return this._visitNode(attribute, node);
  15449. };
  15450. _I18nVisitor.prototype.visitText = function (text, context) {
  15451. var node = this._visitTextWithInterpolation(text.value, text.sourceSpan);
  15452. return this._visitNode(text, node);
  15453. };
  15454. _I18nVisitor.prototype.visitComment = function (comment, context) { return null; };
  15455. _I18nVisitor.prototype.visitExpansion = function (icu, context) {
  15456. var _this = this;
  15457. this._icuDepth++;
  15458. var i18nIcuCases = {};
  15459. var i18nIcu = new Icu$1(icu.switchValue, icu.type, i18nIcuCases, icu.sourceSpan);
  15460. icu.cases.forEach(function (caze) {
  15461. i18nIcuCases[caze.value] = new Container(caze.expression.map(function (node) { return node.visit(_this, {}); }), caze.expSourceSpan);
  15462. });
  15463. this._icuDepth--;
  15464. if (this._isIcu || this._icuDepth > 0) {
  15465. // Returns an ICU node when:
  15466. // - the message (vs a part of the message) is an ICU message, or
  15467. // - the ICU message is nested.
  15468. var expPh = this._placeholderRegistry.getUniquePlaceholder("VAR_" + icu.type);
  15469. i18nIcu.expressionPlaceholder = expPh;
  15470. this._placeholderToContent[expPh] = icu.switchValue;
  15471. return this._visitNode(icu, i18nIcu);
  15472. }
  15473. // Else returns a placeholder
  15474. // ICU placeholders should not be replaced with their original content but with the their
  15475. // translations. We need to create a new visitor (they are not re-entrant) to compute the
  15476. // message id.
  15477. // TODO(vicb): add a html.Node -> i18n.Message cache to avoid having to re-create the msg
  15478. var phName = this._placeholderRegistry.getPlaceholderName('ICU', icu.sourceSpan.toString());
  15479. var visitor = new _I18nVisitor(this._expressionParser, this._interpolationConfig);
  15480. this._placeholderToMessage[phName] = visitor.toI18nMessage([icu], '', '', '');
  15481. var node = new IcuPlaceholder(i18nIcu, phName, icu.sourceSpan);
  15482. return this._visitNode(icu, node);
  15483. };
  15484. _I18nVisitor.prototype.visitExpansionCase = function (icuCase, context) {
  15485. throw new Error('Unreachable code');
  15486. };
  15487. _I18nVisitor.prototype._visitTextWithInterpolation = function (text, sourceSpan) {
  15488. var splitInterpolation = this._expressionParser.splitInterpolation(text, sourceSpan.start.toString(), this._interpolationConfig);
  15489. if (!splitInterpolation) {
  15490. // No expression, return a single text
  15491. return new Text$1(text, sourceSpan);
  15492. }
  15493. // Return a group of text + expressions
  15494. var nodes = [];
  15495. var container = new Container(nodes, sourceSpan);
  15496. var _a = this._interpolationConfig, sDelimiter = _a.start, eDelimiter = _a.end;
  15497. for (var i = 0; i < splitInterpolation.strings.length - 1; i++) {
  15498. var expression = splitInterpolation.expressions[i];
  15499. var baseName = _extractPlaceholderName(expression) || 'INTERPOLATION';
  15500. var phName = this._placeholderRegistry.getPlaceholderName(baseName, expression);
  15501. if (splitInterpolation.strings[i].length) {
  15502. // No need to add empty strings
  15503. nodes.push(new Text$1(splitInterpolation.strings[i], sourceSpan));
  15504. }
  15505. nodes.push(new Placeholder(expression, phName, sourceSpan));
  15506. this._placeholderToContent[phName] = sDelimiter + expression + eDelimiter;
  15507. }
  15508. // The last index contains no expression
  15509. var lastStringIdx = splitInterpolation.strings.length - 1;
  15510. if (splitInterpolation.strings[lastStringIdx].length) {
  15511. nodes.push(new Text$1(splitInterpolation.strings[lastStringIdx], sourceSpan));
  15512. }
  15513. return container;
  15514. };
  15515. return _I18nVisitor;
  15516. }());
  15517. var _CUSTOM_PH_EXP = /\/\/[\s\S]*i18n[\s\S]*\([\s\S]*ph[\s\S]*=[\s\S]*("|')([\s\S]*?)\1[\s\S]*\)/g;
  15518. function _extractPlaceholderName(input) {
  15519. return input.split(_CUSTOM_PH_EXP)[2];
  15520. }
  15521. /**
  15522. * @license
  15523. * Copyright Google Inc. All Rights Reserved.
  15524. *
  15525. * Use of this source code is governed by an MIT-style license that can be
  15526. * found in the LICENSE file at https://angular.io/license
  15527. */
  15528. function setI18nRefs(html, i18n) {
  15529. html.i18n = i18n;
  15530. }
  15531. /**
  15532. * This visitor walks over HTML parse tree and converts information stored in
  15533. * i18n-related attributes ("i18n" and "i18n-*") into i18n meta object that is
  15534. * stored with other element's and attribute's information.
  15535. */
  15536. var I18nMetaVisitor = /** @class */ (function () {
  15537. function I18nMetaVisitor(interpolationConfig, keepI18nAttrs) {
  15538. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  15539. if (keepI18nAttrs === void 0) { keepI18nAttrs = false; }
  15540. this.interpolationConfig = interpolationConfig;
  15541. this.keepI18nAttrs = keepI18nAttrs;
  15542. // i18n message generation factory
  15543. this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
  15544. }
  15545. I18nMetaVisitor.prototype._generateI18nMessage = function (nodes, meta, visitNodeFn) {
  15546. if (meta === void 0) { meta = ''; }
  15547. var parsed = typeof meta === 'string' ? parseI18nMeta(meta) : metaFromI18nMessage(meta);
  15548. var message = this._createI18nMessage(nodes, parsed.meaning || '', parsed.description || '', parsed.id || '', visitNodeFn);
  15549. if (!message.id) {
  15550. // generate (or restore) message id if not specified in template
  15551. message.id = typeof meta !== 'string' && meta.id || decimalDigest(message);
  15552. }
  15553. return message;
  15554. };
  15555. I18nMetaVisitor.prototype.visitElement = function (element, context) {
  15556. var e_1, _a, e_2, _b;
  15557. if (hasI18nAttrs(element)) {
  15558. var attrs = [];
  15559. var attrsMeta = {};
  15560. try {
  15561. for (var _c = __values(element.attrs), _d = _c.next(); !_d.done; _d = _c.next()) {
  15562. var attr = _d.value;
  15563. if (attr.name === I18N_ATTR) {
  15564. // root 'i18n' node attribute
  15565. var i18n_1 = element.i18n || attr.value;
  15566. var message = this._generateI18nMessage(element.children, i18n_1, setI18nRefs);
  15567. // do not assign empty i18n meta
  15568. if (message.nodes.length) {
  15569. element.i18n = message;
  15570. }
  15571. }
  15572. else if (attr.name.startsWith(I18N_ATTR_PREFIX)) {
  15573. // 'i18n-*' attributes
  15574. var key = attr.name.slice(I18N_ATTR_PREFIX.length);
  15575. attrsMeta[key] = attr.value;
  15576. }
  15577. else {
  15578. // non-i18n attributes
  15579. attrs.push(attr);
  15580. }
  15581. }
  15582. }
  15583. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  15584. finally {
  15585. try {
  15586. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  15587. }
  15588. finally { if (e_1) throw e_1.error; }
  15589. }
  15590. // set i18n meta for attributes
  15591. if (Object.keys(attrsMeta).length) {
  15592. try {
  15593. for (var attrs_1 = __values(attrs), attrs_1_1 = attrs_1.next(); !attrs_1_1.done; attrs_1_1 = attrs_1.next()) {
  15594. var attr = attrs_1_1.value;
  15595. var meta = attrsMeta[attr.name];
  15596. // do not create translation for empty attributes
  15597. if (meta !== undefined && attr.value) {
  15598. attr.i18n = this._generateI18nMessage([attr], attr.i18n || meta);
  15599. }
  15600. }
  15601. }
  15602. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  15603. finally {
  15604. try {
  15605. if (attrs_1_1 && !attrs_1_1.done && (_b = attrs_1.return)) _b.call(attrs_1);
  15606. }
  15607. finally { if (e_2) throw e_2.error; }
  15608. }
  15609. }
  15610. if (!this.keepI18nAttrs) {
  15611. // update element's attributes,
  15612. // keeping only non-i18n related ones
  15613. element.attrs = attrs;
  15614. }
  15615. }
  15616. visitAll$1(this, element.children);
  15617. return element;
  15618. };
  15619. I18nMetaVisitor.prototype.visitExpansion = function (expansion, context) {
  15620. var message;
  15621. var meta = expansion.i18n;
  15622. if (meta instanceof IcuPlaceholder) {
  15623. // set ICU placeholder name (e.g. "ICU_1"),
  15624. // generated while processing root element contents,
  15625. // so we can reference it when we output translation
  15626. var name_1 = meta.name;
  15627. message = this._generateI18nMessage([expansion], meta);
  15628. var icu = icuFromI18nMessage(message);
  15629. icu.name = name_1;
  15630. }
  15631. else {
  15632. // when ICU is a root level translation
  15633. message = this._generateI18nMessage([expansion], meta);
  15634. }
  15635. expansion.i18n = message;
  15636. return expansion;
  15637. };
  15638. I18nMetaVisitor.prototype.visitText = function (text, context) { return text; };
  15639. I18nMetaVisitor.prototype.visitAttribute = function (attribute, context) { return attribute; };
  15640. I18nMetaVisitor.prototype.visitComment = function (comment, context) { return comment; };
  15641. I18nMetaVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return expansionCase; };
  15642. return I18nMetaVisitor;
  15643. }());
  15644. /**
  15645. * @license
  15646. * Copyright Google Inc. All Rights Reserved.
  15647. *
  15648. * Use of this source code is governed by an MIT-style license that can be
  15649. * found in the LICENSE file at https://angular.io/license
  15650. */
  15651. var formatPh = function (value) { return "{$" + formatI18nPlaceholderName(value) + "}"; };
  15652. /**
  15653. * This visitor walks over i18n tree and generates its string representation,
  15654. * including ICUs and placeholders in {$PLACEHOLDER} format.
  15655. */
  15656. var SerializerVisitor = /** @class */ (function () {
  15657. function SerializerVisitor() {
  15658. }
  15659. SerializerVisitor.prototype.visitText = function (text, context) { return text.value; };
  15660. SerializerVisitor.prototype.visitContainer = function (container, context) {
  15661. var _this = this;
  15662. return container.children.map(function (child) { return child.visit(_this); }).join('');
  15663. };
  15664. SerializerVisitor.prototype.visitIcu = function (icu, context) {
  15665. var _this = this;
  15666. var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
  15667. return "{" + icu.expressionPlaceholder + ", " + icu.type + ", " + strCases.join(' ') + "}";
  15668. };
  15669. SerializerVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  15670. var _this = this;
  15671. return ph.isVoid ?
  15672. formatPh(ph.startName) :
  15673. "" + formatPh(ph.startName) + ph.children.map(function (child) { return child.visit(_this); }).join('') + formatPh(ph.closeName);
  15674. };
  15675. SerializerVisitor.prototype.visitPlaceholder = function (ph, context) { return formatPh(ph.name); };
  15676. SerializerVisitor.prototype.visitIcuPlaceholder = function (ph, context) { return formatPh(ph.name); };
  15677. return SerializerVisitor;
  15678. }());
  15679. var serializerVisitor$1 = new SerializerVisitor();
  15680. function getSerializedI18nContent(message) {
  15681. return message.nodes.map(function (node) { return node.visit(serializerVisitor$1, null); }).join('');
  15682. }
  15683. /**
  15684. * @license
  15685. * Copyright Google Inc. All Rights Reserved.
  15686. *
  15687. * Use of this source code is governed by an MIT-style license that can be
  15688. * found in the LICENSE file at https://angular.io/license
  15689. */
  15690. // Selector attribute name of `<ng-content>`
  15691. var NG_CONTENT_SELECT_ATTR$1 = 'select';
  15692. // Attribute name of `ngProjectAs`.
  15693. var NG_PROJECT_AS_ATTR_NAME = 'ngProjectAs';
  15694. // List of supported global targets for event listeners
  15695. var GLOBAL_TARGET_RESOLVERS = new Map([['window', Identifiers$1.resolveWindow], ['document', Identifiers$1.resolveDocument], ['body', Identifiers$1.resolveBody]]);
  15696. var LEADING_TRIVIA_CHARS = [' ', '\n', '\r', '\t'];
  15697. // if (rf & flags) { .. }
  15698. function renderFlagCheckIfStmt(flags, statements) {
  15699. return ifStmt(variable(RENDER_FLAGS).bitwiseAnd(literal(flags), null, false), statements);
  15700. }
  15701. function prepareEventListenerParameters(eventAst, handlerName, scope) {
  15702. if (handlerName === void 0) { handlerName = null; }
  15703. if (scope === void 0) { scope = null; }
  15704. var type = eventAst.type, name = eventAst.name, target = eventAst.target, phase = eventAst.phase, handler = eventAst.handler;
  15705. if (target && !GLOBAL_TARGET_RESOLVERS.has(target)) {
  15706. throw new Error("Unexpected global target '" + target + "' defined for '" + name + "' event.\n Supported list of global targets: " + Array.from(GLOBAL_TARGET_RESOLVERS.keys()) + ".");
  15707. }
  15708. var implicitReceiverExpr = (scope === null || scope.bindingLevel === 0) ?
  15709. variable(CONTEXT_NAME) :
  15710. scope.getOrCreateSharedContextVar(0);
  15711. var bindingExpr = convertActionBinding(scope, implicitReceiverExpr, handler, 'b', function () { return error('Unexpected interpolation'); }, eventAst.handlerSpan);
  15712. var statements = [];
  15713. if (scope) {
  15714. statements.push.apply(statements, __spread(scope.restoreViewStatement()));
  15715. statements.push.apply(statements, __spread(scope.variableDeclarations()));
  15716. }
  15717. statements.push.apply(statements, __spread(bindingExpr.render3Stmts));
  15718. var eventName = type === 1 /* Animation */ ? prepareSyntheticListenerName(name, phase) : name;
  15719. var fnName = handlerName && sanitizeIdentifier(handlerName);
  15720. var fnArgs = [new FnParam('$event', DYNAMIC_TYPE)];
  15721. var handlerFn = fn(fnArgs, statements, INFERRED_TYPE, null, fnName);
  15722. var params = [literal(eventName), handlerFn];
  15723. if (target) {
  15724. params.push(literal(false), // `useCapture` flag, defaults to `false`
  15725. importExpr(GLOBAL_TARGET_RESOLVERS.get(target)));
  15726. }
  15727. return params;
  15728. }
  15729. var TemplateDefinitionBuilder = /** @class */ (function () {
  15730. function TemplateDefinitionBuilder(constantPool, parentBindingScope, level, contextName, i18nContext, templateIndex, templateName, directiveMatcher, directives, pipeTypeByName, pipes, _namespace, relativeContextFilePath, i18nUseExternalIds) {
  15731. var _this = this;
  15732. if (level === void 0) { level = 0; }
  15733. this.constantPool = constantPool;
  15734. this.level = level;
  15735. this.contextName = contextName;
  15736. this.i18nContext = i18nContext;
  15737. this.templateIndex = templateIndex;
  15738. this.templateName = templateName;
  15739. this.directiveMatcher = directiveMatcher;
  15740. this.directives = directives;
  15741. this.pipeTypeByName = pipeTypeByName;
  15742. this.pipes = pipes;
  15743. this._namespace = _namespace;
  15744. this.relativeContextFilePath = relativeContextFilePath;
  15745. this.i18nUseExternalIds = i18nUseExternalIds;
  15746. this._dataIndex = 0;
  15747. this._bindingContext = 0;
  15748. this._prefixCode = [];
  15749. /**
  15750. * List of callbacks to generate creation mode instructions. We store them here as we process
  15751. * the template so bindings in listeners are resolved only once all nodes have been visited.
  15752. * This ensures all local refs and context variables are available for matching.
  15753. */
  15754. this._creationCodeFns = [];
  15755. /**
  15756. * List of callbacks to generate update mode instructions. We store them here as we process
  15757. * the template so bindings are resolved only once all nodes have been visited. This ensures
  15758. * all local refs and context variables are available for matching.
  15759. */
  15760. this._updateCodeFns = [];
  15761. /**
  15762. * Memorizes the last node index for which a select instruction has been generated.
  15763. * We're initializing this to -1 to ensure the `select(0)` instruction is generated before any
  15764. * relevant update instructions.
  15765. */
  15766. this._lastNodeIndexWithFlush = -1;
  15767. /** Temporary variable declarations generated from visiting pipes, literals, etc. */
  15768. this._tempVariables = [];
  15769. /**
  15770. * List of callbacks to build nested templates. Nested templates must not be visited until
  15771. * after the parent template has finished visiting all of its nodes. This ensures that all
  15772. * local ref bindings in nested templates are able to find local ref values if the refs
  15773. * are defined after the template declaration.
  15774. */
  15775. this._nestedTemplateFns = [];
  15776. this._unsupported = unsupported;
  15777. // i18n context local to this template
  15778. this.i18n = null;
  15779. // Number of slots to reserve for pureFunctions
  15780. this._pureFunctionSlots = 0;
  15781. // Number of binding slots
  15782. this._bindingSlots = 0;
  15783. // Projection slots found in the template. Projection slots can distribute projected
  15784. // nodes based on a selector, or can just use the wildcard selector to match
  15785. // all nodes which aren't matching any selector.
  15786. this._ngContentReservedSlots = [];
  15787. // Number of non-default selectors found in all parent templates of this template. We need to
  15788. // track it to properly adjust projection slot index in the `projection` instruction.
  15789. this._ngContentSelectorsOffset = 0;
  15790. // Expression that should be used as implicit receiver when converting template
  15791. // expressions to output AST.
  15792. this._implicitReceiverExpr = null;
  15793. // These should be handled in the template or element directly.
  15794. this.visitReference = invalid$1;
  15795. this.visitVariable = invalid$1;
  15796. this.visitTextAttribute = invalid$1;
  15797. this.visitBoundAttribute = invalid$1;
  15798. this.visitBoundEvent = invalid$1;
  15799. this._bindingScope = parentBindingScope.nestedScope(level);
  15800. // Turn the relative context file path into an identifier by replacing non-alphanumeric
  15801. // characters with underscores.
  15802. this.fileBasedI18nSuffix = relativeContextFilePath.replace(/[^A-Za-z0-9]/g, '_') + '_';
  15803. this._valueConverter = new ValueConverter(constantPool, function () { return _this.allocateDataSlot(); }, function (numSlots) { return _this.allocatePureFunctionSlots(numSlots); }, function (name, localName, slot, value) {
  15804. var pipeType = pipeTypeByName.get(name);
  15805. if (pipeType) {
  15806. _this.pipes.add(pipeType);
  15807. }
  15808. _this._bindingScope.set(_this.level, localName, value);
  15809. _this.creationInstruction(null, Identifiers$1.pipe, [literal(slot), literal(name)]);
  15810. });
  15811. }
  15812. TemplateDefinitionBuilder.prototype.registerContextVariables = function (variable$1) {
  15813. var scopedName = this._bindingScope.freshReferenceName();
  15814. var retrievalLevel = this.level;
  15815. var lhs = variable(variable$1.name + scopedName);
  15816. this._bindingScope.set(retrievalLevel, variable$1.name, lhs, 1 /* CONTEXT */, function (scope, relativeLevel) {
  15817. var rhs;
  15818. if (scope.bindingLevel === retrievalLevel) {
  15819. // e.g. ctx
  15820. rhs = variable(CONTEXT_NAME);
  15821. }
  15822. else {
  15823. var sharedCtxVar = scope.getSharedContextName(retrievalLevel);
  15824. // e.g. ctx_r0 OR x(2);
  15825. rhs = sharedCtxVar ? sharedCtxVar : generateNextContextExpr(relativeLevel);
  15826. }
  15827. // e.g. const $item$ = x(2).$implicit;
  15828. return [lhs.set(rhs.prop(variable$1.value || IMPLICIT_REFERENCE)).toConstDecl()];
  15829. });
  15830. };
  15831. TemplateDefinitionBuilder.prototype.buildTemplateFunction = function (nodes, variables, ngContentSelectorsOffset, i18n) {
  15832. var _this = this;
  15833. if (ngContentSelectorsOffset === void 0) { ngContentSelectorsOffset = 0; }
  15834. this._ngContentSelectorsOffset = ngContentSelectorsOffset;
  15835. if (this._namespace !== Identifiers$1.namespaceHTML) {
  15836. this.creationInstruction(null, this._namespace);
  15837. }
  15838. // Create variable bindings
  15839. variables.forEach(function (v) { return _this.registerContextVariables(v); });
  15840. // Initiate i18n context in case:
  15841. // - this template has parent i18n context
  15842. // - or the template has i18n meta associated with it,
  15843. // but it's not initiated by the Element (e.g. <ng-template i18n>)
  15844. var initI18nContext = this.i18nContext || (isI18nRootNode(i18n) && !isSingleI18nIcu(i18n) &&
  15845. !(isSingleElementTemplate(nodes) && nodes[0].i18n === i18n));
  15846. var selfClosingI18nInstruction = hasTextChildrenOnly(nodes);
  15847. if (initI18nContext) {
  15848. this.i18nStart(null, i18n, selfClosingI18nInstruction);
  15849. }
  15850. // This is the initial pass through the nodes of this template. In this pass, we
  15851. // queue all creation mode and update mode instructions for generation in the second
  15852. // pass. It's necessary to separate the passes to ensure local refs are defined before
  15853. // resolving bindings. We also count bindings in this pass as we walk bound expressions.
  15854. visitAll(this, nodes);
  15855. // Add total binding count to pure function count so pure function instructions are
  15856. // generated with the correct slot offset when update instructions are processed.
  15857. this._pureFunctionSlots += this._bindingSlots;
  15858. // Pipes are walked in the first pass (to enqueue `pipe()` creation instructions and
  15859. // `pipeBind` update instructions), so we have to update the slot offsets manually
  15860. // to account for bindings.
  15861. this._valueConverter.updatePipeSlotOffsets(this._bindingSlots);
  15862. // Nested templates must be processed before creation instructions so template()
  15863. // instructions can be generated with the correct internal const count.
  15864. this._nestedTemplateFns.forEach(function (buildTemplateFn) { return buildTemplateFn(); });
  15865. // Output the `projectionDef` instruction when some `<ng-content>` tags are present.
  15866. // The `projectionDef` instruction is only emitted for the component template and
  15867. // is skipped for nested templates (<ng-template> tags).
  15868. if (this.level === 0 && this._ngContentReservedSlots.length) {
  15869. var parameters = [];
  15870. // By default the `projectionDef` instructions creates one slot for the wildcard
  15871. // selector if no parameters are passed. Therefore we only want to allocate a new
  15872. // array for the projection slots if the default projection slot is not sufficient.
  15873. if (this._ngContentReservedSlots.length > 1 || this._ngContentReservedSlots[0] !== '*') {
  15874. var r3ReservedSlots = this._ngContentReservedSlots.map(function (s) { return s !== '*' ? parseSelectorToR3Selector(s) : s; });
  15875. parameters.push(this.constantPool.getConstLiteral(asLiteral(r3ReservedSlots), true));
  15876. }
  15877. // Since we accumulate ngContent selectors while processing template elements,
  15878. // we *prepend* `projectionDef` to creation instructions block, to put it before
  15879. // any `projection` instructions
  15880. this.creationInstruction(null, Identifiers$1.projectionDef, parameters, /* prepend */ true);
  15881. }
  15882. if (initI18nContext) {
  15883. this.i18nEnd(null, selfClosingI18nInstruction);
  15884. }
  15885. // Generate all the creation mode instructions (e.g. resolve bindings in listeners)
  15886. var creationStatements = this._creationCodeFns.map(function (fn) { return fn(); });
  15887. // Generate all the update mode instructions (e.g. resolve property or text bindings)
  15888. var updateStatements = this._updateCodeFns.map(function (fn) { return fn(); });
  15889. // Variable declaration must occur after binding resolution so we can generate context
  15890. // instructions that build on each other.
  15891. // e.g. const b = nextContext().$implicit(); const b = nextContext();
  15892. var creationVariables = this._bindingScope.viewSnapshotStatements();
  15893. var updateVariables = this._bindingScope.variableDeclarations().concat(this._tempVariables);
  15894. var creationBlock = creationStatements.length > 0 ?
  15895. [renderFlagCheckIfStmt(1 /* Create */, creationVariables.concat(creationStatements))] :
  15896. [];
  15897. var updateBlock = updateStatements.length > 0 ?
  15898. [renderFlagCheckIfStmt(2 /* Update */, updateVariables.concat(updateStatements))] :
  15899. [];
  15900. return fn(
  15901. // i.e. (rf: RenderFlags, ctx: any)
  15902. [new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], __spread(this._prefixCode, creationBlock, updateBlock), INFERRED_TYPE, null, this.templateName);
  15903. };
  15904. // LocalResolver
  15905. TemplateDefinitionBuilder.prototype.getLocal = function (name) { return this._bindingScope.get(name); };
  15906. // LocalResolver
  15907. TemplateDefinitionBuilder.prototype.notifyImplicitReceiverUse = function () { this._bindingScope.notifyImplicitReceiverUse(); };
  15908. TemplateDefinitionBuilder.prototype.i18nTranslate = function (message, params, ref, transformFn) {
  15909. var _a;
  15910. if (params === void 0) { params = {}; }
  15911. var _ref = ref || variable(this.constantPool.uniqueName(TRANSLATION_PREFIX));
  15912. // Closure Compiler requires const names to start with `MSG_` but disallows any other const to
  15913. // start with `MSG_`. We define a variable starting with `MSG_` just for the `goog.getMsg` call
  15914. var closureVar = this.i18nGenerateClosureVar(message.id);
  15915. var _params = {};
  15916. if (params && Object.keys(params).length) {
  15917. Object.keys(params).forEach(function (key) { return _params[formatI18nPlaceholderName(key)] = params[key]; });
  15918. }
  15919. var meta = metaFromI18nMessage(message);
  15920. var content = getSerializedI18nContent(message);
  15921. var statements = getTranslationDeclStmts(_ref, closureVar, content, meta, _params, transformFn);
  15922. (_a = this.constantPool.statements).push.apply(_a, __spread(statements));
  15923. return _ref;
  15924. };
  15925. TemplateDefinitionBuilder.prototype.i18nAppendBindings = function (expressions) {
  15926. var _this = this;
  15927. if (expressions.length > 0) {
  15928. expressions.forEach(function (expression) { return _this.i18n.appendBinding(expression); });
  15929. }
  15930. };
  15931. TemplateDefinitionBuilder.prototype.i18nBindProps = function (props) {
  15932. var _this = this;
  15933. var bound = {};
  15934. Object.keys(props).forEach(function (key) {
  15935. var prop = props[key];
  15936. if (prop instanceof Text) {
  15937. bound[key] = literal(prop.value);
  15938. }
  15939. else {
  15940. var value = prop.value.visit(_this._valueConverter);
  15941. _this.allocateBindingSlots(value);
  15942. if (value instanceof Interpolation) {
  15943. var strings = value.strings, expressions = value.expressions;
  15944. var _a = _this.i18n, id = _a.id, bindings = _a.bindings;
  15945. var label = assembleI18nBoundString(strings, bindings.size, id);
  15946. _this.i18nAppendBindings(expressions);
  15947. bound[key] = literal(label);
  15948. }
  15949. }
  15950. });
  15951. return bound;
  15952. };
  15953. TemplateDefinitionBuilder.prototype.i18nGenerateClosureVar = function (messageId) {
  15954. var name;
  15955. var suffix = this.fileBasedI18nSuffix.toUpperCase();
  15956. if (this.i18nUseExternalIds) {
  15957. var prefix = getTranslationConstPrefix("EXTERNAL_");
  15958. var uniqueSuffix = this.constantPool.uniqueName(suffix);
  15959. name = "" + prefix + sanitizeIdentifier(messageId) + "$$" + uniqueSuffix;
  15960. }
  15961. else {
  15962. var prefix = getTranslationConstPrefix(suffix);
  15963. name = this.constantPool.uniqueName(prefix);
  15964. }
  15965. return variable(name);
  15966. };
  15967. TemplateDefinitionBuilder.prototype.i18nUpdateRef = function (context) {
  15968. var icus = context.icus, meta = context.meta, isRoot = context.isRoot, isResolved = context.isResolved, isEmitted = context.isEmitted;
  15969. if (isRoot && isResolved && !isEmitted && !isSingleI18nIcu(meta)) {
  15970. context.isEmitted = true;
  15971. var placeholders = context.getSerializedPlaceholders();
  15972. var icuMapping_1 = {};
  15973. var params_1 = placeholders.size ? placeholdersToParams(placeholders) : {};
  15974. if (icus.size) {
  15975. icus.forEach(function (refs, key) {
  15976. if (refs.length === 1) {
  15977. // if we have one ICU defined for a given
  15978. // placeholder - just output its reference
  15979. params_1[key] = refs[0];
  15980. }
  15981. else {
  15982. // ... otherwise we need to activate post-processing
  15983. // to replace ICU placeholders with proper values
  15984. var placeholder = wrapI18nPlaceholder("" + I18N_ICU_MAPPING_PREFIX + key);
  15985. params_1[key] = literal(placeholder);
  15986. icuMapping_1[key] = literalArr(refs);
  15987. }
  15988. });
  15989. }
  15990. // translation requires post processing in 2 cases:
  15991. // - if we have placeholders with multiple values (ex. `START_DIV`: [�#1�, �#2�, ...])
  15992. // - if we have multiple ICUs that refer to the same placeholder name
  15993. var needsPostprocessing = Array.from(placeholders.values()).some(function (value) { return value.length > 1; }) ||
  15994. Object.keys(icuMapping_1).length;
  15995. var transformFn = void 0;
  15996. if (needsPostprocessing) {
  15997. transformFn = function (raw) {
  15998. var args = [raw];
  15999. if (Object.keys(icuMapping_1).length) {
  16000. args.push(mapLiteral(icuMapping_1, true));
  16001. }
  16002. return instruction(null, Identifiers$1.i18nPostprocess, args);
  16003. };
  16004. }
  16005. this.i18nTranslate(meta, params_1, context.ref, transformFn);
  16006. }
  16007. };
  16008. TemplateDefinitionBuilder.prototype.i18nStart = function (span, meta, selfClosing) {
  16009. if (span === void 0) { span = null; }
  16010. var index = this.allocateDataSlot();
  16011. if (this.i18nContext) {
  16012. this.i18n = this.i18nContext.forkChildContext(index, this.templateIndex, meta);
  16013. }
  16014. else {
  16015. var ref_1 = variable(this.constantPool.uniqueName(TRANSLATION_PREFIX));
  16016. this.i18n = new I18nContext(index, ref_1, 0, this.templateIndex, meta);
  16017. }
  16018. // generate i18nStart instruction
  16019. var _a = this.i18n, id = _a.id, ref = _a.ref;
  16020. var params = [literal(index), ref];
  16021. if (id > 0) {
  16022. // do not push 3rd argument (sub-block id)
  16023. // into i18nStart call for top level i18n context
  16024. params.push(literal(id));
  16025. }
  16026. this.creationInstruction(span, selfClosing ? Identifiers$1.i18n : Identifiers$1.i18nStart, params);
  16027. };
  16028. TemplateDefinitionBuilder.prototype.i18nEnd = function (span, selfClosing) {
  16029. var _this = this;
  16030. if (span === void 0) { span = null; }
  16031. if (!this.i18n) {
  16032. throw new Error('i18nEnd is executed with no i18n context present');
  16033. }
  16034. if (this.i18nContext) {
  16035. this.i18nContext.reconcileChildContext(this.i18n);
  16036. this.i18nUpdateRef(this.i18nContext);
  16037. }
  16038. else {
  16039. this.i18nUpdateRef(this.i18n);
  16040. }
  16041. // setup accumulated bindings
  16042. var _a = this.i18n, index = _a.index, bindings = _a.bindings;
  16043. if (bindings.size) {
  16044. var chainBindings_1 = [];
  16045. bindings.forEach(function (binding) {
  16046. chainBindings_1.push({ sourceSpan: span, value: function () { return _this.convertPropertyBinding(binding); } });
  16047. });
  16048. this.updateInstructionChain(index, Identifiers$1.i18nExp, chainBindings_1);
  16049. this.updateInstruction(index, span, Identifiers$1.i18nApply, [literal(index)]);
  16050. }
  16051. if (!selfClosing) {
  16052. this.creationInstruction(span, Identifiers$1.i18nEnd);
  16053. }
  16054. this.i18n = null; // reset local i18n context
  16055. };
  16056. TemplateDefinitionBuilder.prototype.visitContent = function (ngContent) {
  16057. var slot = this.allocateDataSlot();
  16058. var projectionSlotIdx = this._ngContentSelectorsOffset + this._ngContentReservedSlots.length;
  16059. var parameters = [literal(slot)];
  16060. var attributes = [];
  16061. this._ngContentReservedSlots.push(ngContent.selector);
  16062. ngContent.attributes.forEach(function (attribute) {
  16063. var name = attribute.name, value = attribute.value;
  16064. if (name === NG_PROJECT_AS_ATTR_NAME) {
  16065. attributes.push.apply(attributes, __spread(getNgProjectAsLiteral(attribute)));
  16066. }
  16067. else if (name.toLowerCase() !== NG_CONTENT_SELECT_ATTR$1) {
  16068. attributes.push(literal(name), literal(value));
  16069. }
  16070. });
  16071. if (attributes.length > 0) {
  16072. parameters.push(literal(projectionSlotIdx), literalArr(attributes));
  16073. }
  16074. else if (projectionSlotIdx !== 0) {
  16075. parameters.push(literal(projectionSlotIdx));
  16076. }
  16077. this.creationInstruction(ngContent.sourceSpan, Identifiers$1.projection, parameters);
  16078. if (this.i18n) {
  16079. this.i18n.appendProjection(ngContent.i18n, slot);
  16080. }
  16081. };
  16082. TemplateDefinitionBuilder.prototype.getNamespaceInstruction = function (namespaceKey) {
  16083. switch (namespaceKey) {
  16084. case 'math':
  16085. return Identifiers$1.namespaceMathML;
  16086. case 'svg':
  16087. return Identifiers$1.namespaceSVG;
  16088. default:
  16089. return Identifiers$1.namespaceHTML;
  16090. }
  16091. };
  16092. TemplateDefinitionBuilder.prototype.addNamespaceInstruction = function (nsInstruction, element) {
  16093. this._namespace = nsInstruction;
  16094. this.creationInstruction(element.sourceSpan, nsInstruction);
  16095. };
  16096. TemplateDefinitionBuilder.prototype.visitElement = function (element) {
  16097. var _this = this;
  16098. var e_1, _a;
  16099. var elementIndex = this.allocateDataSlot();
  16100. var stylingBuilder = new StylingBuilder(literal(elementIndex), null);
  16101. var isNonBindableMode = false;
  16102. var isI18nRootElement = isI18nRootNode(element.i18n) && !isSingleI18nIcu(element.i18n);
  16103. if (isI18nRootElement && this.i18n) {
  16104. throw new Error("Could not mark an element as translatable inside of a translatable section");
  16105. }
  16106. var i18nAttrs = [];
  16107. var outputAttrs = [];
  16108. var _b = __read(splitNsName(element.name), 2), namespaceKey = _b[0], elementName = _b[1];
  16109. var isNgContainer$1 = isNgContainer(element.name);
  16110. try {
  16111. // Handle styling, i18n, ngNonBindable attributes
  16112. for (var _c = __values(element.attributes), _d = _c.next(); !_d.done; _d = _c.next()) {
  16113. var attr = _d.value;
  16114. var name_1 = attr.name, value = attr.value;
  16115. if (name_1 === NON_BINDABLE_ATTR) {
  16116. isNonBindableMode = true;
  16117. }
  16118. else if (name_1 === 'style') {
  16119. stylingBuilder.registerStyleAttr(value);
  16120. }
  16121. else if (name_1 === 'class') {
  16122. stylingBuilder.registerClassAttr(value);
  16123. }
  16124. else {
  16125. if (attr.i18n) {
  16126. // Place attributes into a separate array for i18n processing, but also keep such
  16127. // attributes in the main list to make them available for directive matching at runtime.
  16128. // TODO(FW-1248): prevent attributes duplication in `i18nAttributes` and `elementStart`
  16129. // arguments
  16130. i18nAttrs.push(attr);
  16131. }
  16132. else {
  16133. outputAttrs.push(attr);
  16134. }
  16135. }
  16136. }
  16137. }
  16138. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  16139. finally {
  16140. try {
  16141. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  16142. }
  16143. finally { if (e_1) throw e_1.error; }
  16144. }
  16145. // Match directives on non i18n attributes
  16146. this.matchDirectives(element.name, element);
  16147. // Regular element or ng-container creation mode
  16148. var parameters = [literal(elementIndex)];
  16149. if (!isNgContainer$1) {
  16150. parameters.push(literal(elementName));
  16151. }
  16152. // Add the attributes
  16153. var attributes = [];
  16154. var allOtherInputs = [];
  16155. element.inputs.forEach(function (input) {
  16156. var stylingInputWasSet = stylingBuilder.registerBoundInput(input);
  16157. if (!stylingInputWasSet) {
  16158. if (input.type === 0 /* Property */ && input.i18n) {
  16159. // Place attributes into a separate array for i18n processing, but also keep such
  16160. // attributes in the main list to make them available for directive matching at runtime.
  16161. // TODO(FW-1248): prevent attributes duplication in `i18nAttributes` and `elementStart`
  16162. // arguments
  16163. i18nAttrs.push(input);
  16164. }
  16165. else {
  16166. allOtherInputs.push(input);
  16167. }
  16168. }
  16169. });
  16170. outputAttrs.forEach(function (attr) {
  16171. if (attr.name === NG_PROJECT_AS_ATTR_NAME) {
  16172. attributes.push.apply(attributes, __spread(getNgProjectAsLiteral(attr)));
  16173. }
  16174. else {
  16175. attributes.push.apply(attributes, __spread(getAttributeNameLiterals(attr.name), [literal(attr.value)]));
  16176. }
  16177. });
  16178. // add attributes for directive and projection matching purposes
  16179. attributes.push.apply(attributes, __spread(this.prepareNonRenderAttrs(allOtherInputs, element.outputs, stylingBuilder, [], i18nAttrs)));
  16180. parameters.push(this.toAttrsParam(attributes));
  16181. // local refs (ex.: <div #foo #bar="baz">)
  16182. parameters.push(this.prepareRefsParameter(element.references));
  16183. var wasInNamespace = this._namespace;
  16184. var currentNamespace = this.getNamespaceInstruction(namespaceKey);
  16185. // If the namespace is changing now, include an instruction to change it
  16186. // during element creation.
  16187. if (currentNamespace !== wasInNamespace) {
  16188. this.addNamespaceInstruction(currentNamespace, element);
  16189. }
  16190. if (this.i18n) {
  16191. this.i18n.appendElement(element.i18n, elementIndex);
  16192. }
  16193. var hasChildren = function () {
  16194. if (!isI18nRootElement && _this.i18n) {
  16195. // we do not append text node instructions and ICUs inside i18n section,
  16196. // so we exclude them while calculating whether current element has children
  16197. return !hasTextChildrenOnly(element.children);
  16198. }
  16199. return element.children.length > 0;
  16200. };
  16201. var createSelfClosingInstruction = !stylingBuilder.hasBindings && !isNgContainer$1 &&
  16202. element.outputs.length === 0 && i18nAttrs.length === 0 && !hasChildren();
  16203. var createSelfClosingI18nInstruction = !createSelfClosingInstruction &&
  16204. !stylingBuilder.hasBindings && hasTextChildrenOnly(element.children);
  16205. if (createSelfClosingInstruction) {
  16206. this.creationInstruction(element.sourceSpan, Identifiers$1.element, trimTrailingNulls(parameters));
  16207. }
  16208. else {
  16209. this.creationInstruction(element.sourceSpan, isNgContainer$1 ? Identifiers$1.elementContainerStart : Identifiers$1.elementStart, trimTrailingNulls(parameters));
  16210. if (isNonBindableMode) {
  16211. this.creationInstruction(element.sourceSpan, Identifiers$1.disableBindings);
  16212. }
  16213. // process i18n element attributes
  16214. if (i18nAttrs.length) {
  16215. var hasBindings_1 = false;
  16216. var i18nAttrArgs_1 = [];
  16217. var bindings_1 = [];
  16218. i18nAttrs.forEach(function (attr) {
  16219. var message = attr.i18n;
  16220. if (attr instanceof TextAttribute) {
  16221. i18nAttrArgs_1.push(literal(attr.name), _this.i18nTranslate(message));
  16222. }
  16223. else {
  16224. var converted = attr.value.visit(_this._valueConverter);
  16225. _this.allocateBindingSlots(converted);
  16226. if (converted instanceof Interpolation) {
  16227. var placeholders = assembleBoundTextPlaceholders(message);
  16228. var params = placeholdersToParams(placeholders);
  16229. i18nAttrArgs_1.push(literal(attr.name), _this.i18nTranslate(message, params));
  16230. converted.expressions.forEach(function (expression) {
  16231. hasBindings_1 = true;
  16232. bindings_1.push({
  16233. sourceSpan: element.sourceSpan,
  16234. value: function () { return _this.convertExpressionBinding(expression); }
  16235. });
  16236. });
  16237. }
  16238. }
  16239. });
  16240. if (bindings_1.length) {
  16241. this.updateInstructionChain(elementIndex, Identifiers$1.i18nExp, bindings_1);
  16242. }
  16243. if (i18nAttrArgs_1.length) {
  16244. var index = literal(this.allocateDataSlot());
  16245. var args = this.constantPool.getConstLiteral(literalArr(i18nAttrArgs_1), true);
  16246. this.creationInstruction(element.sourceSpan, Identifiers$1.i18nAttributes, [index, args]);
  16247. if (hasBindings_1) {
  16248. this.updateInstruction(elementIndex, element.sourceSpan, Identifiers$1.i18nApply, [index]);
  16249. }
  16250. }
  16251. }
  16252. // The style bindings code is placed into two distinct blocks within the template function AOT
  16253. // code: creation and update. The creation code contains the `styling` instructions
  16254. // which will apply the collected binding values to the element. `styling` is
  16255. // designed to run inside of `elementStart` and `elementEnd`. The update instructions
  16256. // (things like `styleProp`, `classProp`, etc..) are applied later on in this
  16257. // file
  16258. this.processStylingInstruction(elementIndex, stylingBuilder.buildStylingInstruction(element.sourceSpan, this.constantPool), true);
  16259. // Generate Listeners (outputs)
  16260. element.outputs.forEach(function (outputAst) {
  16261. _this.creationInstruction(outputAst.sourceSpan, Identifiers$1.listener, _this.prepareListenerParameter(element.name, outputAst, elementIndex));
  16262. });
  16263. // Note: it's important to keep i18n/i18nStart instructions after i18nAttributes and
  16264. // listeners, to make sure i18nAttributes instruction targets current element at runtime.
  16265. if (isI18nRootElement) {
  16266. this.i18nStart(element.sourceSpan, element.i18n, createSelfClosingI18nInstruction);
  16267. }
  16268. }
  16269. // the code here will collect all update-level styling instructions and add them to the
  16270. // update block of the template function AOT code. Instructions like `styleProp`,
  16271. // `styleMap`, `classMap`, `classProp` and `stylingApply`
  16272. // are all generated and assigned in the code below.
  16273. var stylingInstructions = stylingBuilder.buildUpdateLevelInstructions(this._valueConverter);
  16274. var limit = stylingInstructions.length - 1;
  16275. for (var i = 0; i <= limit; i++) {
  16276. var instruction_1 = stylingInstructions[i];
  16277. this._bindingSlots += instruction_1.allocateBindingSlots;
  16278. this.processStylingInstruction(elementIndex, instruction_1, false);
  16279. }
  16280. // the reason why `undefined` is used is because the renderer understands this as a
  16281. // special value to symbolize that there is no RHS to this binding
  16282. // TODO (matsko): revisit this once FW-959 is approached
  16283. var emptyValueBindInstruction = literal(undefined);
  16284. var propertyBindings = [];
  16285. var attributeBindings = [];
  16286. // Generate element input bindings
  16287. allOtherInputs.forEach(function (input) {
  16288. var inputType = input.type;
  16289. if (inputType === 4 /* Animation */) {
  16290. var value_1 = input.value.visit(_this._valueConverter);
  16291. // animation bindings can be presented in the following formats:
  16292. // 1. [@binding]="fooExp"
  16293. // 2. [@binding]="{value:fooExp, params:{...}}"
  16294. // 3. [@binding]
  16295. // 4. @binding
  16296. // All formats will be valid for when a synthetic binding is created.
  16297. // The reasoning for this is because the renderer should get each
  16298. // synthetic binding value in the order of the array that they are
  16299. // defined in...
  16300. var hasValue_1 = value_1 instanceof LiteralPrimitive ? !!value_1.value : true;
  16301. _this.allocateBindingSlots(value_1);
  16302. propertyBindings.push({
  16303. name: prepareSyntheticPropertyName(input.name),
  16304. sourceSpan: input.sourceSpan,
  16305. value: function () { return hasValue_1 ? _this.convertPropertyBinding(value_1) : emptyValueBindInstruction; }
  16306. });
  16307. }
  16308. else {
  16309. // we must skip attributes with associated i18n context, since these attributes are handled
  16310. // separately and corresponding `i18nExp` and `i18nApply` instructions will be generated
  16311. if (input.i18n)
  16312. return;
  16313. var value_2 = input.value.visit(_this._valueConverter);
  16314. if (value_2 !== undefined) {
  16315. var params_2 = [];
  16316. var _a = __read(splitNsName(input.name), 2), attrNamespace = _a[0], attrName_1 = _a[1];
  16317. var isAttributeBinding = inputType === 1 /* Attribute */;
  16318. var sanitizationRef = resolveSanitizationFn(input.securityContext, isAttributeBinding);
  16319. if (sanitizationRef)
  16320. params_2.push(sanitizationRef);
  16321. if (attrNamespace) {
  16322. var namespaceLiteral = literal(attrNamespace);
  16323. if (sanitizationRef) {
  16324. params_2.push(namespaceLiteral);
  16325. }
  16326. else {
  16327. // If there wasn't a sanitization ref, we need to add
  16328. // an extra param so that we can pass in the namespace.
  16329. params_2.push(literal(null), namespaceLiteral);
  16330. }
  16331. }
  16332. _this.allocateBindingSlots(value_2);
  16333. if (inputType === 0 /* Property */) {
  16334. if (value_2 instanceof Interpolation) {
  16335. // prop="{{value}}" and friends
  16336. _this.interpolatedUpdateInstruction(getPropertyInterpolationExpression(value_2), elementIndex, attrName_1, input, value_2, params_2);
  16337. }
  16338. else {
  16339. // [prop]="value"
  16340. // Collect all the properties so that we can chain into a single function at the end.
  16341. propertyBindings.push({
  16342. name: attrName_1,
  16343. sourceSpan: input.sourceSpan,
  16344. value: function () { return _this.convertPropertyBinding(value_2); }, params: params_2
  16345. });
  16346. }
  16347. }
  16348. else if (inputType === 1 /* Attribute */) {
  16349. if (value_2 instanceof Interpolation && getInterpolationArgsLength(value_2) > 1) {
  16350. // attr.name="text{{value}}" and friends
  16351. _this.interpolatedUpdateInstruction(getAttributeInterpolationExpression(value_2), elementIndex, attrName_1, input, value_2, params_2);
  16352. }
  16353. else {
  16354. var boundValue_1 = value_2 instanceof Interpolation ? value_2.expressions[0] : value_2;
  16355. // [attr.name]="value" or attr.name="{{value}}"
  16356. // Collect the attribute bindings so that they can be chained at the end.
  16357. attributeBindings.push({
  16358. name: attrName_1,
  16359. sourceSpan: input.sourceSpan,
  16360. value: function () { return _this.convertPropertyBinding(boundValue_1); }, params: params_2
  16361. });
  16362. }
  16363. }
  16364. else {
  16365. // class prop
  16366. _this.updateInstruction(elementIndex, input.sourceSpan, Identifiers$1.classProp, function () {
  16367. return __spread([
  16368. literal(elementIndex), literal(attrName_1), _this.convertPropertyBinding(value_2)
  16369. ], params_2);
  16370. });
  16371. }
  16372. }
  16373. }
  16374. });
  16375. if (propertyBindings.length > 0) {
  16376. this.updateInstructionChain(elementIndex, Identifiers$1.property, propertyBindings);
  16377. }
  16378. if (attributeBindings.length > 0) {
  16379. this.updateInstructionChain(elementIndex, Identifiers$1.attribute, attributeBindings);
  16380. }
  16381. // Traverse element child nodes
  16382. visitAll(this, element.children);
  16383. if (!isI18nRootElement && this.i18n) {
  16384. this.i18n.appendElement(element.i18n, elementIndex, true);
  16385. }
  16386. if (!createSelfClosingInstruction) {
  16387. // Finish element construction mode.
  16388. var span = element.endSourceSpan || element.sourceSpan;
  16389. if (isI18nRootElement) {
  16390. this.i18nEnd(span, createSelfClosingI18nInstruction);
  16391. }
  16392. if (isNonBindableMode) {
  16393. this.creationInstruction(span, Identifiers$1.enableBindings);
  16394. }
  16395. this.creationInstruction(span, isNgContainer$1 ? Identifiers$1.elementContainerEnd : Identifiers$1.elementEnd);
  16396. }
  16397. };
  16398. /**
  16399. * Adds an update instruction for an interpolated property or attribute, such as
  16400. * `prop="{{value}}"` or `attr.title="{{value}}"`
  16401. */
  16402. TemplateDefinitionBuilder.prototype.interpolatedUpdateInstruction = function (instruction, elementIndex, attrName, input, value, params) {
  16403. var _this = this;
  16404. this.updateInstruction(elementIndex, input.sourceSpan, instruction, function () { return __spread([literal(attrName)], _this.getUpdateInstructionArguments(value), params); });
  16405. };
  16406. TemplateDefinitionBuilder.prototype.visitTemplate = function (template) {
  16407. var _this = this;
  16408. var NG_TEMPLATE_TAG_NAME = 'ng-template';
  16409. var templateIndex = this.allocateDataSlot();
  16410. if (this.i18n) {
  16411. this.i18n.appendTemplate(template.i18n, templateIndex);
  16412. }
  16413. var tagName = sanitizeIdentifier(template.tagName || '');
  16414. var contextName = "" + this.contextName + (tagName ? '_' + tagName : '') + "_" + templateIndex;
  16415. var templateName = contextName + "_Template";
  16416. var parameters = [
  16417. literal(templateIndex),
  16418. variable(templateName),
  16419. // We don't care about the tag's namespace here, because we infer
  16420. // it based on the parent nodes inside the template instruction.
  16421. literal(template.tagName ? splitNsName(template.tagName)[1] : template.tagName),
  16422. ];
  16423. // find directives matching on a given <ng-template> node
  16424. this.matchDirectives(NG_TEMPLATE_TAG_NAME, template);
  16425. // prepare attributes parameter (including attributes used for directive matching)
  16426. var attrsExprs = [];
  16427. template.attributes.forEach(function (a) { attrsExprs.push(asLiteral(a.name), asLiteral(a.value)); });
  16428. attrsExprs.push.apply(attrsExprs, __spread(this.prepareNonRenderAttrs(template.inputs, template.outputs, undefined, template.templateAttrs)));
  16429. parameters.push(this.toAttrsParam(attrsExprs));
  16430. // local refs (ex.: <ng-template #foo>)
  16431. if (template.references && template.references.length) {
  16432. parameters.push(this.prepareRefsParameter(template.references));
  16433. parameters.push(importExpr(Identifiers$1.templateRefExtractor));
  16434. }
  16435. // Create the template function
  16436. 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);
  16437. // Nested templates must not be visited until after their parent templates have completed
  16438. // processing, so they are queued here until after the initial pass. Otherwise, we wouldn't
  16439. // be able to support bindings in nested templates to local refs that occur after the
  16440. // template definition. e.g. <div *ngIf="showing">{{ foo }}</div> <div #foo></div>
  16441. this._nestedTemplateFns.push(function () {
  16442. var _a;
  16443. var templateFunctionExpr = templateVisitor.buildTemplateFunction(template.children, template.variables, _this._ngContentReservedSlots.length + _this._ngContentSelectorsOffset, template.i18n);
  16444. _this.constantPool.statements.push(templateFunctionExpr.toDeclStmt(templateName, null));
  16445. if (templateVisitor._ngContentReservedSlots.length) {
  16446. (_a = _this._ngContentReservedSlots).push.apply(_a, __spread(templateVisitor._ngContentReservedSlots));
  16447. }
  16448. });
  16449. // e.g. template(1, MyComp_Template_1)
  16450. this.creationInstruction(template.sourceSpan, Identifiers$1.templateCreate, function () {
  16451. parameters.splice(2, 0, literal(templateVisitor.getConstCount()), literal(templateVisitor.getVarCount()));
  16452. return trimTrailingNulls(parameters);
  16453. });
  16454. // handle property bindings e.g. ɵɵproperty('ngForOf', ctx.items), et al;
  16455. this.templatePropertyBindings(templateIndex, template.templateAttrs);
  16456. // Only add normal input/output binding instructions on explicit ng-template elements.
  16457. if (template.tagName === NG_TEMPLATE_TAG_NAME) {
  16458. // Add the input bindings
  16459. this.templatePropertyBindings(templateIndex, template.inputs);
  16460. // Generate listeners for directive output
  16461. template.outputs.forEach(function (outputAst) {
  16462. _this.creationInstruction(outputAst.sourceSpan, Identifiers$1.listener, _this.prepareListenerParameter('ng_template', outputAst, templateIndex));
  16463. });
  16464. }
  16465. };
  16466. TemplateDefinitionBuilder.prototype.visitBoundText = function (text) {
  16467. var _this = this;
  16468. if (this.i18n) {
  16469. var value_3 = text.value.visit(this._valueConverter);
  16470. this.allocateBindingSlots(value_3);
  16471. if (value_3 instanceof Interpolation) {
  16472. this.i18n.appendBoundText(text.i18n);
  16473. this.i18nAppendBindings(value_3.expressions);
  16474. }
  16475. return;
  16476. }
  16477. var nodeIndex = this.allocateDataSlot();
  16478. this.creationInstruction(text.sourceSpan, Identifiers$1.text, [literal(nodeIndex)]);
  16479. var value = text.value.visit(this._valueConverter);
  16480. this.allocateBindingSlots(value);
  16481. if (value instanceof Interpolation) {
  16482. this.updateInstruction(nodeIndex, text.sourceSpan, getTextInterpolationExpression(value), function () { return _this.getUpdateInstructionArguments(value); });
  16483. }
  16484. else {
  16485. this.updateInstruction(nodeIndex, text.sourceSpan, Identifiers$1.textBinding, function () { return [_this.convertPropertyBinding(value)]; });
  16486. }
  16487. };
  16488. TemplateDefinitionBuilder.prototype.visitText = function (text) {
  16489. // when a text element is located within a translatable
  16490. // block, we exclude this text element from instructions set,
  16491. // since it will be captured in i18n content and processed at runtime
  16492. if (!this.i18n) {
  16493. this.creationInstruction(text.sourceSpan, Identifiers$1.text, [literal(this.allocateDataSlot()), literal(text.value)]);
  16494. }
  16495. };
  16496. TemplateDefinitionBuilder.prototype.visitIcu = function (icu) {
  16497. var initWasInvoked = false;
  16498. // if an ICU was created outside of i18n block, we still treat
  16499. // it as a translatable entity and invoke i18nStart and i18nEnd
  16500. // to generate i18n context and the necessary instructions
  16501. if (!this.i18n) {
  16502. initWasInvoked = true;
  16503. this.i18nStart(null, icu.i18n, true);
  16504. }
  16505. var i18n = this.i18n;
  16506. var vars = this.i18nBindProps(icu.vars);
  16507. var placeholders = this.i18nBindProps(icu.placeholders);
  16508. // output ICU directly and keep ICU reference in context
  16509. var message = icu.i18n;
  16510. var transformFn = function (raw) {
  16511. return instruction(null, Identifiers$1.i18nPostprocess, [raw, mapLiteral(vars, true)]);
  16512. };
  16513. // in case the whole i18n message is a single ICU - we do not need to
  16514. // create a separate top-level translation, we can use the root ref instead
  16515. // and make this ICU a top-level translation
  16516. if (isSingleI18nIcu(i18n.meta)) {
  16517. this.i18nTranslate(message, placeholders, i18n.ref, transformFn);
  16518. }
  16519. else {
  16520. // output ICU directly and keep ICU reference in context
  16521. var ref = this.i18nTranslate(message, placeholders, undefined, transformFn);
  16522. i18n.appendIcu(icuFromI18nMessage(message).name, ref);
  16523. }
  16524. if (initWasInvoked) {
  16525. this.i18nEnd(null, true);
  16526. }
  16527. return null;
  16528. };
  16529. TemplateDefinitionBuilder.prototype.allocateDataSlot = function () { return this._dataIndex++; };
  16530. TemplateDefinitionBuilder.prototype.getConstCount = function () { return this._dataIndex; };
  16531. TemplateDefinitionBuilder.prototype.getVarCount = function () { return this._pureFunctionSlots; };
  16532. TemplateDefinitionBuilder.prototype.getNgContentSelectors = function () {
  16533. return this._ngContentReservedSlots.length ?
  16534. this.constantPool.getConstLiteral(asLiteral(this._ngContentReservedSlots), true) :
  16535. null;
  16536. };
  16537. TemplateDefinitionBuilder.prototype.bindingContext = function () { return "" + this._bindingContext++; };
  16538. TemplateDefinitionBuilder.prototype.templatePropertyBindings = function (templateIndex, attrs) {
  16539. var _this = this;
  16540. var propertyBindings = [];
  16541. attrs.forEach(function (input) {
  16542. if (input instanceof BoundAttribute) {
  16543. var value_4 = input.value.visit(_this._valueConverter);
  16544. if (value_4 !== undefined) {
  16545. _this.allocateBindingSlots(value_4);
  16546. propertyBindings.push({
  16547. name: input.name,
  16548. sourceSpan: input.sourceSpan,
  16549. value: function () { return _this.convertPropertyBinding(value_4); }
  16550. });
  16551. }
  16552. }
  16553. });
  16554. if (propertyBindings.length > 0) {
  16555. this.updateInstructionChain(templateIndex, Identifiers$1.property, propertyBindings);
  16556. }
  16557. };
  16558. // Bindings must only be resolved after all local refs have been visited, so all
  16559. // instructions are queued in callbacks that execute once the initial pass has completed.
  16560. // Otherwise, we wouldn't be able to support local refs that are defined after their
  16561. // bindings. e.g. {{ foo }} <div #foo></div>
  16562. TemplateDefinitionBuilder.prototype.instructionFn = function (fns, span, reference, paramsOrFn, prepend) {
  16563. if (prepend === void 0) { prepend = false; }
  16564. fns[prepend ? 'unshift' : 'push'](function () {
  16565. var params = Array.isArray(paramsOrFn) ? paramsOrFn : paramsOrFn();
  16566. return instruction(span, reference, params).toStmt();
  16567. });
  16568. };
  16569. TemplateDefinitionBuilder.prototype.processStylingInstruction = function (elementIndex, instruction, createMode) {
  16570. var _this = this;
  16571. if (instruction) {
  16572. var paramsFn = function () { return instruction.buildParams(function (value) { return _this.convertPropertyBinding(value); }); };
  16573. if (createMode) {
  16574. this.creationInstruction(instruction.sourceSpan, instruction.reference, paramsFn);
  16575. }
  16576. else {
  16577. this.updateInstruction(elementIndex, instruction.sourceSpan, instruction.reference, paramsFn);
  16578. }
  16579. }
  16580. };
  16581. TemplateDefinitionBuilder.prototype.creationInstruction = function (span, reference, paramsOrFn, prepend) {
  16582. this.instructionFn(this._creationCodeFns, span, reference, paramsOrFn || [], prepend);
  16583. };
  16584. TemplateDefinitionBuilder.prototype.updateInstruction = function (nodeIndex, span, reference, paramsOrFn) {
  16585. this.addSelectInstructionIfNecessary(nodeIndex, span);
  16586. this.instructionFn(this._updateCodeFns, span, reference, paramsOrFn || []);
  16587. };
  16588. TemplateDefinitionBuilder.prototype.updateInstructionChain = function (nodeIndex, reference, bindings) {
  16589. var span = bindings.length ? bindings[0].sourceSpan : null;
  16590. this.addSelectInstructionIfNecessary(nodeIndex, span);
  16591. this._updateCodeFns.push(function () {
  16592. var calls = bindings.map(function (property) {
  16593. var fnParams = __spread([property.value()], (property.params || []));
  16594. if (property.name) {
  16595. fnParams.unshift(literal(property.name));
  16596. }
  16597. return fnParams;
  16598. });
  16599. return chainedInstruction(span, reference, calls).toStmt();
  16600. });
  16601. };
  16602. TemplateDefinitionBuilder.prototype.addSelectInstructionIfNecessary = function (nodeIndex, span) {
  16603. if (this._lastNodeIndexWithFlush < nodeIndex) {
  16604. if (nodeIndex > 0) {
  16605. this.instructionFn(this._updateCodeFns, span, Identifiers$1.select, [literal(nodeIndex)]);
  16606. }
  16607. this._lastNodeIndexWithFlush = nodeIndex;
  16608. }
  16609. };
  16610. TemplateDefinitionBuilder.prototype.allocatePureFunctionSlots = function (numSlots) {
  16611. var originalSlots = this._pureFunctionSlots;
  16612. this._pureFunctionSlots += numSlots;
  16613. return originalSlots;
  16614. };
  16615. TemplateDefinitionBuilder.prototype.allocateBindingSlots = function (value) {
  16616. this._bindingSlots += value instanceof Interpolation ? value.expressions.length : 1;
  16617. };
  16618. /**
  16619. * Gets an expression that refers to the implicit receiver. The implicit
  16620. * receiver is always the root level context.
  16621. */
  16622. TemplateDefinitionBuilder.prototype.getImplicitReceiverExpr = function () {
  16623. if (this._implicitReceiverExpr) {
  16624. return this._implicitReceiverExpr;
  16625. }
  16626. return this._implicitReceiverExpr = this.level === 0 ?
  16627. variable(CONTEXT_NAME) :
  16628. this._bindingScope.getOrCreateSharedContextVar(0);
  16629. };
  16630. TemplateDefinitionBuilder.prototype.convertExpressionBinding = function (value) {
  16631. var convertedPropertyBinding = convertPropertyBinding(this, this.getImplicitReceiverExpr(), value, this.bindingContext(), BindingForm.TrySimple);
  16632. return convertedPropertyBinding.currValExpr;
  16633. };
  16634. TemplateDefinitionBuilder.prototype.convertPropertyBinding = function (value) {
  16635. var _a;
  16636. var interpolationFn = value instanceof Interpolation ? interpolate : function () { return error('Unexpected interpolation'); };
  16637. var convertedPropertyBinding = convertPropertyBinding(this, this.getImplicitReceiverExpr(), value, this.bindingContext(), BindingForm.TrySimple, interpolationFn);
  16638. var valExpr = convertedPropertyBinding.currValExpr;
  16639. (_a = this._tempVariables).push.apply(_a, __spread(convertedPropertyBinding.stmts));
  16640. return valExpr;
  16641. };
  16642. /**
  16643. * Gets a list of argument expressions to pass to an update instruction expression. Also updates
  16644. * the temp variables state with temp variables that were identified as needing to be created
  16645. * while visiting the arguments.
  16646. * @param value The original expression we will be resolving an arguments list from.
  16647. */
  16648. TemplateDefinitionBuilder.prototype.getUpdateInstructionArguments = function (value) {
  16649. var _a;
  16650. var _b = convertUpdateArguments(this, this.getImplicitReceiverExpr(), value, this.bindingContext()), args = _b.args, stmts = _b.stmts;
  16651. (_a = this._tempVariables).push.apply(_a, __spread(stmts));
  16652. return args;
  16653. };
  16654. TemplateDefinitionBuilder.prototype.matchDirectives = function (tagName, elOrTpl) {
  16655. var _this = this;
  16656. if (this.directiveMatcher) {
  16657. var selector = createCssSelector(tagName, getAttrsForDirectiveMatching(elOrTpl));
  16658. this.directiveMatcher.match(selector, function (cssSelector, staticType) { _this.directives.add(staticType); });
  16659. }
  16660. };
  16661. /**
  16662. * Prepares all attribute expression values for the `TAttributes` array.
  16663. *
  16664. * The purpose of this function is to properly construct an attributes array that
  16665. * is passed into the `elementStart` (or just `element`) functions. Because there
  16666. * are many different types of attributes, the array needs to be constructed in a
  16667. * special way so that `elementStart` can properly evaluate them.
  16668. *
  16669. * The format looks like this:
  16670. *
  16671. * ```
  16672. * attrs = [prop, value, prop2, value2,
  16673. * CLASSES, class1, class2,
  16674. * STYLES, style1, value1, style2, value2,
  16675. * BINDINGS, name1, name2, name3,
  16676. * TEMPLATE, name4, name5, name6,
  16677. * I18N, name7, name8, ...]
  16678. * ```
  16679. *
  16680. * Note that this function will fully ignore all synthetic (@foo) attribute values
  16681. * because those values are intended to always be generated as property instructions.
  16682. */
  16683. TemplateDefinitionBuilder.prototype.prepareNonRenderAttrs = function (inputs, outputs, styles, templateAttrs, i18nAttrs) {
  16684. if (templateAttrs === void 0) { templateAttrs = []; }
  16685. if (i18nAttrs === void 0) { i18nAttrs = []; }
  16686. var alreadySeen = new Set();
  16687. var attrExprs = [];
  16688. function addAttrExpr(key, value) {
  16689. if (typeof key === 'string') {
  16690. if (!alreadySeen.has(key)) {
  16691. attrExprs.push.apply(attrExprs, __spread(getAttributeNameLiterals(key)));
  16692. value !== undefined && attrExprs.push(value);
  16693. alreadySeen.add(key);
  16694. }
  16695. }
  16696. else {
  16697. attrExprs.push(literal(key));
  16698. }
  16699. }
  16700. // it's important that this occurs before BINDINGS and TEMPLATE because once `elementStart`
  16701. // comes across the BINDINGS or TEMPLATE markers then it will continue reading each value as
  16702. // as single property value cell by cell.
  16703. if (styles) {
  16704. styles.populateInitialStylingAttrs(attrExprs);
  16705. }
  16706. if (inputs.length || outputs.length) {
  16707. var attrsStartIndex = attrExprs.length;
  16708. for (var i = 0; i < inputs.length; i++) {
  16709. var input = inputs[i];
  16710. if (input.type !== 4 /* Animation */) {
  16711. addAttrExpr(input.name);
  16712. }
  16713. }
  16714. for (var i = 0; i < outputs.length; i++) {
  16715. var output = outputs[i];
  16716. if (output.type !== 1 /* Animation */) {
  16717. addAttrExpr(output.name);
  16718. }
  16719. }
  16720. // this is a cheap way of adding the marker only after all the input/output
  16721. // values have been filtered (by not including the animation ones) and added
  16722. // to the expressions. The marker is important because it tells the runtime
  16723. // code that this is where attributes without values start...
  16724. if (attrExprs.length) {
  16725. attrExprs.splice(attrsStartIndex, 0, literal(3 /* Bindings */));
  16726. }
  16727. }
  16728. if (templateAttrs.length) {
  16729. attrExprs.push(literal(4 /* Template */));
  16730. templateAttrs.forEach(function (attr) { return addAttrExpr(attr.name); });
  16731. }
  16732. if (i18nAttrs.length) {
  16733. attrExprs.push(literal(6 /* I18n */));
  16734. i18nAttrs.forEach(function (attr) { return addAttrExpr(attr.name); });
  16735. }
  16736. return attrExprs;
  16737. };
  16738. TemplateDefinitionBuilder.prototype.toAttrsParam = function (attrsExprs) {
  16739. return attrsExprs.length > 0 ?
  16740. this.constantPool.getConstLiteral(literalArr(attrsExprs), true) :
  16741. TYPED_NULL_EXPR;
  16742. };
  16743. TemplateDefinitionBuilder.prototype.prepareRefsParameter = function (references) {
  16744. var _this = this;
  16745. if (!references || references.length === 0) {
  16746. return TYPED_NULL_EXPR;
  16747. }
  16748. var refsParam = flatten(references.map(function (reference) {
  16749. var slot = _this.allocateDataSlot();
  16750. // Generate the update temporary.
  16751. var variableName = _this._bindingScope.freshReferenceName();
  16752. var retrievalLevel = _this.level;
  16753. var lhs = variable(variableName);
  16754. _this._bindingScope.set(retrievalLevel, reference.name, lhs, 0 /* DEFAULT */, function (scope, relativeLevel) {
  16755. // e.g. nextContext(2);
  16756. var nextContextStmt = relativeLevel > 0 ? [generateNextContextExpr(relativeLevel).toStmt()] : [];
  16757. // e.g. const $foo$ = reference(1);
  16758. var refExpr = lhs.set(importExpr(Identifiers$1.reference).callFn([literal(slot)]));
  16759. return nextContextStmt.concat(refExpr.toConstDecl());
  16760. }, true);
  16761. return [reference.name, reference.value];
  16762. }));
  16763. return this.constantPool.getConstLiteral(asLiteral(refsParam), true);
  16764. };
  16765. TemplateDefinitionBuilder.prototype.prepareListenerParameter = function (tagName, outputAst, index) {
  16766. var _this = this;
  16767. return function () {
  16768. var eventName = outputAst.name;
  16769. var bindingFnName = outputAst.type === 1 /* Animation */ ?
  16770. // synthetic @listener.foo values are treated the exact same as are standard listeners
  16771. prepareSyntheticListenerFunctionName(eventName, outputAst.phase) :
  16772. sanitizeIdentifier(eventName);
  16773. var handlerName = _this.templateName + "_" + tagName + "_" + bindingFnName + "_" + index + "_listener";
  16774. var scope = _this._bindingScope.nestedScope(_this._bindingScope.bindingLevel);
  16775. return prepareEventListenerParameters(outputAst, handlerName, scope);
  16776. };
  16777. };
  16778. return TemplateDefinitionBuilder;
  16779. }());
  16780. var ValueConverter = /** @class */ (function (_super) {
  16781. __extends(ValueConverter, _super);
  16782. function ValueConverter(constantPool, allocateSlot, allocatePureFunctionSlots, definePipe) {
  16783. var _this = _super.call(this) || this;
  16784. _this.constantPool = constantPool;
  16785. _this.allocateSlot = allocateSlot;
  16786. _this.allocatePureFunctionSlots = allocatePureFunctionSlots;
  16787. _this.definePipe = definePipe;
  16788. _this._pipeBindExprs = [];
  16789. return _this;
  16790. }
  16791. // AstMemoryEfficientTransformer
  16792. ValueConverter.prototype.visitPipe = function (pipe, context) {
  16793. // Allocate a slot to create the pipe
  16794. var slot = this.allocateSlot();
  16795. var slotPseudoLocal = "PIPE:" + slot;
  16796. // Allocate one slot for the result plus one slot per pipe argument
  16797. var pureFunctionSlot = this.allocatePureFunctionSlots(2 + pipe.args.length);
  16798. var target = new PropertyRead(pipe.span, new ImplicitReceiver(pipe.span), slotPseudoLocal);
  16799. var _a = pipeBindingCallInfo(pipe.args), identifier = _a.identifier, isVarLength = _a.isVarLength;
  16800. this.definePipe(pipe.name, slotPseudoLocal, slot, importExpr(identifier));
  16801. var args = __spread([pipe.exp], pipe.args);
  16802. var convertedArgs = isVarLength ? this.visitAll([new LiteralArray(pipe.span, args)]) : this.visitAll(args);
  16803. var pipeBindExpr = new FunctionCall(pipe.span, target, __spread([
  16804. new LiteralPrimitive(pipe.span, slot),
  16805. new LiteralPrimitive(pipe.span, pureFunctionSlot)
  16806. ], convertedArgs));
  16807. this._pipeBindExprs.push(pipeBindExpr);
  16808. return pipeBindExpr;
  16809. };
  16810. ValueConverter.prototype.updatePipeSlotOffsets = function (bindingSlots) {
  16811. this._pipeBindExprs.forEach(function (pipe) {
  16812. // update the slot offset arg (index 1) to account for binding slots
  16813. var slotOffset = pipe.args[1];
  16814. slotOffset.value += bindingSlots;
  16815. });
  16816. };
  16817. ValueConverter.prototype.visitLiteralArray = function (array, context) {
  16818. var _this = this;
  16819. return new BuiltinFunctionCall(array.span, this.visitAll(array.expressions), function (values) {
  16820. // If the literal has calculated (non-literal) elements transform it into
  16821. // calls to literal factories that compose the literal and will cache intermediate
  16822. // values. Otherwise, just return an literal array that contains the values.
  16823. var literal = literalArr(values);
  16824. return values.every(function (a) { return a.isConstant(); }) ?
  16825. _this.constantPool.getConstLiteral(literal, true) :
  16826. getLiteralFactory(_this.constantPool, literal, _this.allocatePureFunctionSlots);
  16827. });
  16828. };
  16829. ValueConverter.prototype.visitLiteralMap = function (map, context) {
  16830. var _this = this;
  16831. return new BuiltinFunctionCall(map.span, this.visitAll(map.values), function (values) {
  16832. // If the literal has calculated (non-literal) elements transform it into
  16833. // calls to literal factories that compose the literal and will cache intermediate
  16834. // values. Otherwise, just return an literal array that contains the values.
  16835. var literal = literalMap(values.map(function (value, index) { return ({ key: map.keys[index].key, value: value, quoted: map.keys[index].quoted }); }));
  16836. return values.every(function (a) { return a.isConstant(); }) ?
  16837. _this.constantPool.getConstLiteral(literal, true) :
  16838. getLiteralFactory(_this.constantPool, literal, _this.allocatePureFunctionSlots);
  16839. });
  16840. };
  16841. return ValueConverter;
  16842. }(AstMemoryEfficientTransformer));
  16843. // Pipes always have at least one parameter, the value they operate on
  16844. var pipeBindingIdentifiers = [Identifiers$1.pipeBind1, Identifiers$1.pipeBind2, Identifiers$1.pipeBind3, Identifiers$1.pipeBind4];
  16845. function pipeBindingCallInfo(args) {
  16846. var identifier = pipeBindingIdentifiers[args.length];
  16847. return {
  16848. identifier: identifier || Identifiers$1.pipeBindV,
  16849. isVarLength: !identifier,
  16850. };
  16851. }
  16852. var pureFunctionIdentifiers = [
  16853. Identifiers$1.pureFunction0, Identifiers$1.pureFunction1, Identifiers$1.pureFunction2, Identifiers$1.pureFunction3, Identifiers$1.pureFunction4,
  16854. Identifiers$1.pureFunction5, Identifiers$1.pureFunction6, Identifiers$1.pureFunction7, Identifiers$1.pureFunction8
  16855. ];
  16856. function pureFunctionCallInfo(args) {
  16857. var identifier = pureFunctionIdentifiers[args.length];
  16858. return {
  16859. identifier: identifier || Identifiers$1.pureFunctionV,
  16860. isVarLength: !identifier,
  16861. };
  16862. }
  16863. function instruction(span, reference, params) {
  16864. return importExpr(reference, null, span).callFn(params, span);
  16865. }
  16866. function chainedInstruction(span, reference, calls) {
  16867. var expression = importExpr(reference, null, span);
  16868. if (calls.length > 0) {
  16869. for (var i = 0; i < calls.length; i++) {
  16870. expression = expression.callFn(calls[i], span);
  16871. }
  16872. }
  16873. else {
  16874. // Add a blank invocation, in case the `calls` array is empty.
  16875. expression = expression.callFn([], span);
  16876. }
  16877. return expression;
  16878. }
  16879. // e.g. x(2);
  16880. function generateNextContextExpr(relativeLevelDiff) {
  16881. return importExpr(Identifiers$1.nextContext)
  16882. .callFn(relativeLevelDiff > 1 ? [literal(relativeLevelDiff)] : []);
  16883. }
  16884. function getLiteralFactory(constantPool, literal$1, allocateSlots) {
  16885. var _a = constantPool.getLiteralFactory(literal$1), literalFactory = _a.literalFactory, literalFactoryArguments = _a.literalFactoryArguments;
  16886. // Allocate 1 slot for the result plus 1 per argument
  16887. var startSlot = allocateSlots(1 + literalFactoryArguments.length);
  16888. literalFactoryArguments.length > 0 || error("Expected arguments to a literal factory function");
  16889. var _b = pureFunctionCallInfo(literalFactoryArguments), identifier = _b.identifier, isVarLength = _b.isVarLength;
  16890. // Literal factories are pure functions that only need to be re-invoked when the parameters
  16891. // change.
  16892. var args = [
  16893. literal(startSlot),
  16894. literalFactory,
  16895. ];
  16896. if (isVarLength) {
  16897. args.push(literalArr(literalFactoryArguments));
  16898. }
  16899. else {
  16900. args.push.apply(args, __spread(literalFactoryArguments));
  16901. }
  16902. return importExpr(identifier).callFn(args);
  16903. }
  16904. /**
  16905. * Gets an array of literals that can be added to an expression
  16906. * to represent the name and namespace of an attribute. E.g.
  16907. * `:xlink:href` turns into `[AttributeMarker.NamespaceURI, 'xlink', 'href']`.
  16908. *
  16909. * @param name Name of the attribute, including the namespace.
  16910. */
  16911. function getAttributeNameLiterals(name) {
  16912. var _a = __read(splitNsName(name), 2), attributeNamespace = _a[0], attributeName = _a[1];
  16913. var nameLiteral = literal(attributeName);
  16914. if (attributeNamespace) {
  16915. return [
  16916. literal(0 /* NamespaceURI */), literal(attributeNamespace), nameLiteral
  16917. ];
  16918. }
  16919. return [nameLiteral];
  16920. }
  16921. /** The prefix used to get a shared context in BindingScope's map. */
  16922. var SHARED_CONTEXT_KEY = '$$shared_ctx$$';
  16923. var BindingScope = /** @class */ (function () {
  16924. function BindingScope(bindingLevel, parent) {
  16925. if (bindingLevel === void 0) { bindingLevel = 0; }
  16926. if (parent === void 0) { parent = null; }
  16927. this.bindingLevel = bindingLevel;
  16928. this.parent = parent;
  16929. /** Keeps a map from local variables to their BindingData. */
  16930. this.map = new Map();
  16931. this.referenceNameIndex = 0;
  16932. this.restoreViewVariable = null;
  16933. }
  16934. Object.defineProperty(BindingScope, "ROOT_SCOPE", {
  16935. get: function () {
  16936. if (!BindingScope._ROOT_SCOPE) {
  16937. BindingScope._ROOT_SCOPE = new BindingScope().set(0, '$event', variable('$event'));
  16938. }
  16939. return BindingScope._ROOT_SCOPE;
  16940. },
  16941. enumerable: true,
  16942. configurable: true
  16943. });
  16944. BindingScope.prototype.get = function (name) {
  16945. var current = this;
  16946. while (current) {
  16947. var value = current.map.get(name);
  16948. if (value != null) {
  16949. if (current !== this) {
  16950. // make a local copy and reset the `declare` state
  16951. value = {
  16952. retrievalLevel: value.retrievalLevel,
  16953. lhs: value.lhs,
  16954. declareLocalCallback: value.declareLocalCallback,
  16955. declare: false,
  16956. priority: value.priority,
  16957. localRef: value.localRef
  16958. };
  16959. // Cache the value locally.
  16960. this.map.set(name, value);
  16961. // Possibly generate a shared context var
  16962. this.maybeGenerateSharedContextVar(value);
  16963. this.maybeRestoreView(value.retrievalLevel, value.localRef);
  16964. }
  16965. if (value.declareLocalCallback && !value.declare) {
  16966. value.declare = true;
  16967. }
  16968. return value.lhs;
  16969. }
  16970. current = current.parent;
  16971. }
  16972. // If we get to this point, we are looking for a property on the top level component
  16973. // - If level === 0, we are on the top and don't need to re-declare `ctx`.
  16974. // - If level > 0, we are in an embedded view. We need to retrieve the name of the
  16975. // local var we used to store the component context, e.g. const $comp$ = x();
  16976. return this.bindingLevel === 0 ? null : this.getComponentProperty(name);
  16977. };
  16978. /**
  16979. * Create a local variable for later reference.
  16980. *
  16981. * @param retrievalLevel The level from which this value can be retrieved
  16982. * @param name Name of the variable.
  16983. * @param lhs AST representing the left hand side of the `let lhs = rhs;`.
  16984. * @param priority The sorting priority of this var
  16985. * @param declareLocalCallback The callback to invoke when declaring this local var
  16986. * @param localRef Whether or not this is a local ref
  16987. */
  16988. BindingScope.prototype.set = function (retrievalLevel, name, lhs, priority, declareLocalCallback, localRef) {
  16989. if (priority === void 0) { priority = 0 /* DEFAULT */; }
  16990. if (this.map.has(name)) {
  16991. if (localRef) {
  16992. // Do not throw an error if it's a local ref and do not update existing value,
  16993. // so the first defined ref is always returned.
  16994. return this;
  16995. }
  16996. error("The name " + name + " is already defined in scope to be " + this.map.get(name));
  16997. }
  16998. this.map.set(name, {
  16999. retrievalLevel: retrievalLevel,
  17000. lhs: lhs,
  17001. declare: false,
  17002. declareLocalCallback: declareLocalCallback,
  17003. priority: priority,
  17004. localRef: localRef || false
  17005. });
  17006. return this;
  17007. };
  17008. // Implemented as part of LocalResolver.
  17009. BindingScope.prototype.getLocal = function (name) { return this.get(name); };
  17010. // Implemented as part of LocalResolver.
  17011. BindingScope.prototype.notifyImplicitReceiverUse = function () {
  17012. if (this.bindingLevel !== 0) {
  17013. // Since the implicit receiver is accessed in an embedded view, we need to
  17014. // ensure that we declare a shared context variable for the current template
  17015. // in the update variables.
  17016. this.map.get(SHARED_CONTEXT_KEY + 0).declare = true;
  17017. }
  17018. };
  17019. BindingScope.prototype.nestedScope = function (level) {
  17020. var newScope = new BindingScope(level, this);
  17021. if (level > 0)
  17022. newScope.generateSharedContextVar(0);
  17023. return newScope;
  17024. };
  17025. /**
  17026. * Gets or creates a shared context variable and returns its expression. Note that
  17027. * this does not mean that the shared variable will be declared. Variables in the
  17028. * binding scope will be only declared if they are used.
  17029. */
  17030. BindingScope.prototype.getOrCreateSharedContextVar = function (retrievalLevel) {
  17031. var bindingKey = SHARED_CONTEXT_KEY + retrievalLevel;
  17032. if (!this.map.has(bindingKey)) {
  17033. this.generateSharedContextVar(retrievalLevel);
  17034. }
  17035. return this.map.get(bindingKey).lhs;
  17036. };
  17037. BindingScope.prototype.getSharedContextName = function (retrievalLevel) {
  17038. var sharedCtxObj = this.map.get(SHARED_CONTEXT_KEY + retrievalLevel);
  17039. return sharedCtxObj && sharedCtxObj.declare ? sharedCtxObj.lhs : null;
  17040. };
  17041. BindingScope.prototype.maybeGenerateSharedContextVar = function (value) {
  17042. if (value.priority === 1 /* CONTEXT */ &&
  17043. value.retrievalLevel < this.bindingLevel) {
  17044. var sharedCtxObj = this.map.get(SHARED_CONTEXT_KEY + value.retrievalLevel);
  17045. if (sharedCtxObj) {
  17046. sharedCtxObj.declare = true;
  17047. }
  17048. else {
  17049. this.generateSharedContextVar(value.retrievalLevel);
  17050. }
  17051. }
  17052. };
  17053. BindingScope.prototype.generateSharedContextVar = function (retrievalLevel) {
  17054. var lhs = variable(CONTEXT_NAME + this.freshReferenceName());
  17055. this.map.set(SHARED_CONTEXT_KEY + retrievalLevel, {
  17056. retrievalLevel: retrievalLevel,
  17057. lhs: lhs,
  17058. declareLocalCallback: function (scope, relativeLevel) {
  17059. // const ctx_r0 = nextContext(2);
  17060. return [lhs.set(generateNextContextExpr(relativeLevel)).toConstDecl()];
  17061. },
  17062. declare: false,
  17063. priority: 2 /* SHARED_CONTEXT */,
  17064. localRef: false
  17065. });
  17066. };
  17067. BindingScope.prototype.getComponentProperty = function (name) {
  17068. var componentValue = this.map.get(SHARED_CONTEXT_KEY + 0);
  17069. componentValue.declare = true;
  17070. this.maybeRestoreView(0, false);
  17071. return componentValue.lhs.prop(name);
  17072. };
  17073. BindingScope.prototype.maybeRestoreView = function (retrievalLevel, localRefLookup) {
  17074. // We want to restore the current view in listener fns if:
  17075. // 1 - we are accessing a value in a parent view, which requires walking the view tree rather
  17076. // than using the ctx arg. In this case, the retrieval and binding level will be different.
  17077. // 2 - we are looking up a local ref, which requires restoring the view where the local
  17078. // ref is stored
  17079. if (this.isListenerScope() && (retrievalLevel < this.bindingLevel || localRefLookup)) {
  17080. if (!this.parent.restoreViewVariable) {
  17081. // parent saves variable to generate a shared `const $s$ = getCurrentView();` instruction
  17082. this.parent.restoreViewVariable = variable(this.parent.freshReferenceName());
  17083. }
  17084. this.restoreViewVariable = this.parent.restoreViewVariable;
  17085. }
  17086. };
  17087. BindingScope.prototype.restoreViewStatement = function () {
  17088. // restoreView($state$);
  17089. return this.restoreViewVariable ?
  17090. [instruction(null, Identifiers$1.restoreView, [this.restoreViewVariable]).toStmt()] :
  17091. [];
  17092. };
  17093. BindingScope.prototype.viewSnapshotStatements = function () {
  17094. // const $state$ = getCurrentView();
  17095. var getCurrentViewInstruction = instruction(null, Identifiers$1.getCurrentView, []);
  17096. return this.restoreViewVariable ?
  17097. [this.restoreViewVariable.set(getCurrentViewInstruction).toConstDecl()] :
  17098. [];
  17099. };
  17100. BindingScope.prototype.isListenerScope = function () { return this.parent && this.parent.bindingLevel === this.bindingLevel; };
  17101. BindingScope.prototype.variableDeclarations = function () {
  17102. var _this = this;
  17103. var currentContextLevel = 0;
  17104. return Array.from(this.map.values())
  17105. .filter(function (value) { return value.declare; })
  17106. .sort(function (a, b) { return b.retrievalLevel - a.retrievalLevel || b.priority - a.priority; })
  17107. .reduce(function (stmts, value) {
  17108. var levelDiff = _this.bindingLevel - value.retrievalLevel;
  17109. var currStmts = value.declareLocalCallback(_this, levelDiff - currentContextLevel);
  17110. currentContextLevel = levelDiff;
  17111. return stmts.concat(currStmts);
  17112. }, []);
  17113. };
  17114. BindingScope.prototype.freshReferenceName = function () {
  17115. var current = this;
  17116. // Find the top scope as it maintains the global reference count
  17117. while (current.parent)
  17118. current = current.parent;
  17119. var ref = "" + REFERENCE_PREFIX + current.referenceNameIndex++;
  17120. return ref;
  17121. };
  17122. return BindingScope;
  17123. }());
  17124. /**
  17125. * Creates a `CssSelector` given a tag name and a map of attributes
  17126. */
  17127. function createCssSelector(tag, attributes) {
  17128. var cssSelector = new CssSelector();
  17129. cssSelector.setElement(tag);
  17130. Object.getOwnPropertyNames(attributes).forEach(function (name) {
  17131. var value = attributes[name];
  17132. cssSelector.addAttribute(name, value);
  17133. if (name.toLowerCase() === 'class') {
  17134. var classes = value.trim().split(/\s+/);
  17135. classes.forEach(function (className) { return cssSelector.addClassName(className); });
  17136. }
  17137. });
  17138. return cssSelector;
  17139. }
  17140. /**
  17141. * Creates an array of expressions out of an `ngProjectAs` attributes
  17142. * which can be added to the instruction parameters.
  17143. */
  17144. function getNgProjectAsLiteral(attribute) {
  17145. // Parse the attribute value into a CssSelectorList. Note that we only take the
  17146. // first selector, because we don't support multiple selectors in ngProjectAs.
  17147. var parsedR3Selector = parseSelectorToR3Selector(attribute.value)[0];
  17148. return [literal(5 /* ProjectAs */), asLiteral(parsedR3Selector)];
  17149. }
  17150. function interpolate(args) {
  17151. args = args.slice(1); // Ignore the length prefix added for render2
  17152. switch (args.length) {
  17153. case 3:
  17154. return importExpr(Identifiers$1.interpolation1).callFn(args);
  17155. case 5:
  17156. return importExpr(Identifiers$1.interpolation2).callFn(args);
  17157. case 7:
  17158. return importExpr(Identifiers$1.interpolation3).callFn(args);
  17159. case 9:
  17160. return importExpr(Identifiers$1.interpolation4).callFn(args);
  17161. case 11:
  17162. return importExpr(Identifiers$1.interpolation5).callFn(args);
  17163. case 13:
  17164. return importExpr(Identifiers$1.interpolation6).callFn(args);
  17165. case 15:
  17166. return importExpr(Identifiers$1.interpolation7).callFn(args);
  17167. case 17:
  17168. return importExpr(Identifiers$1.interpolation8).callFn(args);
  17169. }
  17170. (args.length >= 19 && args.length % 2 == 1) ||
  17171. error("Invalid interpolation argument length " + args.length);
  17172. return importExpr(Identifiers$1.interpolationV).callFn([literalArr(args)]);
  17173. }
  17174. /**
  17175. * Gets the instruction to generate for an interpolated property
  17176. * @param interpolation An Interpolation AST
  17177. */
  17178. function getPropertyInterpolationExpression(interpolation) {
  17179. switch (getInterpolationArgsLength(interpolation)) {
  17180. case 1:
  17181. return Identifiers$1.propertyInterpolate;
  17182. case 3:
  17183. return Identifiers$1.propertyInterpolate1;
  17184. case 5:
  17185. return Identifiers$1.propertyInterpolate2;
  17186. case 7:
  17187. return Identifiers$1.propertyInterpolate3;
  17188. case 9:
  17189. return Identifiers$1.propertyInterpolate4;
  17190. case 11:
  17191. return Identifiers$1.propertyInterpolate5;
  17192. case 13:
  17193. return Identifiers$1.propertyInterpolate6;
  17194. case 15:
  17195. return Identifiers$1.propertyInterpolate7;
  17196. case 17:
  17197. return Identifiers$1.propertyInterpolate8;
  17198. default:
  17199. return Identifiers$1.propertyInterpolateV;
  17200. }
  17201. }
  17202. /**
  17203. * Gets the instruction to generate for an interpolated attribute
  17204. * @param interpolation An Interpolation AST
  17205. */
  17206. function getAttributeInterpolationExpression(interpolation) {
  17207. switch (getInterpolationArgsLength(interpolation)) {
  17208. case 3:
  17209. return Identifiers$1.attributeInterpolate1;
  17210. case 5:
  17211. return Identifiers$1.attributeInterpolate2;
  17212. case 7:
  17213. return Identifiers$1.attributeInterpolate3;
  17214. case 9:
  17215. return Identifiers$1.attributeInterpolate4;
  17216. case 11:
  17217. return Identifiers$1.attributeInterpolate5;
  17218. case 13:
  17219. return Identifiers$1.attributeInterpolate6;
  17220. case 15:
  17221. return Identifiers$1.attributeInterpolate7;
  17222. case 17:
  17223. return Identifiers$1.attributeInterpolate8;
  17224. default:
  17225. return Identifiers$1.attributeInterpolateV;
  17226. }
  17227. }
  17228. /**
  17229. * Gets the instruction to generate for interpolated text.
  17230. * @param interpolation An Interpolation AST
  17231. */
  17232. function getTextInterpolationExpression(interpolation) {
  17233. switch (getInterpolationArgsLength(interpolation)) {
  17234. case 1:
  17235. return Identifiers$1.textInterpolate;
  17236. case 3:
  17237. return Identifiers$1.textInterpolate1;
  17238. case 5:
  17239. return Identifiers$1.textInterpolate2;
  17240. case 7:
  17241. return Identifiers$1.textInterpolate3;
  17242. case 9:
  17243. return Identifiers$1.textInterpolate4;
  17244. case 11:
  17245. return Identifiers$1.textInterpolate5;
  17246. case 13:
  17247. return Identifiers$1.textInterpolate6;
  17248. case 15:
  17249. return Identifiers$1.textInterpolate7;
  17250. case 17:
  17251. return Identifiers$1.textInterpolate8;
  17252. default:
  17253. return Identifiers$1.textInterpolateV;
  17254. }
  17255. }
  17256. /**
  17257. * Gets the number of arguments expected to be passed to a generated instruction in the case of
  17258. * interpolation instructions.
  17259. * @param interpolation An interpolation ast
  17260. */
  17261. function getInterpolationArgsLength(interpolation) {
  17262. var expressions = interpolation.expressions, strings = interpolation.strings;
  17263. if (expressions.length === 1 && strings.length === 2 && strings[0] === '' && strings[1] === '') {
  17264. // If the interpolation has one interpolated value, but the prefix and suffix are both empty
  17265. // strings, we only pass one argument, to a special instruction like `propertyInterpolate` or
  17266. // `textInterpolate`.
  17267. return 1;
  17268. }
  17269. else {
  17270. return expressions.length + strings.length;
  17271. }
  17272. }
  17273. /**
  17274. * Parse a template into render3 `Node`s and additional metadata, with no other dependencies.
  17275. *
  17276. * @param template text of the template to parse
  17277. * @param templateUrl URL to use for source mapping of the parsed template
  17278. * @param options options to modify how the template is parsed
  17279. */
  17280. function parseTemplate(template, templateUrl, options) {
  17281. if (options === void 0) { options = {}; }
  17282. var interpolationConfig = options.interpolationConfig, preserveWhitespaces = options.preserveWhitespaces;
  17283. var bindingParser = makeBindingParser(interpolationConfig);
  17284. var htmlParser = new HtmlParser();
  17285. var parseResult = htmlParser.parse(template, templateUrl, __assign({ leadingTriviaChars: LEADING_TRIVIA_CHARS }, options, { tokenizeExpansionForms: true }));
  17286. if (parseResult.errors && parseResult.errors.length > 0) {
  17287. return { errors: parseResult.errors, nodes: [], styleUrls: [], styles: [] };
  17288. }
  17289. var rootNodes = parseResult.rootNodes;
  17290. // process i18n meta information (scan attributes, generate ids)
  17291. // before we run whitespace removal process, because existing i18n
  17292. // extraction process (ng xi18n) relies on a raw content to generate
  17293. // message ids
  17294. rootNodes =
  17295. visitAll$1(new I18nMetaVisitor(interpolationConfig, !preserveWhitespaces), rootNodes);
  17296. if (!preserveWhitespaces) {
  17297. rootNodes = visitAll$1(new WhitespaceVisitor(), rootNodes);
  17298. // run i18n meta visitor again in case we remove whitespaces, because
  17299. // that might affect generated i18n message content. During this pass
  17300. // i18n IDs generated at the first pass will be preserved, so we can mimic
  17301. // existing extraction process (ng xi18n)
  17302. rootNodes = visitAll$1(new I18nMetaVisitor(interpolationConfig, /* keepI18nAttrs */ false), rootNodes);
  17303. }
  17304. var _a = htmlAstToRender3Ast(rootNodes, bindingParser), nodes = _a.nodes, errors = _a.errors, styleUrls = _a.styleUrls, styles = _a.styles;
  17305. if (errors && errors.length > 0) {
  17306. return { errors: errors, nodes: [], styleUrls: [], styles: [] };
  17307. }
  17308. return { nodes: nodes, styleUrls: styleUrls, styles: styles };
  17309. }
  17310. /**
  17311. * Construct a `BindingParser` with a default configuration.
  17312. */
  17313. function makeBindingParser(interpolationConfig) {
  17314. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  17315. return new BindingParser(new Parser$1(new Lexer()), interpolationConfig, new DomElementSchemaRegistry(), null, []);
  17316. }
  17317. function resolveSanitizationFn(context, isAttribute) {
  17318. switch (context) {
  17319. case SecurityContext.HTML:
  17320. return importExpr(Identifiers$1.sanitizeHtml);
  17321. case SecurityContext.SCRIPT:
  17322. return importExpr(Identifiers$1.sanitizeScript);
  17323. case SecurityContext.STYLE:
  17324. // the compiler does not fill in an instruction for [style.prop?] binding
  17325. // values because the style algorithm knows internally what props are subject
  17326. // to sanitization (only [attr.style] values are explicitly sanitized)
  17327. return isAttribute ? importExpr(Identifiers$1.sanitizeStyle) : null;
  17328. case SecurityContext.URL:
  17329. return importExpr(Identifiers$1.sanitizeUrl);
  17330. case SecurityContext.RESOURCE_URL:
  17331. return importExpr(Identifiers$1.sanitizeResourceUrl);
  17332. default:
  17333. return null;
  17334. }
  17335. }
  17336. function isSingleElementTemplate(children) {
  17337. return children.length === 1 && children[0] instanceof Element;
  17338. }
  17339. function isTextNode(node) {
  17340. return node instanceof Text || node instanceof BoundText || node instanceof Icu;
  17341. }
  17342. function hasTextChildrenOnly(children) {
  17343. return children.every(isTextNode);
  17344. }
  17345. /**
  17346. * @license
  17347. * Copyright Google Inc. All Rights Reserved.
  17348. *
  17349. * Use of this source code is governed by an MIT-style license that can be
  17350. * found in the LICENSE file at https://angular.io/license
  17351. */
  17352. var EMPTY_ARRAY = [];
  17353. // This regex matches any binding names that contain the "attr." prefix, e.g. "attr.required"
  17354. // If there is a match, the first matching group will contain the attribute name to bind.
  17355. var ATTR_REGEX = /attr\.([^\]]+)/;
  17356. function getStylingPrefix(name) {
  17357. return name.substring(0, 5); // style or class
  17358. }
  17359. function baseDirectiveFields(meta, constantPool, bindingParser) {
  17360. var definitionMap = new DefinitionMap();
  17361. // e.g. `type: MyDirective`
  17362. definitionMap.set('type', meta.type);
  17363. // e.g. `selectors: [['', 'someDir', '']]`
  17364. definitionMap.set('selectors', createDirectiveSelector(meta.selector));
  17365. // e.g. `factory: () => new MyApp(directiveInject(ElementRef))`
  17366. var result = compileFactoryFunction({
  17367. name: meta.name,
  17368. type: meta.type,
  17369. deps: meta.deps,
  17370. injectFn: Identifiers$1.directiveInject,
  17371. });
  17372. definitionMap.set('factory', result.factory);
  17373. if (meta.queries.length > 0) {
  17374. // e.g. `contentQueries: (rf, ctx, dirIndex) => { ... }
  17375. definitionMap.set('contentQueries', createContentQueriesFunction(meta.queries, constantPool, meta.name));
  17376. }
  17377. if (meta.viewQueries.length) {
  17378. definitionMap.set('viewQuery', createViewQueriesFunction(meta.viewQueries, constantPool, meta.name));
  17379. }
  17380. // e.g. `hostBindings: (rf, ctx, elIndex) => { ... }
  17381. definitionMap.set('hostBindings', createHostBindingsFunction(meta.host, meta.typeSourceSpan, bindingParser, constantPool, meta.selector || '', meta.name));
  17382. // e.g 'inputs: {a: 'a'}`
  17383. definitionMap.set('inputs', conditionallyCreateMapObjectLiteral(meta.inputs, true));
  17384. // e.g 'outputs: {a: 'a'}`
  17385. definitionMap.set('outputs', conditionallyCreateMapObjectLiteral(meta.outputs));
  17386. if (meta.exportAs !== null) {
  17387. definitionMap.set('exportAs', literalArr(meta.exportAs.map(function (e) { return literal(e); })));
  17388. }
  17389. return { definitionMap: definitionMap, statements: result.statements };
  17390. }
  17391. /**
  17392. * Add features to the definition map.
  17393. */
  17394. function addFeatures(definitionMap, meta) {
  17395. // e.g. `features: [NgOnChangesFeature()]`
  17396. var features = [];
  17397. var providers = meta.providers;
  17398. var viewProviders = meta.viewProviders;
  17399. if (providers || viewProviders) {
  17400. var args = [providers || new LiteralArrayExpr([])];
  17401. if (viewProviders) {
  17402. args.push(viewProviders);
  17403. }
  17404. features.push(importExpr(Identifiers$1.ProvidersFeature).callFn(args));
  17405. }
  17406. if (meta.usesInheritance) {
  17407. features.push(importExpr(Identifiers$1.InheritDefinitionFeature));
  17408. }
  17409. if (meta.lifecycle.usesOnChanges) {
  17410. features.push(importExpr(Identifiers$1.NgOnChangesFeature).callFn(EMPTY_ARRAY));
  17411. }
  17412. if (features.length) {
  17413. definitionMap.set('features', literalArr(features));
  17414. }
  17415. }
  17416. /**
  17417. * Compile a directive for the render3 runtime as defined by the `R3DirectiveMetadata`.
  17418. */
  17419. function compileDirectiveFromMetadata(meta, constantPool, bindingParser) {
  17420. var _a = baseDirectiveFields(meta, constantPool, bindingParser), definitionMap = _a.definitionMap, statements = _a.statements;
  17421. addFeatures(definitionMap, meta);
  17422. var expression = importExpr(Identifiers$1.defineDirective).callFn([definitionMap.toLiteralMap()]);
  17423. if (!meta.selector) {
  17424. throw new Error("Directive " + meta.name + " has no selector, please add it!");
  17425. }
  17426. var type = createTypeForDef(meta, Identifiers$1.DirectiveDefWithMeta);
  17427. return { expression: expression, type: type, statements: statements };
  17428. }
  17429. /**
  17430. * Compile a base definition for the render3 runtime as defined by {@link R3BaseRefMetadata}
  17431. * @param meta the metadata used for compilation.
  17432. */
  17433. function compileBaseDefFromMetadata(meta, constantPool, bindingParser) {
  17434. var definitionMap = new DefinitionMap();
  17435. if (meta.inputs) {
  17436. var inputs_1 = meta.inputs;
  17437. var inputsMap = Object.keys(inputs_1).map(function (key) {
  17438. var v = inputs_1[key];
  17439. var value = Array.isArray(v) ? literalArr(v.map(function (vx) { return literal(vx); })) : literal(v);
  17440. return { key: key, value: value, quoted: false };
  17441. });
  17442. definitionMap.set('inputs', literalMap(inputsMap));
  17443. }
  17444. if (meta.outputs) {
  17445. var outputs_1 = meta.outputs;
  17446. var outputsMap = Object.keys(outputs_1).map(function (key) {
  17447. var value = literal(outputs_1[key]);
  17448. return { key: key, value: value, quoted: false };
  17449. });
  17450. definitionMap.set('outputs', literalMap(outputsMap));
  17451. }
  17452. if (meta.viewQueries && meta.viewQueries.length > 0) {
  17453. definitionMap.set('viewQuery', createViewQueriesFunction(meta.viewQueries, constantPool));
  17454. }
  17455. if (meta.queries && meta.queries.length > 0) {
  17456. definitionMap.set('contentQueries', createContentQueriesFunction(meta.queries, constantPool));
  17457. }
  17458. if (meta.host) {
  17459. definitionMap.set('hostBindings', createHostBindingsFunction(meta.host, meta.typeSourceSpan, bindingParser, constantPool, meta.name));
  17460. }
  17461. var expression = importExpr(Identifiers$1.defineBase).callFn([definitionMap.toLiteralMap()]);
  17462. var type = new ExpressionType(importExpr(Identifiers$1.BaseDef));
  17463. return { expression: expression, type: type };
  17464. }
  17465. /**
  17466. * Compile a component for the render3 runtime as defined by the `R3ComponentMetadata`.
  17467. */
  17468. function compileComponentFromMetadata(meta, constantPool, bindingParser) {
  17469. var e_1, _a;
  17470. var _b = baseDirectiveFields(meta, constantPool, bindingParser), definitionMap = _b.definitionMap, statements = _b.statements;
  17471. addFeatures(definitionMap, meta);
  17472. var selector = meta.selector && CssSelector.parse(meta.selector);
  17473. var firstSelector = selector && selector[0];
  17474. // e.g. `attr: ["class", ".my.app"]`
  17475. // This is optional an only included if the first selector of a component specifies attributes.
  17476. if (firstSelector) {
  17477. var selectorAttributes = firstSelector.getAttrs();
  17478. if (selectorAttributes.length) {
  17479. definitionMap.set('attrs', constantPool.getConstLiteral(literalArr(selectorAttributes.map(function (value) { return value != null ? literal(value) : literal(undefined); })),
  17480. /* forceShared */ true));
  17481. }
  17482. }
  17483. // Generate the CSS matcher that recognize directive
  17484. var directiveMatcher = null;
  17485. if (meta.directives.length > 0) {
  17486. var matcher = new SelectorMatcher();
  17487. try {
  17488. for (var _c = __values(meta.directives), _d = _c.next(); !_d.done; _d = _c.next()) {
  17489. var _e = _d.value, selector_1 = _e.selector, expression_1 = _e.expression;
  17490. matcher.addSelectables(CssSelector.parse(selector_1), expression_1);
  17491. }
  17492. }
  17493. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  17494. finally {
  17495. try {
  17496. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  17497. }
  17498. finally { if (e_1) throw e_1.error; }
  17499. }
  17500. directiveMatcher = matcher;
  17501. }
  17502. // e.g. `template: function MyComponent_Template(_ctx, _cm) {...}`
  17503. var templateTypeName = meta.name;
  17504. var templateName = templateTypeName ? templateTypeName + "_Template" : null;
  17505. var directivesUsed = new Set();
  17506. var pipesUsed = new Set();
  17507. var changeDetection = meta.changeDetection;
  17508. var template = meta.template;
  17509. 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);
  17510. var templateFunctionExpression = templateBuilder.buildTemplateFunction(template.nodes, []);
  17511. // We need to provide this so that dynamically generated components know what
  17512. // projected content blocks to pass through to the component when it is instantiated.
  17513. var ngContentSelectors = templateBuilder.getNgContentSelectors();
  17514. if (ngContentSelectors) {
  17515. definitionMap.set('ngContentSelectors', ngContentSelectors);
  17516. }
  17517. // e.g. `consts: 2`
  17518. definitionMap.set('consts', literal(templateBuilder.getConstCount()));
  17519. // e.g. `vars: 2`
  17520. definitionMap.set('vars', literal(templateBuilder.getVarCount()));
  17521. definitionMap.set('template', templateFunctionExpression);
  17522. // e.g. `directives: [MyDirective]`
  17523. if (directivesUsed.size) {
  17524. var directivesExpr = literalArr(Array.from(directivesUsed));
  17525. if (meta.wrapDirectivesAndPipesInClosure) {
  17526. directivesExpr = fn([], [new ReturnStatement(directivesExpr)]);
  17527. }
  17528. definitionMap.set('directives', directivesExpr);
  17529. }
  17530. // e.g. `pipes: [MyPipe]`
  17531. if (pipesUsed.size) {
  17532. var pipesExpr = literalArr(Array.from(pipesUsed));
  17533. if (meta.wrapDirectivesAndPipesInClosure) {
  17534. pipesExpr = fn([], [new ReturnStatement(pipesExpr)]);
  17535. }
  17536. definitionMap.set('pipes', pipesExpr);
  17537. }
  17538. if (meta.encapsulation === null) {
  17539. meta.encapsulation = ViewEncapsulation.Emulated;
  17540. }
  17541. // e.g. `styles: [str1, str2]`
  17542. if (meta.styles && meta.styles.length) {
  17543. var styleValues = meta.encapsulation == ViewEncapsulation.Emulated ?
  17544. compileStyles(meta.styles, CONTENT_ATTR, HOST_ATTR) :
  17545. meta.styles;
  17546. var strings = styleValues.map(function (str) { return literal(str); });
  17547. definitionMap.set('styles', literalArr(strings));
  17548. }
  17549. else if (meta.encapsulation === ViewEncapsulation.Emulated) {
  17550. // If there is no style, don't generate css selectors on elements
  17551. meta.encapsulation = ViewEncapsulation.None;
  17552. }
  17553. // Only set view encapsulation if it's not the default value
  17554. if (meta.encapsulation !== ViewEncapsulation.Emulated) {
  17555. definitionMap.set('encapsulation', literal(meta.encapsulation));
  17556. }
  17557. // e.g. `animation: [trigger('123', [])]`
  17558. if (meta.animations !== null) {
  17559. definitionMap.set('data', literalMap([{ key: 'animation', value: meta.animations, quoted: false }]));
  17560. }
  17561. // Only set the change detection flag if it's defined and it's not the default.
  17562. if (changeDetection != null && changeDetection !== ChangeDetectionStrategy.Default) {
  17563. definitionMap.set('changeDetection', literal(changeDetection));
  17564. }
  17565. // On the type side, remove newlines from the selector as it will need to fit into a TypeScript
  17566. // string literal, which must be on one line.
  17567. var selectorForType = (meta.selector || '').replace(/\n/g, '');
  17568. var expression = importExpr(Identifiers$1.defineComponent).callFn([definitionMap.toLiteralMap()]);
  17569. var type = createTypeForDef(meta, Identifiers$1.ComponentDefWithMeta);
  17570. return { expression: expression, type: type, statements: statements };
  17571. }
  17572. /**
  17573. * A wrapper around `compileDirective` which depends on render2 global analysis data as its input
  17574. * instead of the `R3DirectiveMetadata`.
  17575. *
  17576. * `R3DirectiveMetadata` is computed from `CompileDirectiveMetadata` and other statically reflected
  17577. * information.
  17578. */
  17579. function compileDirectiveFromRender2(outputCtx, directive, reflector, bindingParser) {
  17580. var name = identifierName(directive.type);
  17581. name || error("Cannot resolver the name of " + directive.type);
  17582. var definitionField = outputCtx.constantPool.propertyNameOf(1 /* Directive */);
  17583. var meta = directiveMetadataFromGlobalMetadata(directive, outputCtx, reflector);
  17584. var res = compileDirectiveFromMetadata(meta, outputCtx.constantPool, bindingParser);
  17585. // Create the partial class to be merged with the actual class.
  17586. outputCtx.statements.push(new ClassStmt(name, null, [new ClassField(definitionField, INFERRED_TYPE, [exports.StmtModifier.Static], res.expression)], [], new ClassMethod(null, [], []), []));
  17587. }
  17588. /**
  17589. * A wrapper around `compileComponent` which depends on render2 global analysis data as its input
  17590. * instead of the `R3DirectiveMetadata`.
  17591. *
  17592. * `R3ComponentMetadata` is computed from `CompileDirectiveMetadata` and other statically reflected
  17593. * information.
  17594. */
  17595. function compileComponentFromRender2(outputCtx, component, render3Ast, reflector, bindingParser, directiveTypeBySel, pipeTypeByName) {
  17596. var name = identifierName(component.type);
  17597. name || error("Cannot resolver the name of " + component.type);
  17598. var definitionField = outputCtx.constantPool.propertyNameOf(2 /* Component */);
  17599. var summary = component.toSummary();
  17600. // Compute the R3ComponentMetadata from the CompileDirectiveMetadata
  17601. 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 });
  17602. var res = compileComponentFromMetadata(meta, outputCtx.constantPool, bindingParser);
  17603. // Create the partial class to be merged with the actual class.
  17604. outputCtx.statements.push(new ClassStmt(name, null, [new ClassField(definitionField, INFERRED_TYPE, [exports.StmtModifier.Static], res.expression)], [], new ClassMethod(null, [], []), []));
  17605. }
  17606. /**
  17607. * Compute `R3DirectiveMetadata` given `CompileDirectiveMetadata` and a `CompileReflector`.
  17608. */
  17609. function directiveMetadataFromGlobalMetadata(directive, outputCtx, reflector) {
  17610. // The global-analysis based Ivy mode in ngc is no longer utilized/supported.
  17611. throw new Error('unsupported');
  17612. }
  17613. /**
  17614. * Convert `CompileQueryMetadata` into `R3QueryMetadata`.
  17615. */
  17616. function queriesFromGlobalMetadata(queries, outputCtx) {
  17617. return queries.map(function (query) {
  17618. var read = null;
  17619. if (query.read && query.read.identifier) {
  17620. read = outputCtx.importExpr(query.read.identifier.reference);
  17621. }
  17622. return {
  17623. propertyName: query.propertyName,
  17624. first: query.first,
  17625. predicate: selectorsFromGlobalMetadata(query.selectors, outputCtx),
  17626. descendants: query.descendants, read: read,
  17627. static: !!query.static
  17628. };
  17629. });
  17630. }
  17631. /**
  17632. * Convert `CompileTokenMetadata` for query selectors into either an expression for a predicate
  17633. * type, or a list of string predicates.
  17634. */
  17635. function selectorsFromGlobalMetadata(selectors, outputCtx) {
  17636. if (selectors.length > 1 || (selectors.length == 1 && selectors[0].value)) {
  17637. var selectorStrings = selectors.map(function (value) { return value.value; });
  17638. selectorStrings.some(function (value) { return !value; }) &&
  17639. error('Found a type among the string selectors expected');
  17640. return outputCtx.constantPool.getConstLiteral(literalArr(selectorStrings.map(function (value) { return literal(value); })));
  17641. }
  17642. if (selectors.length == 1) {
  17643. var first = selectors[0];
  17644. if (first.identifier) {
  17645. return outputCtx.importExpr(first.identifier.reference);
  17646. }
  17647. }
  17648. error('Unexpected query form');
  17649. return NULL_EXPR;
  17650. }
  17651. function prepareQueryParams(query, constantPool) {
  17652. var parameters = [
  17653. getQueryPredicate(query, constantPool),
  17654. literal(query.descendants),
  17655. query.read || literal(null),
  17656. ];
  17657. return parameters;
  17658. }
  17659. // Turn a directive selector into an R3-compatible selector for directive def
  17660. function createDirectiveSelector(selector) {
  17661. return asLiteral(parseSelectorToR3Selector(selector));
  17662. }
  17663. function convertAttributesToExpressions(attributes) {
  17664. var e_2, _a;
  17665. var values = [];
  17666. try {
  17667. for (var _b = __values(Object.getOwnPropertyNames(attributes)), _c = _b.next(); !_c.done; _c = _b.next()) {
  17668. var key = _c.value;
  17669. var value = attributes[key];
  17670. values.push(literal(key), value);
  17671. }
  17672. }
  17673. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  17674. finally {
  17675. try {
  17676. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  17677. }
  17678. finally { if (e_2) throw e_2.error; }
  17679. }
  17680. return values;
  17681. }
  17682. // Define and update any content queries
  17683. function createContentQueriesFunction(queries, constantPool, name) {
  17684. var e_3, _a;
  17685. var createStatements = [];
  17686. var updateStatements = [];
  17687. var tempAllocator = temporaryAllocator(updateStatements, TEMPORARY_NAME);
  17688. try {
  17689. for (var queries_1 = __values(queries), queries_1_1 = queries_1.next(); !queries_1_1.done; queries_1_1 = queries_1.next()) {
  17690. var query = queries_1_1.value;
  17691. // creation, e.g. r3.contentQuery(dirIndex, somePredicate, true, null);
  17692. var args = __spread([variable('dirIndex')], prepareQueryParams(query, constantPool));
  17693. var queryInstruction = query.static ? Identifiers$1.staticContentQuery : Identifiers$1.contentQuery;
  17694. createStatements.push(importExpr(queryInstruction).callFn(args).toStmt());
  17695. // update, e.g. (r3.queryRefresh(tmp = r3.loadContentQuery()) && (ctx.someDir = tmp));
  17696. var temporary = tempAllocator();
  17697. var getQueryList = importExpr(Identifiers$1.loadContentQuery).callFn([]);
  17698. var refresh = importExpr(Identifiers$1.queryRefresh).callFn([temporary.set(getQueryList)]);
  17699. var updateDirective = variable(CONTEXT_NAME)
  17700. .prop(query.propertyName)
  17701. .set(query.first ? temporary.prop('first') : temporary);
  17702. updateStatements.push(refresh.and(updateDirective).toStmt());
  17703. }
  17704. }
  17705. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  17706. finally {
  17707. try {
  17708. if (queries_1_1 && !queries_1_1.done && (_a = queries_1.return)) _a.call(queries_1);
  17709. }
  17710. finally { if (e_3) throw e_3.error; }
  17711. }
  17712. var contentQueriesFnName = name ? name + "_ContentQueries" : null;
  17713. return fn([
  17714. new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null),
  17715. new FnParam('dirIndex', null)
  17716. ], [
  17717. renderFlagCheckIfStmt(1 /* Create */, createStatements),
  17718. renderFlagCheckIfStmt(2 /* Update */, updateStatements)
  17719. ], INFERRED_TYPE, null, contentQueriesFnName);
  17720. }
  17721. function stringAsType(str) {
  17722. return expressionType(literal(str));
  17723. }
  17724. function stringMapAsType(map) {
  17725. var mapValues = Object.keys(map).map(function (key) {
  17726. var value = Array.isArray(map[key]) ? map[key][0] : map[key];
  17727. return {
  17728. key: key,
  17729. value: literal(value),
  17730. quoted: true,
  17731. };
  17732. });
  17733. return expressionType(literalMap(mapValues));
  17734. }
  17735. function stringArrayAsType(arr) {
  17736. return arr.length > 0 ? expressionType(literalArr(arr.map(function (value) { return literal(value); }))) :
  17737. NONE_TYPE;
  17738. }
  17739. function createTypeForDef(meta, typeBase) {
  17740. // On the type side, remove newlines from the selector as it will need to fit into a TypeScript
  17741. // string literal, which must be on one line.
  17742. var selectorForType = (meta.selector || '').replace(/\n/g, '');
  17743. return expressionType(importExpr(typeBase, [
  17744. typeWithParameters(meta.type, meta.typeArgumentCount),
  17745. stringAsType(selectorForType),
  17746. meta.exportAs !== null ? stringArrayAsType(meta.exportAs) : NONE_TYPE,
  17747. stringMapAsType(meta.inputs),
  17748. stringMapAsType(meta.outputs),
  17749. stringArrayAsType(meta.queries.map(function (q) { return q.propertyName; })),
  17750. ]));
  17751. }
  17752. // Define and update any view queries
  17753. function createViewQueriesFunction(viewQueries, constantPool, name) {
  17754. var createStatements = [];
  17755. var updateStatements = [];
  17756. var tempAllocator = temporaryAllocator(updateStatements, TEMPORARY_NAME);
  17757. viewQueries.forEach(function (query) {
  17758. var queryInstruction = query.static ? Identifiers$1.staticViewQuery : Identifiers$1.viewQuery;
  17759. // creation, e.g. r3.viewQuery(somePredicate, true);
  17760. var queryDefinition = importExpr(queryInstruction).callFn(prepareQueryParams(query, constantPool));
  17761. createStatements.push(queryDefinition.toStmt());
  17762. // update, e.g. (r3.queryRefresh(tmp = r3.loadViewQuery()) && (ctx.someDir = tmp));
  17763. var temporary = tempAllocator();
  17764. var getQueryList = importExpr(Identifiers$1.loadViewQuery).callFn([]);
  17765. var refresh = importExpr(Identifiers$1.queryRefresh).callFn([temporary.set(getQueryList)]);
  17766. var updateDirective = variable(CONTEXT_NAME)
  17767. .prop(query.propertyName)
  17768. .set(query.first ? temporary.prop('first') : temporary);
  17769. updateStatements.push(refresh.and(updateDirective).toStmt());
  17770. });
  17771. var viewQueryFnName = name ? name + "_Query" : null;
  17772. return fn([new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], [
  17773. renderFlagCheckIfStmt(1 /* Create */, createStatements),
  17774. renderFlagCheckIfStmt(2 /* Update */, updateStatements)
  17775. ], INFERRED_TYPE, null, viewQueryFnName);
  17776. }
  17777. // Return a host binding function or null if one is not necessary.
  17778. function createHostBindingsFunction(hostBindingsMetadata, typeSourceSpan, bindingParser, constantPool, selector, name) {
  17779. // Initialize hostVarsCount to number of bound host properties (interpolations illegal),
  17780. // except 'style' and 'class' properties, since they should *not* allocate host var slots
  17781. var hostVarsCount = Object.keys(hostBindingsMetadata.properties)
  17782. .filter(function (name) {
  17783. var prefix = getStylingPrefix(name);
  17784. return prefix !== 'style' && prefix !== 'class';
  17785. })
  17786. .length;
  17787. var elVarExp = variable('elIndex');
  17788. var bindingContext = variable(CONTEXT_NAME);
  17789. var styleBuilder = new StylingBuilder(elVarExp, bindingContext);
  17790. var _a = hostBindingsMetadata.specialAttributes, styleAttr = _a.styleAttr, classAttr = _a.classAttr;
  17791. if (styleAttr !== undefined) {
  17792. styleBuilder.registerStyleAttr(styleAttr);
  17793. }
  17794. if (classAttr !== undefined) {
  17795. styleBuilder.registerClassAttr(classAttr);
  17796. }
  17797. var createStatements = [];
  17798. var updateStatements = [];
  17799. var totalHostVarsCount = hostVarsCount;
  17800. var hostBindingSourceSpan = typeSourceSpan;
  17801. var directiveSummary = metadataAsSummary(hostBindingsMetadata);
  17802. var valueConverter;
  17803. var getValueConverter = function () {
  17804. if (!valueConverter) {
  17805. var hostVarsCountFn = function (numSlots) {
  17806. var originalVarsCount = totalHostVarsCount;
  17807. totalHostVarsCount += numSlots;
  17808. return originalVarsCount;
  17809. };
  17810. valueConverter = new ValueConverter(constantPool, function () { return error('Unexpected node'); }, // new nodes are illegal here
  17811. hostVarsCountFn, function () { return error('Unexpected pipe'); }); // pipes are illegal here
  17812. }
  17813. return valueConverter;
  17814. };
  17815. // Calculate host event bindings
  17816. var eventBindings = bindingParser.createDirectiveHostEventAsts(directiveSummary, hostBindingSourceSpan);
  17817. if (eventBindings && eventBindings.length) {
  17818. var listeners = createHostListeners(eventBindings, name);
  17819. createStatements.push.apply(createStatements, __spread(listeners));
  17820. }
  17821. // Calculate the host property bindings
  17822. var bindings = bindingParser.createBoundHostProperties(directiveSummary, hostBindingSourceSpan);
  17823. (bindings || []).forEach(function (binding) {
  17824. var name = binding.name;
  17825. var stylingInputWasSet = styleBuilder.registerInputBasedOnName(name, binding.expression, binding.sourceSpan);
  17826. if (!stylingInputWasSet) {
  17827. // resolve literal arrays and literal objects
  17828. var value = binding.expression.visit(getValueConverter());
  17829. var bindingExpr = bindingFn(bindingContext, value);
  17830. var _a = getBindingNameAndInstruction(binding), bindingName = _a.bindingName, instruction = _a.instruction, isAttribute = _a.isAttribute;
  17831. var securityContexts = bindingParser.calcPossibleSecurityContexts(selector, bindingName, isAttribute)
  17832. .filter(function (context) { return context !== SecurityContext.NONE; });
  17833. var sanitizerFn = null;
  17834. if (securityContexts.length) {
  17835. if (securityContexts.length === 2 &&
  17836. securityContexts.indexOf(SecurityContext.URL) > -1 &&
  17837. securityContexts.indexOf(SecurityContext.RESOURCE_URL) > -1) {
  17838. // Special case for some URL attributes (such as "src" and "href") that may be a part
  17839. // of different security contexts. In this case we use special santitization function and
  17840. // select the actual sanitizer at runtime based on a tag name that is provided while
  17841. // invoking sanitization function.
  17842. sanitizerFn = importExpr(Identifiers$1.sanitizeUrlOrResourceUrl);
  17843. }
  17844. else {
  17845. sanitizerFn = resolveSanitizationFn(securityContexts[0], isAttribute);
  17846. }
  17847. }
  17848. var instructionParams = [literal(bindingName), bindingExpr.currValExpr];
  17849. if (sanitizerFn) {
  17850. instructionParams.push(sanitizerFn);
  17851. }
  17852. if (!isAttribute) {
  17853. if (!sanitizerFn) {
  17854. // append `null` in front of `nativeOnly` flag if no sanitizer fn defined
  17855. instructionParams.push(literal(null));
  17856. }
  17857. // host bindings must have nativeOnly prop set to true
  17858. instructionParams.push(literal(true));
  17859. }
  17860. updateStatements.push.apply(updateStatements, __spread(bindingExpr.stmts));
  17861. updateStatements.push(importExpr(instruction).callFn(instructionParams).toStmt());
  17862. }
  17863. });
  17864. // since we're dealing with directives/components and both have hostBinding
  17865. // functions, we need to generate a special hostAttrs instruction that deals
  17866. // with both the assignment of styling as well as static attributes to the host
  17867. // element. The instruction below will instruct all initial styling (styling
  17868. // that is inside of a host binding within a directive/component) to be attached
  17869. // to the host element alongside any of the provided host attributes that were
  17870. // collected earlier.
  17871. var hostAttrs = convertAttributesToExpressions(hostBindingsMetadata.attributes);
  17872. var hostInstruction = styleBuilder.buildHostAttrsInstruction(null, hostAttrs, constantPool);
  17873. if (hostInstruction) {
  17874. createStatements.push(createStylingStmt(hostInstruction, bindingContext, bindingFn));
  17875. }
  17876. if (styleBuilder.hasBindings) {
  17877. // singular style/class bindings (things like `[style.prop]` and `[class.name]`)
  17878. // MUST be registered on a given element within the component/directive
  17879. // templateFn/hostBindingsFn functions. The instruction below will figure out
  17880. // what all the bindings are and then generate the statements required to register
  17881. // those bindings to the element via `styling`.
  17882. var stylingInstruction = styleBuilder.buildStylingInstruction(null, constantPool);
  17883. if (stylingInstruction) {
  17884. createStatements.push(createStylingStmt(stylingInstruction, bindingContext, bindingFn));
  17885. }
  17886. // finally each binding that was registered in the statement above will need to be added to
  17887. // the update block of a component/directive templateFn/hostBindingsFn so that the bindings
  17888. // are evaluated and updated for the element.
  17889. styleBuilder.buildUpdateLevelInstructions(getValueConverter()).forEach(function (instruction) {
  17890. totalHostVarsCount += instruction.allocateBindingSlots;
  17891. updateStatements.push(createStylingStmt(instruction, bindingContext, bindingFn));
  17892. });
  17893. }
  17894. if (totalHostVarsCount) {
  17895. createStatements.unshift(importExpr(Identifiers$1.allocHostVars).callFn([literal(totalHostVarsCount)]).toStmt());
  17896. }
  17897. if (createStatements.length > 0 || updateStatements.length > 0) {
  17898. var hostBindingsFnName = name ? name + "_HostBindings" : null;
  17899. var statements = [];
  17900. if (createStatements.length > 0) {
  17901. statements.push(renderFlagCheckIfStmt(1 /* Create */, createStatements));
  17902. }
  17903. if (updateStatements.length > 0) {
  17904. statements.push(renderFlagCheckIfStmt(2 /* Update */, updateStatements));
  17905. }
  17906. return fn([
  17907. new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null),
  17908. new FnParam(elVarExp.name, NUMBER_TYPE)
  17909. ], statements, INFERRED_TYPE, null, hostBindingsFnName);
  17910. }
  17911. return null;
  17912. }
  17913. function bindingFn(implicit, value) {
  17914. return convertPropertyBinding(null, implicit, value, 'b', BindingForm.TrySimple, function () { return error('Unexpected interpolation'); });
  17915. }
  17916. function createStylingStmt(instruction, bindingContext, bindingFn) {
  17917. var params = instruction.buildParams(function (value) { return bindingFn(bindingContext, value).currValExpr; });
  17918. return importExpr(instruction.reference, null, instruction.sourceSpan)
  17919. .callFn(params, instruction.sourceSpan)
  17920. .toStmt();
  17921. }
  17922. function getBindingNameAndInstruction(binding) {
  17923. var bindingName = binding.name;
  17924. var instruction;
  17925. // Check to see if this is an attr binding or a property binding
  17926. var attrMatches = bindingName.match(ATTR_REGEX);
  17927. if (attrMatches) {
  17928. bindingName = attrMatches[1];
  17929. instruction = Identifiers$1.attribute;
  17930. }
  17931. else {
  17932. if (binding.isAnimation) {
  17933. bindingName = prepareSyntheticPropertyName(bindingName);
  17934. // host bindings that have a synthetic property (e.g. @foo) should always be rendered
  17935. // in the context of the component and not the parent. Therefore there is a special
  17936. // compatibility instruction available for this purpose.
  17937. instruction = Identifiers$1.updateSyntheticHostBinding;
  17938. }
  17939. else {
  17940. instruction = Identifiers$1.property;
  17941. }
  17942. }
  17943. return { bindingName: bindingName, instruction: instruction, isAttribute: !!attrMatches };
  17944. }
  17945. function createHostListeners(eventBindings, name) {
  17946. return eventBindings.map(function (binding) {
  17947. var bindingName = binding.name && sanitizeIdentifier(binding.name);
  17948. var bindingFnName = binding.type === 1 /* Animation */ ?
  17949. prepareSyntheticListenerFunctionName(bindingName, binding.targetOrPhase) :
  17950. bindingName;
  17951. var handlerName = name && bindingName ? name + "_" + bindingFnName + "_HostBindingHandler" : null;
  17952. var params = prepareEventListenerParameters(BoundEvent.fromParsedEvent(binding), handlerName);
  17953. var instruction = binding.type == 1 /* Animation */ ? Identifiers$1.componentHostSyntheticListener : Identifiers$1.listener;
  17954. return importExpr(instruction).callFn(params).toStmt();
  17955. });
  17956. }
  17957. function metadataAsSummary(meta) {
  17958. // clang-format off
  17959. return {
  17960. // This is used by the BindingParser, which only deals with listeners and properties. There's no
  17961. // need to pass attributes to it.
  17962. hostAttributes: {},
  17963. hostListeners: meta.listeners,
  17964. hostProperties: meta.properties,
  17965. };
  17966. // clang-format on
  17967. }
  17968. function typeMapToExpressionMap(map, outputCtx) {
  17969. // Convert each map entry into another entry where the value is an expression importing the type.
  17970. var entries = Array.from(map).map(function (_a) {
  17971. var _b = __read(_a, 2), key = _b[0], type = _b[1];
  17972. return [key, outputCtx.importExpr(type)];
  17973. });
  17974. return new Map(entries);
  17975. }
  17976. var HOST_REG_EXP$1 = /^(?:\[([^\]]+)\])|(?:\(([^\)]+)\))$/;
  17977. function parseHostBindings(host) {
  17978. var e_4, _a;
  17979. var attributes = {};
  17980. var listeners = {};
  17981. var properties = {};
  17982. var specialAttributes = {};
  17983. try {
  17984. for (var _b = __values(Object.keys(host)), _c = _b.next(); !_c.done; _c = _b.next()) {
  17985. var key = _c.value;
  17986. var value = host[key];
  17987. var matches = key.match(HOST_REG_EXP$1);
  17988. if (matches === null) {
  17989. switch (key) {
  17990. case 'class':
  17991. if (typeof value !== 'string') {
  17992. // TODO(alxhub): make this a diagnostic.
  17993. throw new Error("Class binding must be string");
  17994. }
  17995. specialAttributes.classAttr = value;
  17996. break;
  17997. case 'style':
  17998. if (typeof value !== 'string') {
  17999. // TODO(alxhub): make this a diagnostic.
  18000. throw new Error("Style binding must be string");
  18001. }
  18002. specialAttributes.styleAttr = value;
  18003. break;
  18004. default:
  18005. if (typeof value === 'string') {
  18006. attributes[key] = literal(value);
  18007. }
  18008. else {
  18009. attributes[key] = value;
  18010. }
  18011. }
  18012. }
  18013. else if (matches[1 /* Binding */] != null) {
  18014. if (typeof value !== 'string') {
  18015. // TODO(alxhub): make this a diagnostic.
  18016. throw new Error("Property binding must be string");
  18017. }
  18018. // synthetic properties (the ones that have a `@` as a prefix)
  18019. // are still treated the same as regular properties. Therefore
  18020. // there is no point in storing them in a separate map.
  18021. properties[matches[1 /* Binding */]] = value;
  18022. }
  18023. else if (matches[2 /* Event */] != null) {
  18024. if (typeof value !== 'string') {
  18025. // TODO(alxhub): make this a diagnostic.
  18026. throw new Error("Event binding must be string");
  18027. }
  18028. listeners[matches[2 /* Event */]] = value;
  18029. }
  18030. }
  18031. }
  18032. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  18033. finally {
  18034. try {
  18035. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  18036. }
  18037. finally { if (e_4) throw e_4.error; }
  18038. }
  18039. return { attributes: attributes, listeners: listeners, properties: properties, specialAttributes: specialAttributes };
  18040. }
  18041. /**
  18042. * Verifies host bindings and returns the list of errors (if any). Empty array indicates that a
  18043. * given set of host bindings has no errors.
  18044. *
  18045. * @param bindings set of host bindings to verify.
  18046. * @param sourceSpan source span where host bindings were defined.
  18047. * @returns array of errors associated with a given set of host bindings.
  18048. */
  18049. function verifyHostBindings(bindings, sourceSpan) {
  18050. var summary = metadataAsSummary(bindings);
  18051. // TODO: abstract out host bindings verification logic and use it instead of
  18052. // creating events and properties ASTs to detect errors (FW-996)
  18053. var bindingParser = makeBindingParser();
  18054. bindingParser.createDirectiveHostEventAsts(summary, sourceSpan);
  18055. bindingParser.createBoundHostProperties(summary, sourceSpan);
  18056. return bindingParser.errors;
  18057. }
  18058. function compileStyles(styles, selector, hostSelector) {
  18059. var shadowCss = new ShadowCss();
  18060. return styles.map(function (style) { return shadowCss.shimCssText(style, selector, hostSelector); });
  18061. }
  18062. /**
  18063. * @license
  18064. * Copyright Google Inc. All Rights Reserved.
  18065. *
  18066. * Use of this source code is governed by an MIT-style license that can be
  18067. * found in the LICENSE file at https://angular.io/license
  18068. */
  18069. /**
  18070. * An interface for retrieving documents by URL that the compiler uses
  18071. * to load templates.
  18072. */
  18073. var ResourceLoader = /** @class */ (function () {
  18074. function ResourceLoader() {
  18075. }
  18076. ResourceLoader.prototype.get = function (url) { return ''; };
  18077. return ResourceLoader;
  18078. }());
  18079. /**
  18080. * @license
  18081. * Copyright Google Inc. All Rights Reserved.
  18082. *
  18083. * Use of this source code is governed by an MIT-style license that can be
  18084. * found in the LICENSE file at https://angular.io/license
  18085. */
  18086. var CompilerFacadeImpl = /** @class */ (function () {
  18087. function CompilerFacadeImpl(jitEvaluator) {
  18088. if (jitEvaluator === void 0) { jitEvaluator = new JitEvaluator(); }
  18089. this.jitEvaluator = jitEvaluator;
  18090. this.R3ResolvedDependencyType = exports.R3ResolvedDependencyType;
  18091. this.ResourceLoader = ResourceLoader;
  18092. this.elementSchemaRegistry = new DomElementSchemaRegistry();
  18093. }
  18094. CompilerFacadeImpl.prototype.compilePipe = function (angularCoreEnv, sourceMapUrl, facade) {
  18095. var res = compilePipeFromMetadata({
  18096. name: facade.name,
  18097. type: new WrappedNodeExpr(facade.type),
  18098. typeArgumentCount: facade.typeArgumentCount,
  18099. deps: convertR3DependencyMetadataArray(facade.deps),
  18100. pipeName: facade.pipeName,
  18101. pure: facade.pure,
  18102. });
  18103. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, res.statements);
  18104. };
  18105. CompilerFacadeImpl.prototype.compileInjectable = function (angularCoreEnv, sourceMapUrl, facade) {
  18106. var _a = compileInjectable({
  18107. name: facade.name,
  18108. type: new WrappedNodeExpr(facade.type),
  18109. typeArgumentCount: facade.typeArgumentCount,
  18110. providedIn: computeProvidedIn(facade.providedIn),
  18111. useClass: wrapExpression(facade, USE_CLASS),
  18112. useFactory: wrapExpression(facade, USE_FACTORY),
  18113. useValue: wrapExpression(facade, USE_VALUE),
  18114. useExisting: wrapExpression(facade, USE_EXISTING),
  18115. ctorDeps: convertR3DependencyMetadataArray(facade.ctorDeps),
  18116. userDeps: convertR3DependencyMetadataArray(facade.userDeps) || undefined,
  18117. }), expression = _a.expression, statements = _a.statements;
  18118. return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, statements);
  18119. };
  18120. CompilerFacadeImpl.prototype.compileInjector = function (angularCoreEnv, sourceMapUrl, facade) {
  18121. var meta = {
  18122. name: facade.name,
  18123. type: new WrappedNodeExpr(facade.type),
  18124. deps: convertR3DependencyMetadataArray(facade.deps),
  18125. providers: new WrappedNodeExpr(facade.providers),
  18126. imports: facade.imports.map(function (i) { return new WrappedNodeExpr(i); }),
  18127. };
  18128. var res = compileInjector(meta);
  18129. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, res.statements);
  18130. };
  18131. CompilerFacadeImpl.prototype.compileNgModule = function (angularCoreEnv, sourceMapUrl, facade) {
  18132. var meta = {
  18133. type: new WrappedNodeExpr(facade.type),
  18134. bootstrap: facade.bootstrap.map(wrapReference),
  18135. declarations: facade.declarations.map(wrapReference),
  18136. imports: facade.imports.map(wrapReference),
  18137. exports: facade.exports.map(wrapReference),
  18138. emitInline: true,
  18139. containsForwardDecls: false,
  18140. schemas: facade.schemas ? facade.schemas.map(wrapReference) : null,
  18141. id: facade.id ? new WrappedNodeExpr(facade.id) : null,
  18142. };
  18143. var res = compileNgModule(meta);
  18144. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
  18145. };
  18146. CompilerFacadeImpl.prototype.compileDirective = function (angularCoreEnv, sourceMapUrl, facade) {
  18147. var constantPool = new ConstantPool();
  18148. var bindingParser = makeBindingParser();
  18149. var meta = convertDirectiveFacadeToMetadata(facade);
  18150. var res = compileDirectiveFromMetadata(meta, constantPool, bindingParser);
  18151. var preStatements = __spread(constantPool.statements, res.statements);
  18152. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, preStatements);
  18153. };
  18154. CompilerFacadeImpl.prototype.compileComponent = function (angularCoreEnv, sourceMapUrl, facade) {
  18155. // The ConstantPool is a requirement of the JIT'er.
  18156. var constantPool = new ConstantPool();
  18157. var interpolationConfig = facade.interpolation ?
  18158. InterpolationConfig.fromArray(facade.interpolation) :
  18159. DEFAULT_INTERPOLATION_CONFIG;
  18160. // Parse the template and check for errors.
  18161. var template = parseTemplate(facade.template, sourceMapUrl, { preserveWhitespaces: facade.preserveWhitespaces, interpolationConfig: interpolationConfig });
  18162. if (template.errors !== undefined) {
  18163. var errors = template.errors.map(function (err) { return err.toString(); }).join(', ');
  18164. throw new Error("Errors during JIT compilation of template for " + facade.name + ": " + errors);
  18165. }
  18166. // Compile the component metadata, including template, into an expression.
  18167. // TODO(alxhub): implement inputs, outputs, queries, etc.
  18168. 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) :
  18169. null, relativeContextFilePath: '', i18nUseExternalIds: true }), constantPool, makeBindingParser(interpolationConfig));
  18170. var preStatements = __spread(constantPool.statements, res.statements);
  18171. return this.jitExpression(res.expression, angularCoreEnv, "ng:///" + facade.name + ".js", preStatements);
  18172. };
  18173. CompilerFacadeImpl.prototype.compileBase = function (angularCoreEnv, sourceMapUrl, facade) {
  18174. var constantPool = new ConstantPool();
  18175. var typeSourceSpan = this.createParseSourceSpan('Base', facade.name, "ng:///" + facade.name + ".js");
  18176. var meta = __assign({}, facade, { typeSourceSpan: typeSourceSpan, viewQueries: facade.viewQueries ? facade.viewQueries.map(convertToR3QueryMetadata) :
  18177. facade.viewQueries, queries: facade.queries ? facade.queries.map(convertToR3QueryMetadata) : facade.queries, host: extractHostBindings(facade.propMetadata, typeSourceSpan) });
  18178. var res = compileBaseDefFromMetadata(meta, constantPool, makeBindingParser());
  18179. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, constantPool.statements);
  18180. };
  18181. CompilerFacadeImpl.prototype.createParseSourceSpan = function (kind, typeName, sourceUrl) {
  18182. return r3JitTypeSourceSpan(kind, typeName, sourceUrl);
  18183. };
  18184. /**
  18185. * JIT compiles an expression and returns the result of executing that expression.
  18186. *
  18187. * @param def the definition which will be compiled and executed to get the value to patch
  18188. * @param context an object map of @angular/core symbol names to symbols which will be available
  18189. * in the context of the compiled expression
  18190. * @param sourceUrl a URL to use for the source map of the compiled expression
  18191. * @param preStatements a collection of statements that should be evaluated before the expression.
  18192. */
  18193. CompilerFacadeImpl.prototype.jitExpression = function (def, context, sourceUrl, preStatements) {
  18194. // The ConstantPool may contain Statements which declare variables used in the final expression.
  18195. // Therefore, its statements need to precede the actual JIT operation. The final statement is a
  18196. // declaration of $def which is set to the expression being compiled.
  18197. var statements = __spread(preStatements, [
  18198. new DeclareVarStmt('$def', def, undefined, [exports.StmtModifier.Exported]),
  18199. ]);
  18200. var res = this.jitEvaluator.evaluateStatements(sourceUrl, statements, new R3JitReflector(context), /* enableSourceMaps */ true);
  18201. return res['$def'];
  18202. };
  18203. return CompilerFacadeImpl;
  18204. }());
  18205. var USE_CLASS = Object.keys({ useClass: null })[0];
  18206. var USE_FACTORY = Object.keys({ useFactory: null })[0];
  18207. var USE_VALUE = Object.keys({ useValue: null })[0];
  18208. var USE_EXISTING = Object.keys({ useExisting: null })[0];
  18209. var wrapReference = function (value) {
  18210. var wrapped = new WrappedNodeExpr(value);
  18211. return { value: wrapped, type: wrapped };
  18212. };
  18213. function convertToR3QueryMetadata(facade) {
  18214. return __assign({}, facade, { predicate: Array.isArray(facade.predicate) ? facade.predicate :
  18215. new WrappedNodeExpr(facade.predicate), read: facade.read ? new WrappedNodeExpr(facade.read) : null, static: facade.static });
  18216. }
  18217. function convertDirectiveFacadeToMetadata(facade) {
  18218. var inputsFromMetadata = parseInputOutputs(facade.inputs || []);
  18219. var outputsFromMetadata = parseInputOutputs(facade.outputs || []);
  18220. var propMetadata = facade.propMetadata;
  18221. var inputsFromType = {};
  18222. var outputsFromType = {};
  18223. var _loop_1 = function (field) {
  18224. if (propMetadata.hasOwnProperty(field)) {
  18225. propMetadata[field].forEach(function (ann) {
  18226. if (isInput(ann)) {
  18227. inputsFromType[field] =
  18228. ann.bindingPropertyName ? [ann.bindingPropertyName, field] : field;
  18229. }
  18230. else if (isOutput(ann)) {
  18231. outputsFromType[field] = ann.bindingPropertyName || field;
  18232. }
  18233. });
  18234. }
  18235. };
  18236. for (var field in propMetadata) {
  18237. _loop_1(field);
  18238. }
  18239. 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) });
  18240. }
  18241. function wrapExpression(obj, property) {
  18242. if (obj.hasOwnProperty(property)) {
  18243. return new WrappedNodeExpr(obj[property]);
  18244. }
  18245. else {
  18246. return undefined;
  18247. }
  18248. }
  18249. function computeProvidedIn(providedIn) {
  18250. if (providedIn == null || typeof providedIn === 'string') {
  18251. return new LiteralExpr(providedIn);
  18252. }
  18253. else {
  18254. return new WrappedNodeExpr(providedIn);
  18255. }
  18256. }
  18257. function convertR3DependencyMetadata(facade) {
  18258. var tokenExpr;
  18259. if (facade.token === null) {
  18260. tokenExpr = new LiteralExpr(null);
  18261. }
  18262. else if (facade.resolved === exports.R3ResolvedDependencyType.Attribute) {
  18263. tokenExpr = new LiteralExpr(facade.token);
  18264. }
  18265. else {
  18266. tokenExpr = new WrappedNodeExpr(facade.token);
  18267. }
  18268. return {
  18269. token: tokenExpr,
  18270. resolved: facade.resolved,
  18271. host: facade.host,
  18272. optional: facade.optional,
  18273. self: facade.self,
  18274. skipSelf: facade.skipSelf
  18275. };
  18276. }
  18277. function convertR3DependencyMetadataArray(facades) {
  18278. return facades == null ? null : facades.map(convertR3DependencyMetadata);
  18279. }
  18280. function extractHostBindings(propMetadata, sourceSpan, host) {
  18281. // First parse the declarations from the metadata.
  18282. var bindings = parseHostBindings(host || {});
  18283. // After that check host bindings for errors
  18284. var errors = verifyHostBindings(bindings, sourceSpan);
  18285. if (errors.length) {
  18286. throw new Error(errors.map(function (error) { return error.msg; }).join('\n'));
  18287. }
  18288. var _loop_2 = function (field) {
  18289. if (propMetadata.hasOwnProperty(field)) {
  18290. propMetadata[field].forEach(function (ann) {
  18291. if (isHostBinding(ann)) {
  18292. bindings.properties[ann.hostPropertyName || field] = field;
  18293. }
  18294. else if (isHostListener(ann)) {
  18295. bindings.listeners[ann.eventName || field] = field + "(" + (ann.args || []).join(',') + ")";
  18296. }
  18297. });
  18298. }
  18299. };
  18300. // Next, loop over the properties of the object, looking for @HostBinding and @HostListener.
  18301. for (var field in propMetadata) {
  18302. _loop_2(field);
  18303. }
  18304. return bindings;
  18305. }
  18306. function isHostBinding(value) {
  18307. return value.ngMetadataName === 'HostBinding';
  18308. }
  18309. function isHostListener(value) {
  18310. return value.ngMetadataName === 'HostListener';
  18311. }
  18312. function isInput(value) {
  18313. return value.ngMetadataName === 'Input';
  18314. }
  18315. function isOutput(value) {
  18316. return value.ngMetadataName === 'Output';
  18317. }
  18318. function parseInputOutputs(values) {
  18319. return values.reduce(function (map, value) {
  18320. var _a = __read(value.split(',').map(function (piece) { return piece.trim(); }), 2), field = _a[0], property = _a[1];
  18321. map[field] = property || field;
  18322. return map;
  18323. }, {});
  18324. }
  18325. function publishFacade(global) {
  18326. var ng = global.ng || (global.ng = {});
  18327. ng.ɵcompilerFacade = new CompilerFacadeImpl();
  18328. }
  18329. /**
  18330. * @license
  18331. * Copyright Google Inc. All Rights Reserved.
  18332. *
  18333. * Use of this source code is governed by an MIT-style license that can be
  18334. * found in the LICENSE file at https://angular.io/license
  18335. */
  18336. var VERSION$1 = new Version('8.1.0');
  18337. /**
  18338. * @license
  18339. * Copyright Google Inc. All Rights Reserved.
  18340. *
  18341. * Use of this source code is governed by an MIT-style license that can be
  18342. * found in the LICENSE file at https://angular.io/license
  18343. */
  18344. var CompilerConfig = /** @class */ (function () {
  18345. function CompilerConfig(_a) {
  18346. 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;
  18347. this.defaultEncapsulation = defaultEncapsulation;
  18348. this.useJit = !!useJit;
  18349. this.jitDevMode = !!jitDevMode;
  18350. this.missingTranslation = missingTranslation;
  18351. this.preserveWhitespaces = preserveWhitespacesDefault(noUndefined(preserveWhitespaces));
  18352. this.strictInjectionParameters = strictInjectionParameters === true;
  18353. }
  18354. return CompilerConfig;
  18355. }());
  18356. function preserveWhitespacesDefault(preserveWhitespacesOption, defaultSetting) {
  18357. if (defaultSetting === void 0) { defaultSetting = false; }
  18358. return preserveWhitespacesOption === null ? defaultSetting : preserveWhitespacesOption;
  18359. }
  18360. /**
  18361. * @license
  18362. * Copyright Google Inc. All Rights Reserved.
  18363. *
  18364. * Use of this source code is governed by an MIT-style license that can be
  18365. * found in the LICENSE file at https://angular.io/license
  18366. */
  18367. var DirectiveNormalizer = /** @class */ (function () {
  18368. function DirectiveNormalizer(_resourceLoader, _urlResolver, _htmlParser, _config) {
  18369. this._resourceLoader = _resourceLoader;
  18370. this._urlResolver = _urlResolver;
  18371. this._htmlParser = _htmlParser;
  18372. this._config = _config;
  18373. this._resourceLoaderCache = new Map();
  18374. }
  18375. DirectiveNormalizer.prototype.clearCache = function () { this._resourceLoaderCache.clear(); };
  18376. DirectiveNormalizer.prototype.clearCacheFor = function (normalizedDirective) {
  18377. var _this = this;
  18378. if (!normalizedDirective.isComponent) {
  18379. return;
  18380. }
  18381. var template = normalizedDirective.template;
  18382. this._resourceLoaderCache.delete(template.templateUrl);
  18383. template.externalStylesheets.forEach(function (stylesheet) { _this._resourceLoaderCache.delete(stylesheet.moduleUrl); });
  18384. };
  18385. DirectiveNormalizer.prototype._fetch = function (url) {
  18386. var result = this._resourceLoaderCache.get(url);
  18387. if (!result) {
  18388. result = this._resourceLoader.get(url);
  18389. this._resourceLoaderCache.set(url, result);
  18390. }
  18391. return result;
  18392. };
  18393. DirectiveNormalizer.prototype.normalizeTemplate = function (prenormData) {
  18394. var _this = this;
  18395. if (isDefined(prenormData.template)) {
  18396. if (isDefined(prenormData.templateUrl)) {
  18397. throw syntaxError("'" + stringify(prenormData.componentType) + "' component cannot define both template and templateUrl");
  18398. }
  18399. if (typeof prenormData.template !== 'string') {
  18400. throw syntaxError("The template specified for component " + stringify(prenormData.componentType) + " is not a string");
  18401. }
  18402. }
  18403. else if (isDefined(prenormData.templateUrl)) {
  18404. if (typeof prenormData.templateUrl !== 'string') {
  18405. throw syntaxError("The templateUrl specified for component " + stringify(prenormData.componentType) + " is not a string");
  18406. }
  18407. }
  18408. else {
  18409. throw syntaxError("No template specified for component " + stringify(prenormData.componentType));
  18410. }
  18411. if (isDefined(prenormData.preserveWhitespaces) &&
  18412. typeof prenormData.preserveWhitespaces !== 'boolean') {
  18413. throw syntaxError("The preserveWhitespaces option for component " + stringify(prenormData.componentType) + " must be a boolean");
  18414. }
  18415. return SyncAsync.then(this._preParseTemplate(prenormData), function (preparsedTemplate) { return _this._normalizeTemplateMetadata(prenormData, preparsedTemplate); });
  18416. };
  18417. DirectiveNormalizer.prototype._preParseTemplate = function (prenomData) {
  18418. var _this = this;
  18419. var template;
  18420. var templateUrl;
  18421. if (prenomData.template != null) {
  18422. template = prenomData.template;
  18423. templateUrl = prenomData.moduleUrl;
  18424. }
  18425. else {
  18426. templateUrl = this._urlResolver.resolve(prenomData.moduleUrl, prenomData.templateUrl);
  18427. template = this._fetch(templateUrl);
  18428. }
  18429. return SyncAsync.then(template, function (template) { return _this._preparseLoadedTemplate(prenomData, template, templateUrl); });
  18430. };
  18431. DirectiveNormalizer.prototype._preparseLoadedTemplate = function (prenormData, template, templateAbsUrl) {
  18432. var isInline = !!prenormData.template;
  18433. var interpolationConfig = InterpolationConfig.fromArray(prenormData.interpolation);
  18434. var templateUrl = templateSourceUrl({ reference: prenormData.ngModuleType }, { type: { reference: prenormData.componentType } }, { isInline: isInline, templateUrl: templateAbsUrl });
  18435. var rootNodesAndErrors = this._htmlParser.parse(template, templateUrl, { tokenizeExpansionForms: true, interpolationConfig: interpolationConfig });
  18436. if (rootNodesAndErrors.errors.length > 0) {
  18437. var errorString = rootNodesAndErrors.errors.join('\n');
  18438. throw syntaxError("Template parse errors:\n" + errorString);
  18439. }
  18440. var templateMetadataStyles = this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: prenormData.styles, moduleUrl: prenormData.moduleUrl }));
  18441. var visitor = new TemplatePreparseVisitor();
  18442. visitAll$1(visitor, rootNodesAndErrors.rootNodes);
  18443. var templateStyles = this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: visitor.styles, styleUrls: visitor.styleUrls, moduleUrl: templateAbsUrl }));
  18444. var styles = templateMetadataStyles.styles.concat(templateStyles.styles);
  18445. var inlineStyleUrls = templateMetadataStyles.styleUrls.concat(templateStyles.styleUrls);
  18446. var styleUrls = this
  18447. ._normalizeStylesheet(new CompileStylesheetMetadata({ styleUrls: prenormData.styleUrls, moduleUrl: prenormData.moduleUrl }))
  18448. .styleUrls;
  18449. return {
  18450. template: template,
  18451. templateUrl: templateAbsUrl, isInline: isInline,
  18452. htmlAst: rootNodesAndErrors, styles: styles, inlineStyleUrls: inlineStyleUrls, styleUrls: styleUrls,
  18453. ngContentSelectors: visitor.ngContentSelectors,
  18454. };
  18455. };
  18456. DirectiveNormalizer.prototype._normalizeTemplateMetadata = function (prenormData, preparsedTemplate) {
  18457. var _this = this;
  18458. return SyncAsync.then(this._loadMissingExternalStylesheets(preparsedTemplate.styleUrls.concat(preparsedTemplate.inlineStyleUrls)), function (externalStylesheets) { return _this._normalizeLoadedTemplateMetadata(prenormData, preparsedTemplate, externalStylesheets); });
  18459. };
  18460. DirectiveNormalizer.prototype._normalizeLoadedTemplateMetadata = function (prenormData, preparsedTemplate, stylesheets) {
  18461. // Algorithm:
  18462. // - produce exactly 1 entry per original styleUrl in
  18463. // CompileTemplateMetadata.externalStylesheets with all styles inlined
  18464. // - inline all styles that are referenced by the template into CompileTemplateMetadata.styles.
  18465. // Reason: be able to determine how many stylesheets there are even without loading
  18466. // the template nor the stylesheets, so we can create a stub for TypeScript always synchronously
  18467. // (as resource loading may be async)
  18468. var _this = this;
  18469. var styles = __spread(preparsedTemplate.styles);
  18470. this._inlineStyles(preparsedTemplate.inlineStyleUrls, stylesheets, styles);
  18471. var styleUrls = preparsedTemplate.styleUrls;
  18472. var externalStylesheets = styleUrls.map(function (styleUrl) {
  18473. var stylesheet = stylesheets.get(styleUrl);
  18474. var styles = __spread(stylesheet.styles);
  18475. _this._inlineStyles(stylesheet.styleUrls, stylesheets, styles);
  18476. return new CompileStylesheetMetadata({ moduleUrl: styleUrl, styles: styles });
  18477. });
  18478. var encapsulation = prenormData.encapsulation;
  18479. if (encapsulation == null) {
  18480. encapsulation = this._config.defaultEncapsulation;
  18481. }
  18482. if (encapsulation === ViewEncapsulation.Emulated && styles.length === 0 &&
  18483. styleUrls.length === 0) {
  18484. encapsulation = ViewEncapsulation.None;
  18485. }
  18486. return new CompileTemplateMetadata({
  18487. encapsulation: encapsulation,
  18488. template: preparsedTemplate.template,
  18489. templateUrl: preparsedTemplate.templateUrl,
  18490. htmlAst: preparsedTemplate.htmlAst, styles: styles, styleUrls: styleUrls,
  18491. ngContentSelectors: preparsedTemplate.ngContentSelectors,
  18492. animations: prenormData.animations,
  18493. interpolation: prenormData.interpolation,
  18494. isInline: preparsedTemplate.isInline, externalStylesheets: externalStylesheets,
  18495. preserveWhitespaces: preserveWhitespacesDefault(prenormData.preserveWhitespaces, this._config.preserveWhitespaces),
  18496. });
  18497. };
  18498. DirectiveNormalizer.prototype._inlineStyles = function (styleUrls, stylesheets, targetStyles) {
  18499. var _this = this;
  18500. styleUrls.forEach(function (styleUrl) {
  18501. var stylesheet = stylesheets.get(styleUrl);
  18502. stylesheet.styles.forEach(function (style) { return targetStyles.push(style); });
  18503. _this._inlineStyles(stylesheet.styleUrls, stylesheets, targetStyles);
  18504. });
  18505. };
  18506. DirectiveNormalizer.prototype._loadMissingExternalStylesheets = function (styleUrls, loadedStylesheets) {
  18507. var _this = this;
  18508. if (loadedStylesheets === void 0) { loadedStylesheets = new Map(); }
  18509. return SyncAsync.then(SyncAsync.all(styleUrls.filter(function (styleUrl) { return !loadedStylesheets.has(styleUrl); })
  18510. .map(function (styleUrl) { return SyncAsync.then(_this._fetch(styleUrl), function (loadedStyle) {
  18511. var stylesheet = _this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: [loadedStyle], moduleUrl: styleUrl }));
  18512. loadedStylesheets.set(styleUrl, stylesheet);
  18513. return _this._loadMissingExternalStylesheets(stylesheet.styleUrls, loadedStylesheets);
  18514. }); })), function (_) { return loadedStylesheets; });
  18515. };
  18516. DirectiveNormalizer.prototype._normalizeStylesheet = function (stylesheet) {
  18517. var _this = this;
  18518. var moduleUrl = stylesheet.moduleUrl;
  18519. var allStyleUrls = stylesheet.styleUrls.filter(isStyleUrlResolvable)
  18520. .map(function (url) { return _this._urlResolver.resolve(moduleUrl, url); });
  18521. var allStyles = stylesheet.styles.map(function (style) {
  18522. var styleWithImports = extractStyleUrls(_this._urlResolver, moduleUrl, style);
  18523. allStyleUrls.push.apply(allStyleUrls, __spread(styleWithImports.styleUrls));
  18524. return styleWithImports.style;
  18525. });
  18526. return new CompileStylesheetMetadata({ styles: allStyles, styleUrls: allStyleUrls, moduleUrl: moduleUrl });
  18527. };
  18528. return DirectiveNormalizer;
  18529. }());
  18530. var TemplatePreparseVisitor = /** @class */ (function () {
  18531. function TemplatePreparseVisitor() {
  18532. this.ngContentSelectors = [];
  18533. this.styles = [];
  18534. this.styleUrls = [];
  18535. this.ngNonBindableStackCount = 0;
  18536. }
  18537. TemplatePreparseVisitor.prototype.visitElement = function (ast, context) {
  18538. var preparsedElement = preparseElement(ast);
  18539. switch (preparsedElement.type) {
  18540. case PreparsedElementType.NG_CONTENT:
  18541. if (this.ngNonBindableStackCount === 0) {
  18542. this.ngContentSelectors.push(preparsedElement.selectAttr);
  18543. }
  18544. break;
  18545. case PreparsedElementType.STYLE:
  18546. var textContent_1 = '';
  18547. ast.children.forEach(function (child) {
  18548. if (child instanceof Text$3) {
  18549. textContent_1 += child.value;
  18550. }
  18551. });
  18552. this.styles.push(textContent_1);
  18553. break;
  18554. case PreparsedElementType.STYLESHEET:
  18555. this.styleUrls.push(preparsedElement.hrefAttr);
  18556. break;
  18557. default:
  18558. break;
  18559. }
  18560. if (preparsedElement.nonBindable) {
  18561. this.ngNonBindableStackCount++;
  18562. }
  18563. visitAll$1(this, ast.children);
  18564. if (preparsedElement.nonBindable) {
  18565. this.ngNonBindableStackCount--;
  18566. }
  18567. return null;
  18568. };
  18569. TemplatePreparseVisitor.prototype.visitExpansion = function (ast, context) { visitAll$1(this, ast.cases); };
  18570. TemplatePreparseVisitor.prototype.visitExpansionCase = function (ast, context) {
  18571. visitAll$1(this, ast.expression);
  18572. };
  18573. TemplatePreparseVisitor.prototype.visitComment = function (ast, context) { return null; };
  18574. TemplatePreparseVisitor.prototype.visitAttribute = function (ast, context) { return null; };
  18575. TemplatePreparseVisitor.prototype.visitText = function (ast, context) { return null; };
  18576. return TemplatePreparseVisitor;
  18577. }());
  18578. /**
  18579. * @license
  18580. * Copyright Google Inc. All Rights Reserved.
  18581. *
  18582. * Use of this source code is governed by an MIT-style license that can be
  18583. * found in the LICENSE file at https://angular.io/license
  18584. */
  18585. var QUERY_METADATA_IDENTIFIERS = [
  18586. createViewChild,
  18587. createViewChildren,
  18588. createContentChild,
  18589. createContentChildren,
  18590. ];
  18591. /*
  18592. * Resolve a `Type` for {@link Directive}.
  18593. *
  18594. * This interface can be overridden by the application developer to create custom behavior.
  18595. *
  18596. * See {@link Compiler}
  18597. */
  18598. var DirectiveResolver = /** @class */ (function () {
  18599. function DirectiveResolver(_reflector) {
  18600. this._reflector = _reflector;
  18601. }
  18602. DirectiveResolver.prototype.isDirective = function (type) {
  18603. var typeMetadata = this._reflector.annotations(resolveForwardRef(type));
  18604. return typeMetadata && typeMetadata.some(isDirectiveMetadata);
  18605. };
  18606. DirectiveResolver.prototype.resolve = function (type, throwIfNotFound) {
  18607. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  18608. var typeMetadata = this._reflector.annotations(resolveForwardRef(type));
  18609. if (typeMetadata) {
  18610. var metadata = findLast(typeMetadata, isDirectiveMetadata);
  18611. if (metadata) {
  18612. var propertyMetadata = this._reflector.propMetadata(type);
  18613. var guards = this._reflector.guards(type);
  18614. return this._mergeWithPropertyMetadata(metadata, propertyMetadata, guards, type);
  18615. }
  18616. }
  18617. if (throwIfNotFound) {
  18618. throw new Error("No Directive annotation found on " + stringify(type));
  18619. }
  18620. return null;
  18621. };
  18622. DirectiveResolver.prototype._mergeWithPropertyMetadata = function (dm, propertyMetadata, guards, directiveType) {
  18623. var inputs = [];
  18624. var outputs = [];
  18625. var host = {};
  18626. var queries = {};
  18627. Object.keys(propertyMetadata).forEach(function (propName) {
  18628. var input = findLast(propertyMetadata[propName], function (a) { return createInput.isTypeOf(a); });
  18629. if (input) {
  18630. if (input.bindingPropertyName) {
  18631. inputs.push(propName + ": " + input.bindingPropertyName);
  18632. }
  18633. else {
  18634. inputs.push(propName);
  18635. }
  18636. }
  18637. var output = findLast(propertyMetadata[propName], function (a) { return createOutput.isTypeOf(a); });
  18638. if (output) {
  18639. if (output.bindingPropertyName) {
  18640. outputs.push(propName + ": " + output.bindingPropertyName);
  18641. }
  18642. else {
  18643. outputs.push(propName);
  18644. }
  18645. }
  18646. var hostBindings = propertyMetadata[propName].filter(function (a) { return createHostBinding.isTypeOf(a); });
  18647. hostBindings.forEach(function (hostBinding) {
  18648. if (hostBinding.hostPropertyName) {
  18649. var startWith = hostBinding.hostPropertyName[0];
  18650. if (startWith === '(') {
  18651. throw new Error("@HostBinding can not bind to events. Use @HostListener instead.");
  18652. }
  18653. else if (startWith === '[') {
  18654. throw new Error("@HostBinding parameter should be a property name, 'class.<name>', or 'attr.<name>'.");
  18655. }
  18656. host["[" + hostBinding.hostPropertyName + "]"] = propName;
  18657. }
  18658. else {
  18659. host["[" + propName + "]"] = propName;
  18660. }
  18661. });
  18662. var hostListeners = propertyMetadata[propName].filter(function (a) { return createHostListener.isTypeOf(a); });
  18663. hostListeners.forEach(function (hostListener) {
  18664. var args = hostListener.args || [];
  18665. host["(" + hostListener.eventName + ")"] = propName + "(" + args.join(',') + ")";
  18666. });
  18667. var query = findLast(propertyMetadata[propName], function (a) { return QUERY_METADATA_IDENTIFIERS.some(function (i) { return i.isTypeOf(a); }); });
  18668. if (query) {
  18669. queries[propName] = query;
  18670. }
  18671. });
  18672. return this._merge(dm, inputs, outputs, host, queries, guards, directiveType);
  18673. };
  18674. DirectiveResolver.prototype._extractPublicName = function (def) { return splitAtColon(def, [null, def])[1].trim(); };
  18675. DirectiveResolver.prototype._dedupeBindings = function (bindings) {
  18676. var names = new Set();
  18677. var publicNames = new Set();
  18678. var reversedResult = [];
  18679. // go last to first to allow later entries to overwrite previous entries
  18680. for (var i = bindings.length - 1; i >= 0; i--) {
  18681. var binding = bindings[i];
  18682. var name_1 = this._extractPublicName(binding);
  18683. publicNames.add(name_1);
  18684. if (!names.has(name_1)) {
  18685. names.add(name_1);
  18686. reversedResult.push(binding);
  18687. }
  18688. }
  18689. return reversedResult.reverse();
  18690. };
  18691. DirectiveResolver.prototype._merge = function (directive, inputs, outputs, host, queries, guards, directiveType) {
  18692. var mergedInputs = this._dedupeBindings(directive.inputs ? directive.inputs.concat(inputs) : inputs);
  18693. var mergedOutputs = this._dedupeBindings(directive.outputs ? directive.outputs.concat(outputs) : outputs);
  18694. var mergedHost = directive.host ? __assign({}, directive.host, host) : host;
  18695. var mergedQueries = directive.queries ? __assign({}, directive.queries, queries) : queries;
  18696. if (createComponent.isTypeOf(directive)) {
  18697. var comp = directive;
  18698. return createComponent({
  18699. selector: comp.selector,
  18700. inputs: mergedInputs,
  18701. outputs: mergedOutputs,
  18702. host: mergedHost,
  18703. exportAs: comp.exportAs,
  18704. moduleId: comp.moduleId,
  18705. queries: mergedQueries,
  18706. changeDetection: comp.changeDetection,
  18707. providers: comp.providers,
  18708. viewProviders: comp.viewProviders,
  18709. entryComponents: comp.entryComponents,
  18710. template: comp.template,
  18711. templateUrl: comp.templateUrl,
  18712. styles: comp.styles,
  18713. styleUrls: comp.styleUrls,
  18714. encapsulation: comp.encapsulation,
  18715. animations: comp.animations,
  18716. interpolation: comp.interpolation,
  18717. preserveWhitespaces: directive.preserveWhitespaces,
  18718. });
  18719. }
  18720. else {
  18721. return createDirective({
  18722. selector: directive.selector,
  18723. inputs: mergedInputs,
  18724. outputs: mergedOutputs,
  18725. host: mergedHost,
  18726. exportAs: directive.exportAs,
  18727. queries: mergedQueries,
  18728. providers: directive.providers, guards: guards
  18729. });
  18730. }
  18731. };
  18732. return DirectiveResolver;
  18733. }());
  18734. function isDirectiveMetadata(type) {
  18735. return createDirective.isTypeOf(type) || createComponent.isTypeOf(type);
  18736. }
  18737. function findLast(arr, condition) {
  18738. for (var i = arr.length - 1; i >= 0; i--) {
  18739. if (condition(arr[i])) {
  18740. return arr[i];
  18741. }
  18742. }
  18743. return null;
  18744. }
  18745. /**
  18746. * @license
  18747. * Copyright Google Inc. All Rights Reserved.
  18748. *
  18749. * Use of this source code is governed by an MIT-style license that can be
  18750. * found in the LICENSE file at https://angular.io/license
  18751. */
  18752. /**
  18753. * An i18n error.
  18754. */
  18755. var I18nError = /** @class */ (function (_super) {
  18756. __extends(I18nError, _super);
  18757. function I18nError(span, msg) {
  18758. return _super.call(this, span, msg) || this;
  18759. }
  18760. return I18nError;
  18761. }(ParseError));
  18762. /**
  18763. * @license
  18764. * Copyright Google Inc. All Rights Reserved.
  18765. *
  18766. * Use of this source code is governed by an MIT-style license that can be
  18767. * found in the LICENSE file at https://angular.io/license
  18768. */
  18769. var _I18N_ATTR = 'i18n';
  18770. var _I18N_ATTR_PREFIX = 'i18n-';
  18771. var _I18N_COMMENT_PREFIX_REGEXP = /^i18n:?/;
  18772. var MEANING_SEPARATOR = '|';
  18773. var ID_SEPARATOR = '@@';
  18774. var i18nCommentsWarned = false;
  18775. /**
  18776. * Extract translatable messages from an html AST
  18777. */
  18778. function extractMessages(nodes, interpolationConfig, implicitTags, implicitAttrs) {
  18779. var visitor = new _Visitor$2(implicitTags, implicitAttrs);
  18780. return visitor.extract(nodes, interpolationConfig);
  18781. }
  18782. function mergeTranslations(nodes, translations, interpolationConfig, implicitTags, implicitAttrs) {
  18783. var visitor = new _Visitor$2(implicitTags, implicitAttrs);
  18784. return visitor.merge(nodes, translations, interpolationConfig);
  18785. }
  18786. var ExtractionResult = /** @class */ (function () {
  18787. function ExtractionResult(messages, errors) {
  18788. this.messages = messages;
  18789. this.errors = errors;
  18790. }
  18791. return ExtractionResult;
  18792. }());
  18793. var _VisitorMode;
  18794. (function (_VisitorMode) {
  18795. _VisitorMode[_VisitorMode["Extract"] = 0] = "Extract";
  18796. _VisitorMode[_VisitorMode["Merge"] = 1] = "Merge";
  18797. })(_VisitorMode || (_VisitorMode = {}));
  18798. /**
  18799. * This Visitor is used:
  18800. * 1. to extract all the translatable strings from an html AST (see `extract()`),
  18801. * 2. to replace the translatable strings with the actual translations (see `merge()`)
  18802. *
  18803. * @internal
  18804. */
  18805. var _Visitor$2 = /** @class */ (function () {
  18806. function _Visitor(_implicitTags, _implicitAttrs) {
  18807. this._implicitTags = _implicitTags;
  18808. this._implicitAttrs = _implicitAttrs;
  18809. }
  18810. /**
  18811. * Extracts the messages from the tree
  18812. */
  18813. _Visitor.prototype.extract = function (nodes, interpolationConfig) {
  18814. var _this = this;
  18815. this._init(_VisitorMode.Extract, interpolationConfig);
  18816. nodes.forEach(function (node) { return node.visit(_this, null); });
  18817. if (this._inI18nBlock) {
  18818. this._reportError(nodes[nodes.length - 1], 'Unclosed block');
  18819. }
  18820. return new ExtractionResult(this._messages, this._errors);
  18821. };
  18822. /**
  18823. * Returns a tree where all translatable nodes are translated
  18824. */
  18825. _Visitor.prototype.merge = function (nodes, translations, interpolationConfig) {
  18826. this._init(_VisitorMode.Merge, interpolationConfig);
  18827. this._translations = translations;
  18828. // Construct a single fake root element
  18829. var wrapper = new Element$1('wrapper', [], nodes, undefined, undefined, undefined);
  18830. var translatedNode = wrapper.visit(this, null);
  18831. if (this._inI18nBlock) {
  18832. this._reportError(nodes[nodes.length - 1], 'Unclosed block');
  18833. }
  18834. return new ParseTreeResult(translatedNode.children, this._errors);
  18835. };
  18836. _Visitor.prototype.visitExpansionCase = function (icuCase, context) {
  18837. // Parse cases for translatable html attributes
  18838. var expression = visitAll$1(this, icuCase.expression, context);
  18839. if (this._mode === _VisitorMode.Merge) {
  18840. return new ExpansionCase(icuCase.value, expression, icuCase.sourceSpan, icuCase.valueSourceSpan, icuCase.expSourceSpan);
  18841. }
  18842. };
  18843. _Visitor.prototype.visitExpansion = function (icu, context) {
  18844. this._mayBeAddBlockChildren(icu);
  18845. var wasInIcu = this._inIcu;
  18846. if (!this._inIcu) {
  18847. // nested ICU messages should not be extracted but top-level translated as a whole
  18848. if (this._isInTranslatableSection) {
  18849. this._addMessage([icu]);
  18850. }
  18851. this._inIcu = true;
  18852. }
  18853. var cases = visitAll$1(this, icu.cases, context);
  18854. if (this._mode === _VisitorMode.Merge) {
  18855. icu = new Expansion(icu.switchValue, icu.type, cases, icu.sourceSpan, icu.switchValueSourceSpan);
  18856. }
  18857. this._inIcu = wasInIcu;
  18858. return icu;
  18859. };
  18860. _Visitor.prototype.visitComment = function (comment, context) {
  18861. var isOpening = _isOpeningComment(comment);
  18862. if (isOpening && this._isInTranslatableSection) {
  18863. this._reportError(comment, 'Could not start a block inside a translatable section');
  18864. return;
  18865. }
  18866. var isClosing = _isClosingComment(comment);
  18867. if (isClosing && !this._inI18nBlock) {
  18868. this._reportError(comment, 'Trying to close an unopened block');
  18869. return;
  18870. }
  18871. if (!this._inI18nNode && !this._inIcu) {
  18872. if (!this._inI18nBlock) {
  18873. if (isOpening) {
  18874. // deprecated from v5 you should use <ng-container i18n> instead of i18n comments
  18875. if (!i18nCommentsWarned && console && console.warn) {
  18876. i18nCommentsWarned = true;
  18877. var details = comment.sourceSpan.details ? ", " + comment.sourceSpan.details : '';
  18878. // TODO(ocombe): use a log service once there is a public one available
  18879. console.warn("I18n comments are deprecated, use an <ng-container> element instead (" + comment.sourceSpan.start + details + ")");
  18880. }
  18881. this._inI18nBlock = true;
  18882. this._blockStartDepth = this._depth;
  18883. this._blockChildren = [];
  18884. this._blockMeaningAndDesc =
  18885. comment.value.replace(_I18N_COMMENT_PREFIX_REGEXP, '').trim();
  18886. this._openTranslatableSection(comment);
  18887. }
  18888. }
  18889. else {
  18890. if (isClosing) {
  18891. if (this._depth == this._blockStartDepth) {
  18892. this._closeTranslatableSection(comment, this._blockChildren);
  18893. this._inI18nBlock = false;
  18894. var message = this._addMessage(this._blockChildren, this._blockMeaningAndDesc);
  18895. // merge attributes in sections
  18896. var nodes = this._translateMessage(comment, message);
  18897. return visitAll$1(this, nodes);
  18898. }
  18899. else {
  18900. this._reportError(comment, 'I18N blocks should not cross element boundaries');
  18901. return;
  18902. }
  18903. }
  18904. }
  18905. }
  18906. };
  18907. _Visitor.prototype.visitText = function (text, context) {
  18908. if (this._isInTranslatableSection) {
  18909. this._mayBeAddBlockChildren(text);
  18910. }
  18911. return text;
  18912. };
  18913. _Visitor.prototype.visitElement = function (el, context) {
  18914. var _this = this;
  18915. this._mayBeAddBlockChildren(el);
  18916. this._depth++;
  18917. var wasInI18nNode = this._inI18nNode;
  18918. var wasInImplicitNode = this._inImplicitNode;
  18919. var childNodes = [];
  18920. var translatedChildNodes = undefined;
  18921. // Extract:
  18922. // - top level nodes with the (implicit) "i18n" attribute if not already in a section
  18923. // - ICU messages
  18924. var i18nAttr = _getI18nAttr(el);
  18925. var i18nMeta = i18nAttr ? i18nAttr.value : '';
  18926. var isImplicit = this._implicitTags.some(function (tag) { return el.name === tag; }) && !this._inIcu &&
  18927. !this._isInTranslatableSection;
  18928. var isTopLevelImplicit = !wasInImplicitNode && isImplicit;
  18929. this._inImplicitNode = wasInImplicitNode || isImplicit;
  18930. if (!this._isInTranslatableSection && !this._inIcu) {
  18931. if (i18nAttr || isTopLevelImplicit) {
  18932. this._inI18nNode = true;
  18933. var message = this._addMessage(el.children, i18nMeta);
  18934. translatedChildNodes = this._translateMessage(el, message);
  18935. }
  18936. if (this._mode == _VisitorMode.Extract) {
  18937. var isTranslatable = i18nAttr || isTopLevelImplicit;
  18938. if (isTranslatable)
  18939. this._openTranslatableSection(el);
  18940. visitAll$1(this, el.children);
  18941. if (isTranslatable)
  18942. this._closeTranslatableSection(el, el.children);
  18943. }
  18944. }
  18945. else {
  18946. if (i18nAttr || isTopLevelImplicit) {
  18947. this._reportError(el, 'Could not mark an element as translatable inside a translatable section');
  18948. }
  18949. if (this._mode == _VisitorMode.Extract) {
  18950. // Descend into child nodes for extraction
  18951. visitAll$1(this, el.children);
  18952. }
  18953. }
  18954. if (this._mode === _VisitorMode.Merge) {
  18955. var visitNodes = translatedChildNodes || el.children;
  18956. visitNodes.forEach(function (child) {
  18957. var visited = child.visit(_this, context);
  18958. if (visited && !_this._isInTranslatableSection) {
  18959. // Do not add the children from translatable sections (= i18n blocks here)
  18960. // They will be added later in this loop when the block closes (i.e. on `<!-- /i18n -->`)
  18961. childNodes = childNodes.concat(visited);
  18962. }
  18963. });
  18964. }
  18965. this._visitAttributesOf(el);
  18966. this._depth--;
  18967. this._inI18nNode = wasInI18nNode;
  18968. this._inImplicitNode = wasInImplicitNode;
  18969. if (this._mode === _VisitorMode.Merge) {
  18970. var translatedAttrs = this._translateAttributes(el);
  18971. return new Element$1(el.name, translatedAttrs, childNodes, el.sourceSpan, el.startSourceSpan, el.endSourceSpan);
  18972. }
  18973. return null;
  18974. };
  18975. _Visitor.prototype.visitAttribute = function (attribute, context) {
  18976. throw new Error('unreachable code');
  18977. };
  18978. _Visitor.prototype._init = function (mode, interpolationConfig) {
  18979. this._mode = mode;
  18980. this._inI18nBlock = false;
  18981. this._inI18nNode = false;
  18982. this._depth = 0;
  18983. this._inIcu = false;
  18984. this._msgCountAtSectionStart = undefined;
  18985. this._errors = [];
  18986. this._messages = [];
  18987. this._inImplicitNode = false;
  18988. this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
  18989. };
  18990. // looks for translatable attributes
  18991. _Visitor.prototype._visitAttributesOf = function (el) {
  18992. var _this = this;
  18993. var explicitAttrNameToValue = {};
  18994. var implicitAttrNames = this._implicitAttrs[el.name] || [];
  18995. el.attrs.filter(function (attr) { return attr.name.startsWith(_I18N_ATTR_PREFIX); })
  18996. .forEach(function (attr) { return explicitAttrNameToValue[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
  18997. attr.value; });
  18998. el.attrs.forEach(function (attr) {
  18999. if (attr.name in explicitAttrNameToValue) {
  19000. _this._addMessage([attr], explicitAttrNameToValue[attr.name]);
  19001. }
  19002. else if (implicitAttrNames.some(function (name) { return attr.name === name; })) {
  19003. _this._addMessage([attr]);
  19004. }
  19005. });
  19006. };
  19007. // add a translatable message
  19008. _Visitor.prototype._addMessage = function (ast, msgMeta) {
  19009. if (ast.length == 0 ||
  19010. ast.length == 1 && ast[0] instanceof Attribute && !ast[0].value) {
  19011. // Do not create empty messages
  19012. return null;
  19013. }
  19014. var _a = _parseMessageMeta(msgMeta), meaning = _a.meaning, description = _a.description, id = _a.id;
  19015. var message = this._createI18nMessage(ast, meaning, description, id);
  19016. this._messages.push(message);
  19017. return message;
  19018. };
  19019. // Translates the given message given the `TranslationBundle`
  19020. // This is used for translating elements / blocks - see `_translateAttributes` for attributes
  19021. // no-op when called in extraction mode (returns [])
  19022. _Visitor.prototype._translateMessage = function (el, message) {
  19023. if (message && this._mode === _VisitorMode.Merge) {
  19024. var nodes = this._translations.get(message);
  19025. if (nodes) {
  19026. return nodes;
  19027. }
  19028. this._reportError(el, "Translation unavailable for message id=\"" + this._translations.digest(message) + "\"");
  19029. }
  19030. return [];
  19031. };
  19032. // translate the attributes of an element and remove i18n specific attributes
  19033. _Visitor.prototype._translateAttributes = function (el) {
  19034. var _this = this;
  19035. var attributes = el.attrs;
  19036. var i18nParsedMessageMeta = {};
  19037. attributes.forEach(function (attr) {
  19038. if (attr.name.startsWith(_I18N_ATTR_PREFIX)) {
  19039. i18nParsedMessageMeta[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
  19040. _parseMessageMeta(attr.value);
  19041. }
  19042. });
  19043. var translatedAttributes = [];
  19044. attributes.forEach(function (attr) {
  19045. if (attr.name === _I18N_ATTR || attr.name.startsWith(_I18N_ATTR_PREFIX)) {
  19046. // strip i18n specific attributes
  19047. return;
  19048. }
  19049. if (attr.value && attr.value != '' && i18nParsedMessageMeta.hasOwnProperty(attr.name)) {
  19050. var _a = i18nParsedMessageMeta[attr.name], meaning = _a.meaning, description = _a.description, id = _a.id;
  19051. var message = _this._createI18nMessage([attr], meaning, description, id);
  19052. var nodes = _this._translations.get(message);
  19053. if (nodes) {
  19054. if (nodes.length == 0) {
  19055. translatedAttributes.push(new Attribute(attr.name, '', attr.sourceSpan));
  19056. }
  19057. else if (nodes[0] instanceof Text$3) {
  19058. var value = nodes[0].value;
  19059. translatedAttributes.push(new Attribute(attr.name, value, attr.sourceSpan));
  19060. }
  19061. else {
  19062. _this._reportError(el, "Unexpected translation for attribute \"" + attr.name + "\" (id=\"" + (id || _this._translations.digest(message)) + "\")");
  19063. }
  19064. }
  19065. else {
  19066. _this._reportError(el, "Translation unavailable for attribute \"" + attr.name + "\" (id=\"" + (id || _this._translations.digest(message)) + "\")");
  19067. }
  19068. }
  19069. else {
  19070. translatedAttributes.push(attr);
  19071. }
  19072. });
  19073. return translatedAttributes;
  19074. };
  19075. /**
  19076. * Add the node as a child of the block when:
  19077. * - we are in a block,
  19078. * - we are not inside a ICU message (those are handled separately),
  19079. * - the node is a "direct child" of the block
  19080. */
  19081. _Visitor.prototype._mayBeAddBlockChildren = function (node) {
  19082. if (this._inI18nBlock && !this._inIcu && this._depth == this._blockStartDepth) {
  19083. this._blockChildren.push(node);
  19084. }
  19085. };
  19086. /**
  19087. * Marks the start of a section, see `_closeTranslatableSection`
  19088. */
  19089. _Visitor.prototype._openTranslatableSection = function (node) {
  19090. if (this._isInTranslatableSection) {
  19091. this._reportError(node, 'Unexpected section start');
  19092. }
  19093. else {
  19094. this._msgCountAtSectionStart = this._messages.length;
  19095. }
  19096. };
  19097. Object.defineProperty(_Visitor.prototype, "_isInTranslatableSection", {
  19098. /**
  19099. * A translatable section could be:
  19100. * - the content of translatable element,
  19101. * - nodes between `<!-- i18n -->` and `<!-- /i18n -->` comments
  19102. */
  19103. get: function () {
  19104. return this._msgCountAtSectionStart !== void 0;
  19105. },
  19106. enumerable: true,
  19107. configurable: true
  19108. });
  19109. /**
  19110. * Terminates a section.
  19111. *
  19112. * If a section has only one significant children (comments not significant) then we should not
  19113. * keep the message from this children:
  19114. *
  19115. * `<p i18n="meaning|description">{ICU message}</p>` would produce two messages:
  19116. * - one for the <p> content with meaning and description,
  19117. * - another one for the ICU message.
  19118. *
  19119. * In this case the last message is discarded as it contains less information (the AST is
  19120. * otherwise identical).
  19121. *
  19122. * Note that we should still keep messages extracted from attributes inside the section (ie in the
  19123. * ICU message here)
  19124. */
  19125. _Visitor.prototype._closeTranslatableSection = function (node, directChildren) {
  19126. if (!this._isInTranslatableSection) {
  19127. this._reportError(node, 'Unexpected section end');
  19128. return;
  19129. }
  19130. var startIndex = this._msgCountAtSectionStart;
  19131. var significantChildren = directChildren.reduce(function (count, node) { return count + (node instanceof Comment ? 0 : 1); }, 0);
  19132. if (significantChildren == 1) {
  19133. for (var i = this._messages.length - 1; i >= startIndex; i--) {
  19134. var ast = this._messages[i].nodes;
  19135. if (!(ast.length == 1 && ast[0] instanceof Text$1)) {
  19136. this._messages.splice(i, 1);
  19137. break;
  19138. }
  19139. }
  19140. }
  19141. this._msgCountAtSectionStart = undefined;
  19142. };
  19143. _Visitor.prototype._reportError = function (node, msg) {
  19144. this._errors.push(new I18nError(node.sourceSpan, msg));
  19145. };
  19146. return _Visitor;
  19147. }());
  19148. function _isOpeningComment(n) {
  19149. return !!(n instanceof Comment && n.value && n.value.startsWith('i18n'));
  19150. }
  19151. function _isClosingComment(n) {
  19152. return !!(n instanceof Comment && n.value && n.value === '/i18n');
  19153. }
  19154. function _getI18nAttr(p) {
  19155. return p.attrs.find(function (attr) { return attr.name === _I18N_ATTR; }) || null;
  19156. }
  19157. function _parseMessageMeta(i18n) {
  19158. if (!i18n)
  19159. return { meaning: '', description: '', id: '' };
  19160. var idIndex = i18n.indexOf(ID_SEPARATOR);
  19161. var descIndex = i18n.indexOf(MEANING_SEPARATOR);
  19162. var _a = __read((idIndex > -1) ? [i18n.slice(0, idIndex), i18n.slice(idIndex + 2)] : [i18n, ''], 2), meaningAndDesc = _a[0], id = _a[1];
  19163. var _b = __read((descIndex > -1) ?
  19164. [meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] :
  19165. ['', meaningAndDesc], 2), meaning = _b[0], description = _b[1];
  19166. return { meaning: meaning, description: description, id: id };
  19167. }
  19168. /**
  19169. * @license
  19170. * Copyright Google Inc. All Rights Reserved.
  19171. *
  19172. * Use of this source code is governed by an MIT-style license that can be
  19173. * found in the LICENSE file at https://angular.io/license
  19174. */
  19175. var XmlTagDefinition = /** @class */ (function () {
  19176. function XmlTagDefinition() {
  19177. this.closedByParent = false;
  19178. this.contentType = exports.TagContentType.PARSABLE_DATA;
  19179. this.isVoid = false;
  19180. this.ignoreFirstLf = false;
  19181. this.canSelfClose = true;
  19182. }
  19183. XmlTagDefinition.prototype.requireExtraParent = function (currentParent) { return false; };
  19184. XmlTagDefinition.prototype.isClosedByChild = function (name) { return false; };
  19185. return XmlTagDefinition;
  19186. }());
  19187. var _TAG_DEFINITION = new XmlTagDefinition();
  19188. function getXmlTagDefinition(tagName) {
  19189. return _TAG_DEFINITION;
  19190. }
  19191. /**
  19192. * @license
  19193. * Copyright Google Inc. All Rights Reserved.
  19194. *
  19195. * Use of this source code is governed by an MIT-style license that can be
  19196. * found in the LICENSE file at https://angular.io/license
  19197. */
  19198. var XmlParser = /** @class */ (function (_super) {
  19199. __extends(XmlParser, _super);
  19200. function XmlParser() {
  19201. return _super.call(this, getXmlTagDefinition) || this;
  19202. }
  19203. XmlParser.prototype.parse = function (source, url, options) {
  19204. return _super.prototype.parse.call(this, source, url, options);
  19205. };
  19206. return XmlParser;
  19207. }(Parser));
  19208. /**
  19209. * @license
  19210. * Copyright Google Inc. All Rights Reserved.
  19211. *
  19212. * Use of this source code is governed by an MIT-style license that can be
  19213. * found in the LICENSE file at https://angular.io/license
  19214. */
  19215. var _VERSION = '1.2';
  19216. var _XMLNS = 'urn:oasis:names:tc:xliff:document:1.2';
  19217. // TODO(vicb): make this a param (s/_/-/)
  19218. var _DEFAULT_SOURCE_LANG = 'en';
  19219. var _PLACEHOLDER_TAG$1 = 'x';
  19220. var _MARKER_TAG = 'mrk';
  19221. var _FILE_TAG = 'file';
  19222. var _SOURCE_TAG$1 = 'source';
  19223. var _SEGMENT_SOURCE_TAG = 'seg-source';
  19224. var _TARGET_TAG = 'target';
  19225. var _UNIT_TAG = 'trans-unit';
  19226. var _CONTEXT_GROUP_TAG = 'context-group';
  19227. var _CONTEXT_TAG = 'context';
  19228. // http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html
  19229. // http://docs.oasis-open.org/xliff/v1.2/xliff-profile-html/xliff-profile-html-1.2.html
  19230. var Xliff = /** @class */ (function (_super) {
  19231. __extends(Xliff, _super);
  19232. function Xliff() {
  19233. return _super !== null && _super.apply(this, arguments) || this;
  19234. }
  19235. Xliff.prototype.write = function (messages, locale) {
  19236. var visitor = new _WriteVisitor();
  19237. var transUnits = [];
  19238. messages.forEach(function (message) {
  19239. var _a;
  19240. var contextTags = [];
  19241. message.sources.forEach(function (source) {
  19242. var contextGroupTag = new Tag(_CONTEXT_GROUP_TAG, { purpose: 'location' });
  19243. 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));
  19244. contextTags.push(new CR(8), contextGroupTag);
  19245. });
  19246. var transUnit = new Tag(_UNIT_TAG, { id: message.id, datatype: 'html' });
  19247. (_a = transUnit.children).push.apply(_a, __spread([new CR(8), new Tag(_SOURCE_TAG$1, {}, visitor.serialize(message.nodes))], contextTags));
  19248. if (message.description) {
  19249. transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'description' }, [new Text$2(message.description)]));
  19250. }
  19251. if (message.meaning) {
  19252. transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'meaning' }, [new Text$2(message.meaning)]));
  19253. }
  19254. transUnit.children.push(new CR(6));
  19255. transUnits.push(new CR(6), transUnit);
  19256. });
  19257. var body = new Tag('body', {}, __spread(transUnits, [new CR(4)]));
  19258. var file = new Tag('file', {
  19259. 'source-language': locale || _DEFAULT_SOURCE_LANG,
  19260. datatype: 'plaintext',
  19261. original: 'ng2.template',
  19262. }, [new CR(4), body, new CR(2)]);
  19263. var xliff = new Tag('xliff', { version: _VERSION, xmlns: _XMLNS }, [new CR(2), file, new CR()]);
  19264. return serialize([
  19265. new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR()
  19266. ]);
  19267. };
  19268. Xliff.prototype.load = function (content, url) {
  19269. // xliff to xml nodes
  19270. var xliffParser = new XliffParser();
  19271. var _a = xliffParser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
  19272. // xml nodes to i18n nodes
  19273. var i18nNodesByMsgId = {};
  19274. var converter = new XmlToI18n();
  19275. Object.keys(msgIdToHtml).forEach(function (msgId) {
  19276. var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, e = _a.errors;
  19277. errors.push.apply(errors, __spread(e));
  19278. i18nNodesByMsgId[msgId] = i18nNodes;
  19279. });
  19280. if (errors.length) {
  19281. throw new Error("xliff parse errors:\n" + errors.join('\n'));
  19282. }
  19283. return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
  19284. };
  19285. Xliff.prototype.digest = function (message) { return digest(message); };
  19286. return Xliff;
  19287. }(Serializer));
  19288. var _WriteVisitor = /** @class */ (function () {
  19289. function _WriteVisitor() {
  19290. }
  19291. _WriteVisitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
  19292. _WriteVisitor.prototype.visitContainer = function (container, context) {
  19293. var _this = this;
  19294. var nodes = [];
  19295. container.children.forEach(function (node) { return nodes.push.apply(nodes, __spread(node.visit(_this))); });
  19296. return nodes;
  19297. };
  19298. _WriteVisitor.prototype.visitIcu = function (icu, context) {
  19299. var _this = this;
  19300. var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
  19301. Object.keys(icu.cases).forEach(function (c) {
  19302. nodes.push.apply(nodes, __spread([new Text$2(c + " {")], icu.cases[c].visit(_this), [new Text$2("} ")]));
  19303. });
  19304. nodes.push(new Text$2("}"));
  19305. return nodes;
  19306. };
  19307. _WriteVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  19308. var ctype = getCtypeForTag(ph.tag);
  19309. if (ph.isVoid) {
  19310. // void tags have no children nor closing tags
  19311. return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.startName, ctype: ctype, 'equiv-text': "<" + ph.tag + "/>" })];
  19312. }
  19313. var startTagPh = new Tag(_PLACEHOLDER_TAG$1, { id: ph.startName, ctype: ctype, 'equiv-text': "<" + ph.tag + ">" });
  19314. var closeTagPh = new Tag(_PLACEHOLDER_TAG$1, { id: ph.closeName, ctype: ctype, 'equiv-text': "</" + ph.tag + ">" });
  19315. return __spread([startTagPh], this.serialize(ph.children), [closeTagPh]);
  19316. };
  19317. _WriteVisitor.prototype.visitPlaceholder = function (ph, context) {
  19318. return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.name, 'equiv-text': "{{" + ph.value + "}}" })];
  19319. };
  19320. _WriteVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  19321. var equivText = "{" + ph.value.expression + ", " + ph.value.type + ", " + Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ') + "}";
  19322. return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.name, 'equiv-text': equivText })];
  19323. };
  19324. _WriteVisitor.prototype.serialize = function (nodes) {
  19325. var _this = this;
  19326. return [].concat.apply([], __spread(nodes.map(function (node) { return node.visit(_this); })));
  19327. };
  19328. return _WriteVisitor;
  19329. }());
  19330. // TODO(vicb): add error management (structure)
  19331. // Extract messages as xml nodes from the xliff file
  19332. var XliffParser = /** @class */ (function () {
  19333. function XliffParser() {
  19334. this._locale = null;
  19335. }
  19336. XliffParser.prototype.parse = function (xliff, url) {
  19337. this._unitMlString = null;
  19338. this._msgIdToHtml = {};
  19339. var xml = new XmlParser().parse(xliff, url);
  19340. this._errors = xml.errors;
  19341. visitAll$1(this, xml.rootNodes, null);
  19342. return {
  19343. msgIdToHtml: this._msgIdToHtml,
  19344. errors: this._errors,
  19345. locale: this._locale,
  19346. };
  19347. };
  19348. XliffParser.prototype.visitElement = function (element, context) {
  19349. switch (element.name) {
  19350. case _UNIT_TAG:
  19351. this._unitMlString = null;
  19352. var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
  19353. if (!idAttr) {
  19354. this._addError(element, "<" + _UNIT_TAG + "> misses the \"id\" attribute");
  19355. }
  19356. else {
  19357. var id = idAttr.value;
  19358. if (this._msgIdToHtml.hasOwnProperty(id)) {
  19359. this._addError(element, "Duplicated translations for msg " + id);
  19360. }
  19361. else {
  19362. visitAll$1(this, element.children, null);
  19363. if (typeof this._unitMlString === 'string') {
  19364. this._msgIdToHtml[id] = this._unitMlString;
  19365. }
  19366. else {
  19367. this._addError(element, "Message " + id + " misses a translation");
  19368. }
  19369. }
  19370. }
  19371. break;
  19372. // ignore those tags
  19373. case _SOURCE_TAG$1:
  19374. case _SEGMENT_SOURCE_TAG:
  19375. break;
  19376. case _TARGET_TAG:
  19377. var innerTextStart = element.startSourceSpan.end.offset;
  19378. var innerTextEnd = element.endSourceSpan.start.offset;
  19379. var content = element.startSourceSpan.start.file.content;
  19380. var innerText = content.slice(innerTextStart, innerTextEnd);
  19381. this._unitMlString = innerText;
  19382. break;
  19383. case _FILE_TAG:
  19384. var localeAttr = element.attrs.find(function (attr) { return attr.name === 'target-language'; });
  19385. if (localeAttr) {
  19386. this._locale = localeAttr.value;
  19387. }
  19388. visitAll$1(this, element.children, null);
  19389. break;
  19390. default:
  19391. // TODO(vicb): assert file structure, xliff version
  19392. // For now only recurse on unhandled nodes
  19393. visitAll$1(this, element.children, null);
  19394. }
  19395. };
  19396. XliffParser.prototype.visitAttribute = function (attribute, context) { };
  19397. XliffParser.prototype.visitText = function (text, context) { };
  19398. XliffParser.prototype.visitComment = function (comment, context) { };
  19399. XliffParser.prototype.visitExpansion = function (expansion, context) { };
  19400. XliffParser.prototype.visitExpansionCase = function (expansionCase, context) { };
  19401. XliffParser.prototype._addError = function (node, message) {
  19402. this._errors.push(new I18nError(node.sourceSpan, message));
  19403. };
  19404. return XliffParser;
  19405. }());
  19406. // Convert ml nodes (xliff syntax) to i18n nodes
  19407. var XmlToI18n = /** @class */ (function () {
  19408. function XmlToI18n() {
  19409. }
  19410. XmlToI18n.prototype.convert = function (message, url) {
  19411. var xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
  19412. this._errors = xmlIcu.errors;
  19413. var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
  19414. [] : [].concat.apply([], __spread(visitAll$1(this, xmlIcu.rootNodes)));
  19415. return {
  19416. i18nNodes: i18nNodes,
  19417. errors: this._errors,
  19418. };
  19419. };
  19420. XmlToI18n.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
  19421. XmlToI18n.prototype.visitElement = function (el, context) {
  19422. if (el.name === _PLACEHOLDER_TAG$1) {
  19423. var nameAttr = el.attrs.find(function (attr) { return attr.name === 'id'; });
  19424. if (nameAttr) {
  19425. return new Placeholder('', nameAttr.value, el.sourceSpan);
  19426. }
  19427. this._addError(el, "<" + _PLACEHOLDER_TAG$1 + "> misses the \"id\" attribute");
  19428. return null;
  19429. }
  19430. if (el.name === _MARKER_TAG) {
  19431. return [].concat.apply([], __spread(visitAll$1(this, el.children)));
  19432. }
  19433. this._addError(el, "Unexpected tag");
  19434. return null;
  19435. };
  19436. XmlToI18n.prototype.visitExpansion = function (icu, context) {
  19437. var caseMap = {};
  19438. visitAll$1(this, icu.cases).forEach(function (c) {
  19439. caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
  19440. });
  19441. return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
  19442. };
  19443. XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
  19444. return {
  19445. value: icuCase.value,
  19446. nodes: visitAll$1(this, icuCase.expression),
  19447. };
  19448. };
  19449. XmlToI18n.prototype.visitComment = function (comment, context) { };
  19450. XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
  19451. XmlToI18n.prototype._addError = function (node, message) {
  19452. this._errors.push(new I18nError(node.sourceSpan, message));
  19453. };
  19454. return XmlToI18n;
  19455. }());
  19456. function getCtypeForTag(tag) {
  19457. switch (tag.toLowerCase()) {
  19458. case 'br':
  19459. return 'lb';
  19460. case 'img':
  19461. return 'image';
  19462. default:
  19463. return "x-" + tag;
  19464. }
  19465. }
  19466. /**
  19467. * @license
  19468. * Copyright Google Inc. All Rights Reserved.
  19469. *
  19470. * Use of this source code is governed by an MIT-style license that can be
  19471. * found in the LICENSE file at https://angular.io/license
  19472. */
  19473. var _VERSION$1 = '2.0';
  19474. var _XMLNS$1 = 'urn:oasis:names:tc:xliff:document:2.0';
  19475. // TODO(vicb): make this a param (s/_/-/)
  19476. var _DEFAULT_SOURCE_LANG$1 = 'en';
  19477. var _PLACEHOLDER_TAG$2 = 'ph';
  19478. var _PLACEHOLDER_SPANNING_TAG = 'pc';
  19479. var _MARKER_TAG$1 = 'mrk';
  19480. var _XLIFF_TAG = 'xliff';
  19481. var _SOURCE_TAG$2 = 'source';
  19482. var _TARGET_TAG$1 = 'target';
  19483. var _UNIT_TAG$1 = 'unit';
  19484. // http://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html
  19485. var Xliff2 = /** @class */ (function (_super) {
  19486. __extends(Xliff2, _super);
  19487. function Xliff2() {
  19488. return _super !== null && _super.apply(this, arguments) || this;
  19489. }
  19490. Xliff2.prototype.write = function (messages, locale) {
  19491. var visitor = new _WriteVisitor$1();
  19492. var units = [];
  19493. messages.forEach(function (message) {
  19494. var unit = new Tag(_UNIT_TAG$1, { id: message.id });
  19495. var notes = new Tag('notes');
  19496. if (message.description || message.meaning) {
  19497. if (message.description) {
  19498. notes.children.push(new CR(8), new Tag('note', { category: 'description' }, [new Text$2(message.description)]));
  19499. }
  19500. if (message.meaning) {
  19501. notes.children.push(new CR(8), new Tag('note', { category: 'meaning' }, [new Text$2(message.meaning)]));
  19502. }
  19503. }
  19504. message.sources.forEach(function (source) {
  19505. notes.children.push(new CR(8), new Tag('note', { category: 'location' }, [
  19506. new Text$2(source.filePath + ":" + source.startLine + (source.endLine !== source.startLine ? ',' + source.endLine : ''))
  19507. ]));
  19508. });
  19509. notes.children.push(new CR(6));
  19510. unit.children.push(new CR(6), notes);
  19511. var segment = new Tag('segment');
  19512. segment.children.push(new CR(8), new Tag(_SOURCE_TAG$2, {}, visitor.serialize(message.nodes)), new CR(6));
  19513. unit.children.push(new CR(6), segment, new CR(4));
  19514. units.push(new CR(4), unit);
  19515. });
  19516. var file = new Tag('file', { 'original': 'ng.template', id: 'ngi18n' }, __spread(units, [new CR(2)]));
  19517. var xliff = new Tag(_XLIFF_TAG, { version: _VERSION$1, xmlns: _XMLNS$1, srcLang: locale || _DEFAULT_SOURCE_LANG$1 }, [new CR(2), file, new CR()]);
  19518. return serialize([
  19519. new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR()
  19520. ]);
  19521. };
  19522. Xliff2.prototype.load = function (content, url) {
  19523. // xliff to xml nodes
  19524. var xliff2Parser = new Xliff2Parser();
  19525. var _a = xliff2Parser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
  19526. // xml nodes to i18n nodes
  19527. var i18nNodesByMsgId = {};
  19528. var converter = new XmlToI18n$1();
  19529. Object.keys(msgIdToHtml).forEach(function (msgId) {
  19530. var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, e = _a.errors;
  19531. errors.push.apply(errors, __spread(e));
  19532. i18nNodesByMsgId[msgId] = i18nNodes;
  19533. });
  19534. if (errors.length) {
  19535. throw new Error("xliff2 parse errors:\n" + errors.join('\n'));
  19536. }
  19537. return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
  19538. };
  19539. Xliff2.prototype.digest = function (message) { return decimalDigest(message); };
  19540. return Xliff2;
  19541. }(Serializer));
  19542. var _WriteVisitor$1 = /** @class */ (function () {
  19543. function _WriteVisitor() {
  19544. }
  19545. _WriteVisitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
  19546. _WriteVisitor.prototype.visitContainer = function (container, context) {
  19547. var _this = this;
  19548. var nodes = [];
  19549. container.children.forEach(function (node) { return nodes.push.apply(nodes, __spread(node.visit(_this))); });
  19550. return nodes;
  19551. };
  19552. _WriteVisitor.prototype.visitIcu = function (icu, context) {
  19553. var _this = this;
  19554. var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
  19555. Object.keys(icu.cases).forEach(function (c) {
  19556. nodes.push.apply(nodes, __spread([new Text$2(c + " {")], icu.cases[c].visit(_this), [new Text$2("} ")]));
  19557. });
  19558. nodes.push(new Text$2("}"));
  19559. return nodes;
  19560. };
  19561. _WriteVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  19562. var _this = this;
  19563. var type = getTypeForTag(ph.tag);
  19564. if (ph.isVoid) {
  19565. var tagPh = new Tag(_PLACEHOLDER_TAG$2, {
  19566. id: (this._nextPlaceholderId++).toString(),
  19567. equiv: ph.startName,
  19568. type: type,
  19569. disp: "<" + ph.tag + "/>",
  19570. });
  19571. return [tagPh];
  19572. }
  19573. var tagPc = new Tag(_PLACEHOLDER_SPANNING_TAG, {
  19574. id: (this._nextPlaceholderId++).toString(),
  19575. equivStart: ph.startName,
  19576. equivEnd: ph.closeName,
  19577. type: type,
  19578. dispStart: "<" + ph.tag + ">",
  19579. dispEnd: "</" + ph.tag + ">",
  19580. });
  19581. var nodes = [].concat.apply([], __spread(ph.children.map(function (node) { return node.visit(_this); })));
  19582. if (nodes.length) {
  19583. nodes.forEach(function (node) { return tagPc.children.push(node); });
  19584. }
  19585. else {
  19586. tagPc.children.push(new Text$2(''));
  19587. }
  19588. return [tagPc];
  19589. };
  19590. _WriteVisitor.prototype.visitPlaceholder = function (ph, context) {
  19591. var idStr = (this._nextPlaceholderId++).toString();
  19592. return [new Tag(_PLACEHOLDER_TAG$2, {
  19593. id: idStr,
  19594. equiv: ph.name,
  19595. disp: "{{" + ph.value + "}}",
  19596. })];
  19597. };
  19598. _WriteVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  19599. var cases = Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ');
  19600. var idStr = (this._nextPlaceholderId++).toString();
  19601. return [new Tag(_PLACEHOLDER_TAG$2, { id: idStr, equiv: ph.name, disp: "{" + ph.value.expression + ", " + ph.value.type + ", " + cases + "}" })];
  19602. };
  19603. _WriteVisitor.prototype.serialize = function (nodes) {
  19604. var _this = this;
  19605. this._nextPlaceholderId = 0;
  19606. return [].concat.apply([], __spread(nodes.map(function (node) { return node.visit(_this); })));
  19607. };
  19608. return _WriteVisitor;
  19609. }());
  19610. // Extract messages as xml nodes from the xliff file
  19611. var Xliff2Parser = /** @class */ (function () {
  19612. function Xliff2Parser() {
  19613. this._locale = null;
  19614. }
  19615. Xliff2Parser.prototype.parse = function (xliff, url) {
  19616. this._unitMlString = null;
  19617. this._msgIdToHtml = {};
  19618. var xml = new XmlParser().parse(xliff, url);
  19619. this._errors = xml.errors;
  19620. visitAll$1(this, xml.rootNodes, null);
  19621. return {
  19622. msgIdToHtml: this._msgIdToHtml,
  19623. errors: this._errors,
  19624. locale: this._locale,
  19625. };
  19626. };
  19627. Xliff2Parser.prototype.visitElement = function (element, context) {
  19628. switch (element.name) {
  19629. case _UNIT_TAG$1:
  19630. this._unitMlString = null;
  19631. var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
  19632. if (!idAttr) {
  19633. this._addError(element, "<" + _UNIT_TAG$1 + "> misses the \"id\" attribute");
  19634. }
  19635. else {
  19636. var id = idAttr.value;
  19637. if (this._msgIdToHtml.hasOwnProperty(id)) {
  19638. this._addError(element, "Duplicated translations for msg " + id);
  19639. }
  19640. else {
  19641. visitAll$1(this, element.children, null);
  19642. if (typeof this._unitMlString === 'string') {
  19643. this._msgIdToHtml[id] = this._unitMlString;
  19644. }
  19645. else {
  19646. this._addError(element, "Message " + id + " misses a translation");
  19647. }
  19648. }
  19649. }
  19650. break;
  19651. case _SOURCE_TAG$2:
  19652. // ignore source message
  19653. break;
  19654. case _TARGET_TAG$1:
  19655. var innerTextStart = element.startSourceSpan.end.offset;
  19656. var innerTextEnd = element.endSourceSpan.start.offset;
  19657. var content = element.startSourceSpan.start.file.content;
  19658. var innerText = content.slice(innerTextStart, innerTextEnd);
  19659. this._unitMlString = innerText;
  19660. break;
  19661. case _XLIFF_TAG:
  19662. var localeAttr = element.attrs.find(function (attr) { return attr.name === 'trgLang'; });
  19663. if (localeAttr) {
  19664. this._locale = localeAttr.value;
  19665. }
  19666. var versionAttr = element.attrs.find(function (attr) { return attr.name === 'version'; });
  19667. if (versionAttr) {
  19668. var version = versionAttr.value;
  19669. if (version !== '2.0') {
  19670. this._addError(element, "The XLIFF file version " + version + " is not compatible with XLIFF 2.0 serializer");
  19671. }
  19672. else {
  19673. visitAll$1(this, element.children, null);
  19674. }
  19675. }
  19676. break;
  19677. default:
  19678. visitAll$1(this, element.children, null);
  19679. }
  19680. };
  19681. Xliff2Parser.prototype.visitAttribute = function (attribute, context) { };
  19682. Xliff2Parser.prototype.visitText = function (text, context) { };
  19683. Xliff2Parser.prototype.visitComment = function (comment, context) { };
  19684. Xliff2Parser.prototype.visitExpansion = function (expansion, context) { };
  19685. Xliff2Parser.prototype.visitExpansionCase = function (expansionCase, context) { };
  19686. Xliff2Parser.prototype._addError = function (node, message) {
  19687. this._errors.push(new I18nError(node.sourceSpan, message));
  19688. };
  19689. return Xliff2Parser;
  19690. }());
  19691. // Convert ml nodes (xliff syntax) to i18n nodes
  19692. var XmlToI18n$1 = /** @class */ (function () {
  19693. function XmlToI18n() {
  19694. }
  19695. XmlToI18n.prototype.convert = function (message, url) {
  19696. var xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
  19697. this._errors = xmlIcu.errors;
  19698. var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
  19699. [] : [].concat.apply([], __spread(visitAll$1(this, xmlIcu.rootNodes)));
  19700. return {
  19701. i18nNodes: i18nNodes,
  19702. errors: this._errors,
  19703. };
  19704. };
  19705. XmlToI18n.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
  19706. XmlToI18n.prototype.visitElement = function (el, context) {
  19707. var _this = this;
  19708. switch (el.name) {
  19709. case _PLACEHOLDER_TAG$2:
  19710. var nameAttr = el.attrs.find(function (attr) { return attr.name === 'equiv'; });
  19711. if (nameAttr) {
  19712. return [new Placeholder('', nameAttr.value, el.sourceSpan)];
  19713. }
  19714. this._addError(el, "<" + _PLACEHOLDER_TAG$2 + "> misses the \"equiv\" attribute");
  19715. break;
  19716. case _PLACEHOLDER_SPANNING_TAG:
  19717. var startAttr = el.attrs.find(function (attr) { return attr.name === 'equivStart'; });
  19718. var endAttr = el.attrs.find(function (attr) { return attr.name === 'equivEnd'; });
  19719. if (!startAttr) {
  19720. this._addError(el, "<" + _PLACEHOLDER_TAG$2 + "> misses the \"equivStart\" attribute");
  19721. }
  19722. else if (!endAttr) {
  19723. this._addError(el, "<" + _PLACEHOLDER_TAG$2 + "> misses the \"equivEnd\" attribute");
  19724. }
  19725. else {
  19726. var startId = startAttr.value;
  19727. var endId = endAttr.value;
  19728. var nodes = [];
  19729. 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)]));
  19730. }
  19731. break;
  19732. case _MARKER_TAG$1:
  19733. return [].concat.apply([], __spread(visitAll$1(this, el.children)));
  19734. default:
  19735. this._addError(el, "Unexpected tag");
  19736. }
  19737. return null;
  19738. };
  19739. XmlToI18n.prototype.visitExpansion = function (icu, context) {
  19740. var caseMap = {};
  19741. visitAll$1(this, icu.cases).forEach(function (c) {
  19742. caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
  19743. });
  19744. return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
  19745. };
  19746. XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
  19747. return {
  19748. value: icuCase.value,
  19749. nodes: [].concat.apply([], __spread(visitAll$1(this, icuCase.expression))),
  19750. };
  19751. };
  19752. XmlToI18n.prototype.visitComment = function (comment, context) { };
  19753. XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
  19754. XmlToI18n.prototype._addError = function (node, message) {
  19755. this._errors.push(new I18nError(node.sourceSpan, message));
  19756. };
  19757. return XmlToI18n;
  19758. }());
  19759. function getTypeForTag(tag) {
  19760. switch (tag.toLowerCase()) {
  19761. case 'br':
  19762. case 'b':
  19763. case 'i':
  19764. case 'u':
  19765. return 'fmt';
  19766. case 'img':
  19767. return 'image';
  19768. case 'a':
  19769. return 'link';
  19770. default:
  19771. return 'other';
  19772. }
  19773. }
  19774. /**
  19775. * @license
  19776. * Copyright Google Inc. All Rights Reserved.
  19777. *
  19778. * Use of this source code is governed by an MIT-style license that can be
  19779. * found in the LICENSE file at https://angular.io/license
  19780. */
  19781. var _TRANSLATIONS_TAG = 'translationbundle';
  19782. var _TRANSLATION_TAG = 'translation';
  19783. var _PLACEHOLDER_TAG$3 = 'ph';
  19784. var Xtb = /** @class */ (function (_super) {
  19785. __extends(Xtb, _super);
  19786. function Xtb() {
  19787. return _super !== null && _super.apply(this, arguments) || this;
  19788. }
  19789. Xtb.prototype.write = function (messages, locale) { throw new Error('Unsupported'); };
  19790. Xtb.prototype.load = function (content, url) {
  19791. // xtb to xml nodes
  19792. var xtbParser = new XtbParser();
  19793. var _a = xtbParser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
  19794. // xml nodes to i18n nodes
  19795. var i18nNodesByMsgId = {};
  19796. var converter = new XmlToI18n$2();
  19797. // Because we should be able to load xtb files that rely on features not supported by angular,
  19798. // we need to delay the conversion of html to i18n nodes so that non angular messages are not
  19799. // converted
  19800. Object.keys(msgIdToHtml).forEach(function (msgId) {
  19801. var valueFn = function () {
  19802. var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, errors = _a.errors;
  19803. if (errors.length) {
  19804. throw new Error("xtb parse errors:\n" + errors.join('\n'));
  19805. }
  19806. return i18nNodes;
  19807. };
  19808. createLazyProperty(i18nNodesByMsgId, msgId, valueFn);
  19809. });
  19810. if (errors.length) {
  19811. throw new Error("xtb parse errors:\n" + errors.join('\n'));
  19812. }
  19813. return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
  19814. };
  19815. Xtb.prototype.digest = function (message) { return digest$1(message); };
  19816. Xtb.prototype.createNameMapper = function (message) {
  19817. return new SimplePlaceholderMapper(message, toPublicName);
  19818. };
  19819. return Xtb;
  19820. }(Serializer));
  19821. function createLazyProperty(messages, id, valueFn) {
  19822. Object.defineProperty(messages, id, {
  19823. configurable: true,
  19824. enumerable: true,
  19825. get: function () {
  19826. var value = valueFn();
  19827. Object.defineProperty(messages, id, { enumerable: true, value: value });
  19828. return value;
  19829. },
  19830. set: function (_) { throw new Error('Could not overwrite an XTB translation'); },
  19831. });
  19832. }
  19833. // Extract messages as xml nodes from the xtb file
  19834. var XtbParser = /** @class */ (function () {
  19835. function XtbParser() {
  19836. this._locale = null;
  19837. }
  19838. XtbParser.prototype.parse = function (xtb, url) {
  19839. this._bundleDepth = 0;
  19840. this._msgIdToHtml = {};
  19841. // We can not parse the ICU messages at this point as some messages might not originate
  19842. // from Angular that could not be lex'd.
  19843. var xml = new XmlParser().parse(xtb, url);
  19844. this._errors = xml.errors;
  19845. visitAll$1(this, xml.rootNodes);
  19846. return {
  19847. msgIdToHtml: this._msgIdToHtml,
  19848. errors: this._errors,
  19849. locale: this._locale,
  19850. };
  19851. };
  19852. XtbParser.prototype.visitElement = function (element, context) {
  19853. switch (element.name) {
  19854. case _TRANSLATIONS_TAG:
  19855. this._bundleDepth++;
  19856. if (this._bundleDepth > 1) {
  19857. this._addError(element, "<" + _TRANSLATIONS_TAG + "> elements can not be nested");
  19858. }
  19859. var langAttr = element.attrs.find(function (attr) { return attr.name === 'lang'; });
  19860. if (langAttr) {
  19861. this._locale = langAttr.value;
  19862. }
  19863. visitAll$1(this, element.children, null);
  19864. this._bundleDepth--;
  19865. break;
  19866. case _TRANSLATION_TAG:
  19867. var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
  19868. if (!idAttr) {
  19869. this._addError(element, "<" + _TRANSLATION_TAG + "> misses the \"id\" attribute");
  19870. }
  19871. else {
  19872. var id = idAttr.value;
  19873. if (this._msgIdToHtml.hasOwnProperty(id)) {
  19874. this._addError(element, "Duplicated translations for msg " + id);
  19875. }
  19876. else {
  19877. var innerTextStart = element.startSourceSpan.end.offset;
  19878. var innerTextEnd = element.endSourceSpan.start.offset;
  19879. var content = element.startSourceSpan.start.file.content;
  19880. var innerText = content.slice(innerTextStart, innerTextEnd);
  19881. this._msgIdToHtml[id] = innerText;
  19882. }
  19883. }
  19884. break;
  19885. default:
  19886. this._addError(element, 'Unexpected tag');
  19887. }
  19888. };
  19889. XtbParser.prototype.visitAttribute = function (attribute, context) { };
  19890. XtbParser.prototype.visitText = function (text, context) { };
  19891. XtbParser.prototype.visitComment = function (comment, context) { };
  19892. XtbParser.prototype.visitExpansion = function (expansion, context) { };
  19893. XtbParser.prototype.visitExpansionCase = function (expansionCase, context) { };
  19894. XtbParser.prototype._addError = function (node, message) {
  19895. this._errors.push(new I18nError(node.sourceSpan, message));
  19896. };
  19897. return XtbParser;
  19898. }());
  19899. // Convert ml nodes (xtb syntax) to i18n nodes
  19900. var XmlToI18n$2 = /** @class */ (function () {
  19901. function XmlToI18n() {
  19902. }
  19903. XmlToI18n.prototype.convert = function (message, url) {
  19904. var xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
  19905. this._errors = xmlIcu.errors;
  19906. var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
  19907. [] :
  19908. visitAll$1(this, xmlIcu.rootNodes);
  19909. return {
  19910. i18nNodes: i18nNodes,
  19911. errors: this._errors,
  19912. };
  19913. };
  19914. XmlToI18n.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
  19915. XmlToI18n.prototype.visitExpansion = function (icu, context) {
  19916. var caseMap = {};
  19917. visitAll$1(this, icu.cases).forEach(function (c) {
  19918. caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
  19919. });
  19920. return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
  19921. };
  19922. XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
  19923. return {
  19924. value: icuCase.value,
  19925. nodes: visitAll$1(this, icuCase.expression),
  19926. };
  19927. };
  19928. XmlToI18n.prototype.visitElement = function (el, context) {
  19929. if (el.name === _PLACEHOLDER_TAG$3) {
  19930. var nameAttr = el.attrs.find(function (attr) { return attr.name === 'name'; });
  19931. if (nameAttr) {
  19932. return new Placeholder('', nameAttr.value, el.sourceSpan);
  19933. }
  19934. this._addError(el, "<" + _PLACEHOLDER_TAG$3 + "> misses the \"name\" attribute");
  19935. }
  19936. else {
  19937. this._addError(el, "Unexpected tag");
  19938. }
  19939. return null;
  19940. };
  19941. XmlToI18n.prototype.visitComment = function (comment, context) { };
  19942. XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
  19943. XmlToI18n.prototype._addError = function (node, message) {
  19944. this._errors.push(new I18nError(node.sourceSpan, message));
  19945. };
  19946. return XmlToI18n;
  19947. }());
  19948. /**
  19949. * @license
  19950. * Copyright Google Inc. All Rights Reserved.
  19951. *
  19952. * Use of this source code is governed by an MIT-style license that can be
  19953. * found in the LICENSE file at https://angular.io/license
  19954. */
  19955. /**
  19956. * A container for translated messages
  19957. */
  19958. var TranslationBundle = /** @class */ (function () {
  19959. function TranslationBundle(_i18nNodesByMsgId, locale, digest, mapperFactory, missingTranslationStrategy, console) {
  19960. if (_i18nNodesByMsgId === void 0) { _i18nNodesByMsgId = {}; }
  19961. if (missingTranslationStrategy === void 0) { missingTranslationStrategy = MissingTranslationStrategy.Warning; }
  19962. this._i18nNodesByMsgId = _i18nNodesByMsgId;
  19963. this.digest = digest;
  19964. this.mapperFactory = mapperFactory;
  19965. this._i18nToHtml = new I18nToHtmlVisitor(_i18nNodesByMsgId, locale, digest, mapperFactory, missingTranslationStrategy, console);
  19966. }
  19967. // Creates a `TranslationBundle` by parsing the given `content` with the `serializer`.
  19968. TranslationBundle.load = function (content, url, serializer, missingTranslationStrategy, console) {
  19969. var _a = serializer.load(content, url), locale = _a.locale, i18nNodesByMsgId = _a.i18nNodesByMsgId;
  19970. var digestFn = function (m) { return serializer.digest(m); };
  19971. var mapperFactory = function (m) { return serializer.createNameMapper(m); };
  19972. return new TranslationBundle(i18nNodesByMsgId, locale, digestFn, mapperFactory, missingTranslationStrategy, console);
  19973. };
  19974. // Returns the translation as HTML nodes from the given source message.
  19975. TranslationBundle.prototype.get = function (srcMsg) {
  19976. var html = this._i18nToHtml.convert(srcMsg);
  19977. if (html.errors.length) {
  19978. throw new Error(html.errors.join('\n'));
  19979. }
  19980. return html.nodes;
  19981. };
  19982. TranslationBundle.prototype.has = function (srcMsg) { return this.digest(srcMsg) in this._i18nNodesByMsgId; };
  19983. return TranslationBundle;
  19984. }());
  19985. var I18nToHtmlVisitor = /** @class */ (function () {
  19986. function I18nToHtmlVisitor(_i18nNodesByMsgId, _locale, _digest, _mapperFactory, _missingTranslationStrategy, _console) {
  19987. if (_i18nNodesByMsgId === void 0) { _i18nNodesByMsgId = {}; }
  19988. this._i18nNodesByMsgId = _i18nNodesByMsgId;
  19989. this._locale = _locale;
  19990. this._digest = _digest;
  19991. this._mapperFactory = _mapperFactory;
  19992. this._missingTranslationStrategy = _missingTranslationStrategy;
  19993. this._console = _console;
  19994. this._contextStack = [];
  19995. this._errors = [];
  19996. }
  19997. I18nToHtmlVisitor.prototype.convert = function (srcMsg) {
  19998. this._contextStack.length = 0;
  19999. this._errors.length = 0;
  20000. // i18n to text
  20001. var text = this._convertToText(srcMsg);
  20002. // text to html
  20003. var url = srcMsg.nodes[0].sourceSpan.start.file.url;
  20004. var html = new HtmlParser().parse(text, url, { tokenizeExpansionForms: true });
  20005. return {
  20006. nodes: html.rootNodes,
  20007. errors: __spread(this._errors, html.errors),
  20008. };
  20009. };
  20010. I18nToHtmlVisitor.prototype.visitText = function (text, context) {
  20011. // `convert()` uses an `HtmlParser` to return `html.Node`s
  20012. // we should then make sure that any special characters are escaped
  20013. return escapeXml(text.value);
  20014. };
  20015. I18nToHtmlVisitor.prototype.visitContainer = function (container, context) {
  20016. var _this = this;
  20017. return container.children.map(function (n) { return n.visit(_this); }).join('');
  20018. };
  20019. I18nToHtmlVisitor.prototype.visitIcu = function (icu, context) {
  20020. var _this = this;
  20021. var cases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
  20022. // TODO(vicb): Once all format switch to using expression placeholders
  20023. // we should throw when the placeholder is not in the source message
  20024. var exp = this._srcMsg.placeholders.hasOwnProperty(icu.expression) ?
  20025. this._srcMsg.placeholders[icu.expression] :
  20026. icu.expression;
  20027. return "{" + exp + ", " + icu.type + ", " + cases.join(' ') + "}";
  20028. };
  20029. I18nToHtmlVisitor.prototype.visitPlaceholder = function (ph, context) {
  20030. var phName = this._mapper(ph.name);
  20031. if (this._srcMsg.placeholders.hasOwnProperty(phName)) {
  20032. return this._srcMsg.placeholders[phName];
  20033. }
  20034. if (this._srcMsg.placeholderToMessage.hasOwnProperty(phName)) {
  20035. return this._convertToText(this._srcMsg.placeholderToMessage[phName]);
  20036. }
  20037. this._addError(ph, "Unknown placeholder \"" + ph.name + "\"");
  20038. return '';
  20039. };
  20040. // Loaded message contains only placeholders (vs tag and icu placeholders).
  20041. // However when a translation can not be found, we need to serialize the source message
  20042. // which can contain tag placeholders
  20043. I18nToHtmlVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  20044. var _this = this;
  20045. var tag = "" + ph.tag;
  20046. var attrs = Object.keys(ph.attrs).map(function (name) { return name + "=\"" + ph.attrs[name] + "\""; }).join(' ');
  20047. if (ph.isVoid) {
  20048. return "<" + tag + " " + attrs + "/>";
  20049. }
  20050. var children = ph.children.map(function (c) { return c.visit(_this); }).join('');
  20051. return "<" + tag + " " + attrs + ">" + children + "</" + tag + ">";
  20052. };
  20053. // Loaded message contains only placeholders (vs tag and icu placeholders).
  20054. // However when a translation can not be found, we need to serialize the source message
  20055. // which can contain tag placeholders
  20056. I18nToHtmlVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  20057. // An ICU placeholder references the source message to be serialized
  20058. return this._convertToText(this._srcMsg.placeholderToMessage[ph.name]);
  20059. };
  20060. /**
  20061. * Convert a source message to a translated text string:
  20062. * - text nodes are replaced with their translation,
  20063. * - placeholders are replaced with their content,
  20064. * - ICU nodes are converted to ICU expressions.
  20065. */
  20066. I18nToHtmlVisitor.prototype._convertToText = function (srcMsg) {
  20067. var _this = this;
  20068. var id = this._digest(srcMsg);
  20069. var mapper = this._mapperFactory ? this._mapperFactory(srcMsg) : null;
  20070. var nodes;
  20071. this._contextStack.push({ msg: this._srcMsg, mapper: this._mapper });
  20072. this._srcMsg = srcMsg;
  20073. if (this._i18nNodesByMsgId.hasOwnProperty(id)) {
  20074. // When there is a translation use its nodes as the source
  20075. // And create a mapper to convert serialized placeholder names to internal names
  20076. nodes = this._i18nNodesByMsgId[id];
  20077. this._mapper = function (name) { return mapper ? mapper.toInternalName(name) : name; };
  20078. }
  20079. else {
  20080. // When no translation has been found
  20081. // - report an error / a warning / nothing,
  20082. // - use the nodes from the original message
  20083. // - placeholders are already internal and need no mapper
  20084. if (this._missingTranslationStrategy === MissingTranslationStrategy.Error) {
  20085. var ctx = this._locale ? " for locale \"" + this._locale + "\"" : '';
  20086. this._addError(srcMsg.nodes[0], "Missing translation for message \"" + id + "\"" + ctx);
  20087. }
  20088. else if (this._console &&
  20089. this._missingTranslationStrategy === MissingTranslationStrategy.Warning) {
  20090. var ctx = this._locale ? " for locale \"" + this._locale + "\"" : '';
  20091. this._console.warn("Missing translation for message \"" + id + "\"" + ctx);
  20092. }
  20093. nodes = srcMsg.nodes;
  20094. this._mapper = function (name) { return name; };
  20095. }
  20096. var text = nodes.map(function (node) { return node.visit(_this); }).join('');
  20097. var context = this._contextStack.pop();
  20098. this._srcMsg = context.msg;
  20099. this._mapper = context.mapper;
  20100. return text;
  20101. };
  20102. I18nToHtmlVisitor.prototype._addError = function (el, msg) {
  20103. this._errors.push(new I18nError(el.sourceSpan, msg));
  20104. };
  20105. return I18nToHtmlVisitor;
  20106. }());
  20107. /**
  20108. * @license
  20109. * Copyright Google Inc. All Rights Reserved.
  20110. *
  20111. * Use of this source code is governed by an MIT-style license that can be
  20112. * found in the LICENSE file at https://angular.io/license
  20113. */
  20114. var I18NHtmlParser = /** @class */ (function () {
  20115. function I18NHtmlParser(_htmlParser, translations, translationsFormat, missingTranslation, console) {
  20116. if (missingTranslation === void 0) { missingTranslation = MissingTranslationStrategy.Warning; }
  20117. this._htmlParser = _htmlParser;
  20118. if (translations) {
  20119. var serializer = createSerializer(translationsFormat);
  20120. this._translationBundle =
  20121. TranslationBundle.load(translations, 'i18n', serializer, missingTranslation, console);
  20122. }
  20123. else {
  20124. this._translationBundle =
  20125. new TranslationBundle({}, null, digest, undefined, missingTranslation, console);
  20126. }
  20127. }
  20128. I18NHtmlParser.prototype.parse = function (source, url, options) {
  20129. if (options === void 0) { options = {}; }
  20130. var interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
  20131. var parseResult = this._htmlParser.parse(source, url, __assign({ interpolationConfig: interpolationConfig }, options));
  20132. if (parseResult.errors.length) {
  20133. return new ParseTreeResult(parseResult.rootNodes, parseResult.errors);
  20134. }
  20135. return mergeTranslations(parseResult.rootNodes, this._translationBundle, interpolationConfig, [], {});
  20136. };
  20137. return I18NHtmlParser;
  20138. }());
  20139. function createSerializer(format) {
  20140. format = (format || 'xlf').toLowerCase();
  20141. switch (format) {
  20142. case 'xmb':
  20143. return new Xmb();
  20144. case 'xtb':
  20145. return new Xtb();
  20146. case 'xliff2':
  20147. case 'xlf2':
  20148. return new Xliff2();
  20149. case 'xliff':
  20150. case 'xlf':
  20151. default:
  20152. return new Xliff();
  20153. }
  20154. }
  20155. /**
  20156. * @license
  20157. * Copyright Google Inc. All Rights Reserved.
  20158. *
  20159. * Use of this source code is governed by an MIT-style license that can be
  20160. * found in the LICENSE file at https://angular.io/license
  20161. */
  20162. var QUOTED_KEYS = '$quoted$';
  20163. function convertValueToOutputAst(ctx, value, type) {
  20164. if (type === void 0) { type = null; }
  20165. return visitValue(value, new _ValueOutputAstTransformer(ctx), type);
  20166. }
  20167. var _ValueOutputAstTransformer = /** @class */ (function () {
  20168. function _ValueOutputAstTransformer(ctx) {
  20169. this.ctx = ctx;
  20170. }
  20171. _ValueOutputAstTransformer.prototype.visitArray = function (arr, type) {
  20172. var _this = this;
  20173. return literalArr(arr.map(function (value) { return visitValue(value, _this, null); }), type);
  20174. };
  20175. _ValueOutputAstTransformer.prototype.visitStringMap = function (map, type) {
  20176. var _this = this;
  20177. var entries = [];
  20178. var quotedSet = new Set(map && map[QUOTED_KEYS]);
  20179. Object.keys(map).forEach(function (key) {
  20180. entries.push(new LiteralMapEntry(key, visitValue(map[key], _this, null), quotedSet.has(key)));
  20181. });
  20182. return new LiteralMapExpr(entries, type);
  20183. };
  20184. _ValueOutputAstTransformer.prototype.visitPrimitive = function (value, type) { return literal(value, type); };
  20185. _ValueOutputAstTransformer.prototype.visitOther = function (value, type) {
  20186. if (value instanceof Expression) {
  20187. return value;
  20188. }
  20189. else {
  20190. return this.ctx.importExpr(value);
  20191. }
  20192. };
  20193. return _ValueOutputAstTransformer;
  20194. }());
  20195. /**
  20196. * @license
  20197. * Copyright Google Inc. All Rights Reserved.
  20198. *
  20199. * Use of this source code is governed by an MIT-style license that can be
  20200. * found in the LICENSE file at https://angular.io/license
  20201. */
  20202. function mapEntry(key, value) {
  20203. return { key: key, value: value, quoted: false };
  20204. }
  20205. var InjectableCompiler = /** @class */ (function () {
  20206. function InjectableCompiler(reflector, alwaysGenerateDef) {
  20207. this.reflector = reflector;
  20208. this.alwaysGenerateDef = alwaysGenerateDef;
  20209. this.tokenInjector = reflector.resolveExternalReference(Identifiers.Injector);
  20210. }
  20211. InjectableCompiler.prototype.depsArray = function (deps, ctx) {
  20212. var _this = this;
  20213. return deps.map(function (dep) {
  20214. var token = dep;
  20215. var args = [token];
  20216. var flags = 0 /* Default */;
  20217. if (Array.isArray(dep)) {
  20218. for (var i = 0; i < dep.length; i++) {
  20219. var v = dep[i];
  20220. if (v) {
  20221. if (v.ngMetadataName === 'Optional') {
  20222. flags |= 8 /* Optional */;
  20223. }
  20224. else if (v.ngMetadataName === 'SkipSelf') {
  20225. flags |= 4 /* SkipSelf */;
  20226. }
  20227. else if (v.ngMetadataName === 'Self') {
  20228. flags |= 2 /* Self */;
  20229. }
  20230. else if (v.ngMetadataName === 'Inject') {
  20231. token = v.token;
  20232. }
  20233. else {
  20234. token = v;
  20235. }
  20236. }
  20237. }
  20238. }
  20239. var tokenExpr;
  20240. if (typeof token === 'string') {
  20241. tokenExpr = literal(token);
  20242. }
  20243. else if (token === _this.tokenInjector) {
  20244. tokenExpr = importExpr(Identifiers.INJECTOR);
  20245. }
  20246. else {
  20247. tokenExpr = ctx.importExpr(token);
  20248. }
  20249. if (flags !== 0 /* Default */) {
  20250. args = [tokenExpr, literal(flags)];
  20251. }
  20252. else {
  20253. args = [tokenExpr];
  20254. }
  20255. return importExpr(Identifiers.inject).callFn(args);
  20256. });
  20257. };
  20258. InjectableCompiler.prototype.factoryFor = function (injectable, ctx) {
  20259. var retValue;
  20260. if (injectable.useExisting) {
  20261. retValue = importExpr(Identifiers.inject).callFn([ctx.importExpr(injectable.useExisting)]);
  20262. }
  20263. else if (injectable.useFactory) {
  20264. var deps = injectable.deps || [];
  20265. if (deps.length > 0) {
  20266. retValue = ctx.importExpr(injectable.useFactory).callFn(this.depsArray(deps, ctx));
  20267. }
  20268. else {
  20269. return ctx.importExpr(injectable.useFactory);
  20270. }
  20271. }
  20272. else if (injectable.useValue) {
  20273. retValue = convertValueToOutputAst(ctx, injectable.useValue);
  20274. }
  20275. else {
  20276. var clazz = injectable.useClass || injectable.symbol;
  20277. var depArgs = this.depsArray(this.reflector.parameters(clazz), ctx);
  20278. retValue = new InstantiateExpr(ctx.importExpr(clazz), depArgs);
  20279. }
  20280. return fn([], [new ReturnStatement(retValue)], undefined, undefined, injectable.symbol.name + '_Factory');
  20281. };
  20282. InjectableCompiler.prototype.injectableDef = function (injectable, ctx) {
  20283. var providedIn = NULL_EXPR;
  20284. if (injectable.providedIn !== undefined) {
  20285. if (injectable.providedIn === null) {
  20286. providedIn = NULL_EXPR;
  20287. }
  20288. else if (typeof injectable.providedIn === 'string') {
  20289. providedIn = literal(injectable.providedIn);
  20290. }
  20291. else {
  20292. providedIn = ctx.importExpr(injectable.providedIn);
  20293. }
  20294. }
  20295. var def = [
  20296. mapEntry('factory', this.factoryFor(injectable, ctx)),
  20297. mapEntry('token', ctx.importExpr(injectable.type.reference)),
  20298. mapEntry('providedIn', providedIn),
  20299. ];
  20300. return importExpr(Identifiers.ɵɵdefineInjectable).callFn([literalMap(def)]);
  20301. };
  20302. InjectableCompiler.prototype.compile = function (injectable, ctx) {
  20303. if (this.alwaysGenerateDef || injectable.providedIn !== undefined) {
  20304. var className = identifierName(injectable.type);
  20305. var clazz = new ClassStmt(className, null, [
  20306. new ClassField('ngInjectableDef', INFERRED_TYPE, [exports.StmtModifier.Static], this.injectableDef(injectable, ctx)),
  20307. ], [], new ClassMethod(null, [], []), []);
  20308. ctx.statements.push(clazz);
  20309. }
  20310. };
  20311. return InjectableCompiler;
  20312. }());
  20313. /**
  20314. * @license
  20315. * Copyright Google Inc. All Rights Reserved.
  20316. *
  20317. * Use of this source code is governed by an MIT-style license that can be
  20318. * found in the LICENSE file at https://angular.io/license
  20319. */
  20320. var STRIP_SRC_FILE_SUFFIXES = /(\.ts|\.d\.ts|\.js|\.jsx|\.tsx)$/;
  20321. var GENERATED_FILE = /\.ngfactory\.|\.ngsummary\./;
  20322. var JIT_SUMMARY_FILE = /\.ngsummary\./;
  20323. var JIT_SUMMARY_NAME = /NgSummary$/;
  20324. function ngfactoryFilePath(filePath, forceSourceFile) {
  20325. if (forceSourceFile === void 0) { forceSourceFile = false; }
  20326. var urlWithSuffix = splitTypescriptSuffix(filePath, forceSourceFile);
  20327. return urlWithSuffix[0] + ".ngfactory" + normalizeGenFileSuffix(urlWithSuffix[1]);
  20328. }
  20329. function stripGeneratedFileSuffix(filePath) {
  20330. return filePath.replace(GENERATED_FILE, '.');
  20331. }
  20332. function isGeneratedFile(filePath) {
  20333. return GENERATED_FILE.test(filePath);
  20334. }
  20335. function splitTypescriptSuffix(path, forceSourceFile) {
  20336. if (forceSourceFile === void 0) { forceSourceFile = false; }
  20337. if (path.endsWith('.d.ts')) {
  20338. return [path.slice(0, -5), forceSourceFile ? '.ts' : '.d.ts'];
  20339. }
  20340. var lastDot = path.lastIndexOf('.');
  20341. if (lastDot !== -1) {
  20342. return [path.substring(0, lastDot), path.substring(lastDot)];
  20343. }
  20344. return [path, ''];
  20345. }
  20346. function normalizeGenFileSuffix(srcFileSuffix) {
  20347. return srcFileSuffix === '.tsx' ? '.ts' : srcFileSuffix;
  20348. }
  20349. function summaryFileName(fileName) {
  20350. var fileNameWithoutSuffix = fileName.replace(STRIP_SRC_FILE_SUFFIXES, '');
  20351. return fileNameWithoutSuffix + ".ngsummary.json";
  20352. }
  20353. function summaryForJitFileName(fileName, forceSourceFile) {
  20354. if (forceSourceFile === void 0) { forceSourceFile = false; }
  20355. var urlWithSuffix = splitTypescriptSuffix(stripGeneratedFileSuffix(fileName), forceSourceFile);
  20356. return urlWithSuffix[0] + ".ngsummary" + urlWithSuffix[1];
  20357. }
  20358. function stripSummaryForJitFileSuffix(filePath) {
  20359. return filePath.replace(JIT_SUMMARY_FILE, '.');
  20360. }
  20361. function summaryForJitName(symbolName) {
  20362. return symbolName + "NgSummary";
  20363. }
  20364. function stripSummaryForJitNameSuffix(symbolName) {
  20365. return symbolName.replace(JIT_SUMMARY_NAME, '');
  20366. }
  20367. var LOWERED_SYMBOL = /\u0275\d+/;
  20368. function isLoweredSymbol(name) {
  20369. return LOWERED_SYMBOL.test(name);
  20370. }
  20371. function createLoweredSymbol(id) {
  20372. return "\u0275" + id;
  20373. }
  20374. /**
  20375. * @license
  20376. * Copyright Google Inc. All Rights Reserved.
  20377. *
  20378. * Use of this source code is governed by an MIT-style license that can be
  20379. * found in the LICENSE file at https://angular.io/license
  20380. */
  20381. var LifecycleHooks;
  20382. (function (LifecycleHooks) {
  20383. LifecycleHooks[LifecycleHooks["OnInit"] = 0] = "OnInit";
  20384. LifecycleHooks[LifecycleHooks["OnDestroy"] = 1] = "OnDestroy";
  20385. LifecycleHooks[LifecycleHooks["DoCheck"] = 2] = "DoCheck";
  20386. LifecycleHooks[LifecycleHooks["OnChanges"] = 3] = "OnChanges";
  20387. LifecycleHooks[LifecycleHooks["AfterContentInit"] = 4] = "AfterContentInit";
  20388. LifecycleHooks[LifecycleHooks["AfterContentChecked"] = 5] = "AfterContentChecked";
  20389. LifecycleHooks[LifecycleHooks["AfterViewInit"] = 6] = "AfterViewInit";
  20390. LifecycleHooks[LifecycleHooks["AfterViewChecked"] = 7] = "AfterViewChecked";
  20391. })(LifecycleHooks || (LifecycleHooks = {}));
  20392. var LIFECYCLE_HOOKS_VALUES = [
  20393. LifecycleHooks.OnInit, LifecycleHooks.OnDestroy, LifecycleHooks.DoCheck, LifecycleHooks.OnChanges,
  20394. LifecycleHooks.AfterContentInit, LifecycleHooks.AfterContentChecked, LifecycleHooks.AfterViewInit,
  20395. LifecycleHooks.AfterViewChecked
  20396. ];
  20397. function hasLifecycleHook(reflector, hook, token) {
  20398. return reflector.hasLifecycleHook(token, getHookName(hook));
  20399. }
  20400. function getAllLifecycleHooks(reflector, token) {
  20401. return LIFECYCLE_HOOKS_VALUES.filter(function (hook) { return hasLifecycleHook(reflector, hook, token); });
  20402. }
  20403. function getHookName(hook) {
  20404. switch (hook) {
  20405. case LifecycleHooks.OnInit:
  20406. return 'ngOnInit';
  20407. case LifecycleHooks.OnDestroy:
  20408. return 'ngOnDestroy';
  20409. case LifecycleHooks.DoCheck:
  20410. return 'ngDoCheck';
  20411. case LifecycleHooks.OnChanges:
  20412. return 'ngOnChanges';
  20413. case LifecycleHooks.AfterContentInit:
  20414. return 'ngAfterContentInit';
  20415. case LifecycleHooks.AfterContentChecked:
  20416. return 'ngAfterContentChecked';
  20417. case LifecycleHooks.AfterViewInit:
  20418. return 'ngAfterViewInit';
  20419. case LifecycleHooks.AfterViewChecked:
  20420. return 'ngAfterViewChecked';
  20421. default:
  20422. // This default case is not needed by TypeScript compiler, as the switch is exhaustive.
  20423. // However Closure Compiler does not understand that and reports an error in typed mode.
  20424. // The `throw new Error` below works around the problem, and the unexpected: never variable
  20425. // makes sure tsc still checks this code is unreachable.
  20426. var unexpected = hook;
  20427. throw new Error("unexpected " + unexpected);
  20428. }
  20429. }
  20430. /**
  20431. * @license
  20432. * Copyright Google Inc. All Rights Reserved.
  20433. *
  20434. * Use of this source code is governed by an MIT-style license that can be
  20435. * found in the LICENSE file at https://angular.io/license
  20436. */
  20437. var ERROR_COMPONENT_TYPE = 'ngComponentType';
  20438. // Design notes:
  20439. // - don't lazily create metadata:
  20440. // For some metadata, we need to do async work sometimes,
  20441. // so the user has to kick off this loading.
  20442. // But we want to report errors even when the async work is
  20443. // not required to check that the user would have been able
  20444. // to wait correctly.
  20445. var CompileMetadataResolver = /** @class */ (function () {
  20446. function CompileMetadataResolver(_config, _htmlParser, _ngModuleResolver, _directiveResolver, _pipeResolver, _summaryResolver, _schemaRegistry, _directiveNormalizer, _console, _staticSymbolCache, _reflector, _errorCollector) {
  20447. this._config = _config;
  20448. this._htmlParser = _htmlParser;
  20449. this._ngModuleResolver = _ngModuleResolver;
  20450. this._directiveResolver = _directiveResolver;
  20451. this._pipeResolver = _pipeResolver;
  20452. this._summaryResolver = _summaryResolver;
  20453. this._schemaRegistry = _schemaRegistry;
  20454. this._directiveNormalizer = _directiveNormalizer;
  20455. this._console = _console;
  20456. this._staticSymbolCache = _staticSymbolCache;
  20457. this._reflector = _reflector;
  20458. this._errorCollector = _errorCollector;
  20459. this._nonNormalizedDirectiveCache = new Map();
  20460. this._directiveCache = new Map();
  20461. this._summaryCache = new Map();
  20462. this._pipeCache = new Map();
  20463. this._ngModuleCache = new Map();
  20464. this._ngModuleOfTypes = new Map();
  20465. this._shallowModuleCache = new Map();
  20466. }
  20467. CompileMetadataResolver.prototype.getReflector = function () { return this._reflector; };
  20468. CompileMetadataResolver.prototype.clearCacheFor = function (type) {
  20469. var dirMeta = this._directiveCache.get(type);
  20470. this._directiveCache.delete(type);
  20471. this._nonNormalizedDirectiveCache.delete(type);
  20472. this._summaryCache.delete(type);
  20473. this._pipeCache.delete(type);
  20474. this._ngModuleOfTypes.delete(type);
  20475. // Clear all of the NgModule as they contain transitive information!
  20476. this._ngModuleCache.clear();
  20477. if (dirMeta) {
  20478. this._directiveNormalizer.clearCacheFor(dirMeta);
  20479. }
  20480. };
  20481. CompileMetadataResolver.prototype.clearCache = function () {
  20482. this._directiveCache.clear();
  20483. this._nonNormalizedDirectiveCache.clear();
  20484. this._summaryCache.clear();
  20485. this._pipeCache.clear();
  20486. this._ngModuleCache.clear();
  20487. this._ngModuleOfTypes.clear();
  20488. this._directiveNormalizer.clearCache();
  20489. };
  20490. CompileMetadataResolver.prototype._createProxyClass = function (baseType, name) {
  20491. var delegate = null;
  20492. var proxyClass = function () {
  20493. if (!delegate) {
  20494. throw new Error("Illegal state: Class " + name + " for type " + stringify(baseType) + " is not compiled yet!");
  20495. }
  20496. return delegate.apply(this, arguments);
  20497. };
  20498. proxyClass.setDelegate = function (d) {
  20499. delegate = d;
  20500. proxyClass.prototype = d.prototype;
  20501. };
  20502. // Make stringify work correctly
  20503. proxyClass.overriddenName = name;
  20504. return proxyClass;
  20505. };
  20506. CompileMetadataResolver.prototype.getGeneratedClass = function (dirType, name) {
  20507. if (dirType instanceof StaticSymbol) {
  20508. return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), name);
  20509. }
  20510. else {
  20511. return this._createProxyClass(dirType, name);
  20512. }
  20513. };
  20514. CompileMetadataResolver.prototype.getComponentViewClass = function (dirType) {
  20515. return this.getGeneratedClass(dirType, viewClassName(dirType, 0));
  20516. };
  20517. CompileMetadataResolver.prototype.getHostComponentViewClass = function (dirType) {
  20518. return this.getGeneratedClass(dirType, hostViewClassName(dirType));
  20519. };
  20520. CompileMetadataResolver.prototype.getHostComponentType = function (dirType) {
  20521. var name = identifierName({ reference: dirType }) + "_Host";
  20522. if (dirType instanceof StaticSymbol) {
  20523. return this._staticSymbolCache.get(dirType.filePath, name);
  20524. }
  20525. return this._createProxyClass(dirType, name);
  20526. };
  20527. CompileMetadataResolver.prototype.getRendererType = function (dirType) {
  20528. if (dirType instanceof StaticSymbol) {
  20529. return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), rendererTypeName(dirType));
  20530. }
  20531. else {
  20532. // returning an object as proxy,
  20533. // that we fill later during runtime compilation.
  20534. return {};
  20535. }
  20536. };
  20537. CompileMetadataResolver.prototype.getComponentFactory = function (selector, dirType, inputs, outputs) {
  20538. if (dirType instanceof StaticSymbol) {
  20539. return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), componentFactoryName(dirType));
  20540. }
  20541. else {
  20542. var hostView = this.getHostComponentViewClass(dirType);
  20543. // Note: ngContentSelectors will be filled later once the template is
  20544. // loaded.
  20545. var createComponentFactory = this._reflector.resolveExternalReference(Identifiers.createComponentFactory);
  20546. return createComponentFactory(selector, dirType, hostView, inputs, outputs, []);
  20547. }
  20548. };
  20549. CompileMetadataResolver.prototype.initComponentFactory = function (factory, ngContentSelectors) {
  20550. var _a;
  20551. if (!(factory instanceof StaticSymbol)) {
  20552. (_a = factory.ngContentSelectors).push.apply(_a, __spread(ngContentSelectors));
  20553. }
  20554. };
  20555. CompileMetadataResolver.prototype._loadSummary = function (type, kind) {
  20556. var typeSummary = this._summaryCache.get(type);
  20557. if (!typeSummary) {
  20558. var summary = this._summaryResolver.resolveSummary(type);
  20559. typeSummary = summary ? summary.type : null;
  20560. this._summaryCache.set(type, typeSummary || null);
  20561. }
  20562. return typeSummary && typeSummary.summaryKind === kind ? typeSummary : null;
  20563. };
  20564. CompileMetadataResolver.prototype.getHostComponentMetadata = function (compMeta, hostViewType) {
  20565. var hostType = this.getHostComponentType(compMeta.type.reference);
  20566. if (!hostViewType) {
  20567. hostViewType = this.getHostComponentViewClass(hostType);
  20568. }
  20569. // Note: ! is ok here as this method should only be called with normalized directive
  20570. // metadata, which always fills in the selector.
  20571. var template = CssSelector.parse(compMeta.selector)[0].getMatchingElementTemplate();
  20572. var templateUrl = '';
  20573. var htmlAst = this._htmlParser.parse(template, templateUrl);
  20574. return CompileDirectiveMetadata.create({
  20575. isHost: true,
  20576. type: { reference: hostType, diDeps: [], lifecycleHooks: [] },
  20577. template: new CompileTemplateMetadata({
  20578. encapsulation: ViewEncapsulation.None,
  20579. template: template,
  20580. templateUrl: templateUrl,
  20581. htmlAst: htmlAst,
  20582. styles: [],
  20583. styleUrls: [],
  20584. ngContentSelectors: [],
  20585. animations: [],
  20586. isInline: true,
  20587. externalStylesheets: [],
  20588. interpolation: null,
  20589. preserveWhitespaces: false,
  20590. }),
  20591. exportAs: null,
  20592. changeDetection: ChangeDetectionStrategy.Default,
  20593. inputs: [],
  20594. outputs: [],
  20595. host: {},
  20596. isComponent: true,
  20597. selector: '*',
  20598. providers: [],
  20599. viewProviders: [],
  20600. queries: [],
  20601. guards: {},
  20602. viewQueries: [],
  20603. componentViewType: hostViewType,
  20604. rendererType: { id: '__Host__', encapsulation: ViewEncapsulation.None, styles: [], data: {} },
  20605. entryComponents: [],
  20606. componentFactory: null
  20607. });
  20608. };
  20609. CompileMetadataResolver.prototype.loadDirectiveMetadata = function (ngModuleType, directiveType, isSync) {
  20610. var _this = this;
  20611. if (this._directiveCache.has(directiveType)) {
  20612. return null;
  20613. }
  20614. directiveType = resolveForwardRef(directiveType);
  20615. var _a = this.getNonNormalizedDirectiveMetadata(directiveType), annotation = _a.annotation, metadata = _a.metadata;
  20616. var createDirectiveMetadata = function (templateMetadata) {
  20617. var normalizedDirMeta = new CompileDirectiveMetadata({
  20618. isHost: false,
  20619. type: metadata.type,
  20620. isComponent: metadata.isComponent,
  20621. selector: metadata.selector,
  20622. exportAs: metadata.exportAs,
  20623. changeDetection: metadata.changeDetection,
  20624. inputs: metadata.inputs,
  20625. outputs: metadata.outputs,
  20626. hostListeners: metadata.hostListeners,
  20627. hostProperties: metadata.hostProperties,
  20628. hostAttributes: metadata.hostAttributes,
  20629. providers: metadata.providers,
  20630. viewProviders: metadata.viewProviders,
  20631. queries: metadata.queries,
  20632. guards: metadata.guards,
  20633. viewQueries: metadata.viewQueries,
  20634. entryComponents: metadata.entryComponents,
  20635. componentViewType: metadata.componentViewType,
  20636. rendererType: metadata.rendererType,
  20637. componentFactory: metadata.componentFactory,
  20638. template: templateMetadata
  20639. });
  20640. if (templateMetadata) {
  20641. _this.initComponentFactory(metadata.componentFactory, templateMetadata.ngContentSelectors);
  20642. }
  20643. _this._directiveCache.set(directiveType, normalizedDirMeta);
  20644. _this._summaryCache.set(directiveType, normalizedDirMeta.toSummary());
  20645. return null;
  20646. };
  20647. if (metadata.isComponent) {
  20648. var template = metadata.template;
  20649. var templateMeta = this._directiveNormalizer.normalizeTemplate({
  20650. ngModuleType: ngModuleType,
  20651. componentType: directiveType,
  20652. moduleUrl: this._reflector.componentModuleUrl(directiveType, annotation),
  20653. encapsulation: template.encapsulation,
  20654. template: template.template,
  20655. templateUrl: template.templateUrl,
  20656. styles: template.styles,
  20657. styleUrls: template.styleUrls,
  20658. animations: template.animations,
  20659. interpolation: template.interpolation,
  20660. preserveWhitespaces: template.preserveWhitespaces
  20661. });
  20662. if (isPromise(templateMeta) && isSync) {
  20663. this._reportError(componentStillLoadingError(directiveType), directiveType);
  20664. return null;
  20665. }
  20666. return SyncAsync.then(templateMeta, createDirectiveMetadata);
  20667. }
  20668. else {
  20669. // directive
  20670. createDirectiveMetadata(null);
  20671. return null;
  20672. }
  20673. };
  20674. CompileMetadataResolver.prototype.getNonNormalizedDirectiveMetadata = function (directiveType) {
  20675. var _this = this;
  20676. directiveType = resolveForwardRef(directiveType);
  20677. if (!directiveType) {
  20678. return null;
  20679. }
  20680. var cacheEntry = this._nonNormalizedDirectiveCache.get(directiveType);
  20681. if (cacheEntry) {
  20682. return cacheEntry;
  20683. }
  20684. var dirMeta = this._directiveResolver.resolve(directiveType, false);
  20685. if (!dirMeta) {
  20686. return null;
  20687. }
  20688. var nonNormalizedTemplateMetadata = undefined;
  20689. if (createComponent.isTypeOf(dirMeta)) {
  20690. // component
  20691. var compMeta = dirMeta;
  20692. assertArrayOfStrings('styles', compMeta.styles);
  20693. assertArrayOfStrings('styleUrls', compMeta.styleUrls);
  20694. assertInterpolationSymbols('interpolation', compMeta.interpolation);
  20695. var animations = compMeta.animations;
  20696. nonNormalizedTemplateMetadata = new CompileTemplateMetadata({
  20697. encapsulation: noUndefined(compMeta.encapsulation),
  20698. template: noUndefined(compMeta.template),
  20699. templateUrl: noUndefined(compMeta.templateUrl),
  20700. htmlAst: null,
  20701. styles: compMeta.styles || [],
  20702. styleUrls: compMeta.styleUrls || [],
  20703. animations: animations || [],
  20704. interpolation: noUndefined(compMeta.interpolation),
  20705. isInline: !!compMeta.template,
  20706. externalStylesheets: [],
  20707. ngContentSelectors: [],
  20708. preserveWhitespaces: noUndefined(dirMeta.preserveWhitespaces),
  20709. });
  20710. }
  20711. var changeDetectionStrategy = null;
  20712. var viewProviders = [];
  20713. var entryComponentMetadata = [];
  20714. var selector = dirMeta.selector;
  20715. if (createComponent.isTypeOf(dirMeta)) {
  20716. // Component
  20717. var compMeta = dirMeta;
  20718. changeDetectionStrategy = compMeta.changeDetection;
  20719. if (compMeta.viewProviders) {
  20720. viewProviders = this._getProvidersMetadata(compMeta.viewProviders, entryComponentMetadata, "viewProviders for \"" + stringifyType(directiveType) + "\"", [], directiveType);
  20721. }
  20722. if (compMeta.entryComponents) {
  20723. entryComponentMetadata = flattenAndDedupeArray(compMeta.entryComponents)
  20724. .map(function (type) { return _this._getEntryComponentMetadata(type); })
  20725. .concat(entryComponentMetadata);
  20726. }
  20727. if (!selector) {
  20728. selector = this._schemaRegistry.getDefaultComponentElementName();
  20729. }
  20730. }
  20731. else {
  20732. // Directive
  20733. if (!selector) {
  20734. this._reportError(syntaxError("Directive " + stringifyType(directiveType) + " has no selector, please add it!"), directiveType);
  20735. selector = 'error';
  20736. }
  20737. }
  20738. var providers = [];
  20739. if (dirMeta.providers != null) {
  20740. providers = this._getProvidersMetadata(dirMeta.providers, entryComponentMetadata, "providers for \"" + stringifyType(directiveType) + "\"", [], directiveType);
  20741. }
  20742. var queries = [];
  20743. var viewQueries = [];
  20744. if (dirMeta.queries != null) {
  20745. queries = this._getQueriesMetadata(dirMeta.queries, false, directiveType);
  20746. viewQueries = this._getQueriesMetadata(dirMeta.queries, true, directiveType);
  20747. }
  20748. var metadata = CompileDirectiveMetadata.create({
  20749. isHost: false,
  20750. selector: selector,
  20751. exportAs: noUndefined(dirMeta.exportAs),
  20752. isComponent: !!nonNormalizedTemplateMetadata,
  20753. type: this._getTypeMetadata(directiveType),
  20754. template: nonNormalizedTemplateMetadata,
  20755. changeDetection: changeDetectionStrategy,
  20756. inputs: dirMeta.inputs || [],
  20757. outputs: dirMeta.outputs || [],
  20758. host: dirMeta.host || {},
  20759. providers: providers || [],
  20760. viewProviders: viewProviders || [],
  20761. queries: queries || [],
  20762. guards: dirMeta.guards || {},
  20763. viewQueries: viewQueries || [],
  20764. entryComponents: entryComponentMetadata,
  20765. componentViewType: nonNormalizedTemplateMetadata ? this.getComponentViewClass(directiveType) :
  20766. null,
  20767. rendererType: nonNormalizedTemplateMetadata ? this.getRendererType(directiveType) : null,
  20768. componentFactory: null
  20769. });
  20770. if (nonNormalizedTemplateMetadata) {
  20771. metadata.componentFactory =
  20772. this.getComponentFactory(selector, directiveType, metadata.inputs, metadata.outputs);
  20773. }
  20774. cacheEntry = { metadata: metadata, annotation: dirMeta };
  20775. this._nonNormalizedDirectiveCache.set(directiveType, cacheEntry);
  20776. return cacheEntry;
  20777. };
  20778. /**
  20779. * Gets the metadata for the given directive.
  20780. * This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
  20781. */
  20782. CompileMetadataResolver.prototype.getDirectiveMetadata = function (directiveType) {
  20783. var dirMeta = this._directiveCache.get(directiveType);
  20784. if (!dirMeta) {
  20785. this._reportError(syntaxError("Illegal state: getDirectiveMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Directive " + stringifyType(directiveType) + "."), directiveType);
  20786. }
  20787. return dirMeta;
  20788. };
  20789. CompileMetadataResolver.prototype.getDirectiveSummary = function (dirType) {
  20790. var dirSummary = this._loadSummary(dirType, exports.CompileSummaryKind.Directive);
  20791. if (!dirSummary) {
  20792. this._reportError(syntaxError("Illegal state: Could not load the summary for directive " + stringifyType(dirType) + "."), dirType);
  20793. }
  20794. return dirSummary;
  20795. };
  20796. CompileMetadataResolver.prototype.isDirective = function (type) {
  20797. return !!this._loadSummary(type, exports.CompileSummaryKind.Directive) ||
  20798. this._directiveResolver.isDirective(type);
  20799. };
  20800. CompileMetadataResolver.prototype.isPipe = function (type) {
  20801. return !!this._loadSummary(type, exports.CompileSummaryKind.Pipe) ||
  20802. this._pipeResolver.isPipe(type);
  20803. };
  20804. CompileMetadataResolver.prototype.isNgModule = function (type) {
  20805. return !!this._loadSummary(type, exports.CompileSummaryKind.NgModule) ||
  20806. this._ngModuleResolver.isNgModule(type);
  20807. };
  20808. CompileMetadataResolver.prototype.getNgModuleSummary = function (moduleType, alreadyCollecting) {
  20809. if (alreadyCollecting === void 0) { alreadyCollecting = null; }
  20810. var moduleSummary = this._loadSummary(moduleType, exports.CompileSummaryKind.NgModule);
  20811. if (!moduleSummary) {
  20812. var moduleMeta = this.getNgModuleMetadata(moduleType, false, alreadyCollecting);
  20813. moduleSummary = moduleMeta ? moduleMeta.toSummary() : null;
  20814. if (moduleSummary) {
  20815. this._summaryCache.set(moduleType, moduleSummary);
  20816. }
  20817. }
  20818. return moduleSummary;
  20819. };
  20820. /**
  20821. * Loads the declared directives and pipes of an NgModule.
  20822. */
  20823. CompileMetadataResolver.prototype.loadNgModuleDirectiveAndPipeMetadata = function (moduleType, isSync, throwIfNotFound) {
  20824. var _this = this;
  20825. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  20826. var ngModule = this.getNgModuleMetadata(moduleType, throwIfNotFound);
  20827. var loading = [];
  20828. if (ngModule) {
  20829. ngModule.declaredDirectives.forEach(function (id) {
  20830. var promise = _this.loadDirectiveMetadata(moduleType, id.reference, isSync);
  20831. if (promise) {
  20832. loading.push(promise);
  20833. }
  20834. });
  20835. ngModule.declaredPipes.forEach(function (id) { return _this._loadPipeMetadata(id.reference); });
  20836. }
  20837. return Promise.all(loading);
  20838. };
  20839. CompileMetadataResolver.prototype.getShallowModuleMetadata = function (moduleType) {
  20840. var compileMeta = this._shallowModuleCache.get(moduleType);
  20841. if (compileMeta) {
  20842. return compileMeta;
  20843. }
  20844. var ngModuleMeta = findLast(this._reflector.shallowAnnotations(moduleType), createNgModule.isTypeOf);
  20845. compileMeta = {
  20846. type: this._getTypeMetadata(moduleType),
  20847. rawExports: ngModuleMeta.exports,
  20848. rawImports: ngModuleMeta.imports,
  20849. rawProviders: ngModuleMeta.providers,
  20850. };
  20851. this._shallowModuleCache.set(moduleType, compileMeta);
  20852. return compileMeta;
  20853. };
  20854. CompileMetadataResolver.prototype.getNgModuleMetadata = function (moduleType, throwIfNotFound, alreadyCollecting) {
  20855. var _this = this;
  20856. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  20857. if (alreadyCollecting === void 0) { alreadyCollecting = null; }
  20858. moduleType = resolveForwardRef(moduleType);
  20859. var compileMeta = this._ngModuleCache.get(moduleType);
  20860. if (compileMeta) {
  20861. return compileMeta;
  20862. }
  20863. var meta = this._ngModuleResolver.resolve(moduleType, throwIfNotFound);
  20864. if (!meta) {
  20865. return null;
  20866. }
  20867. var declaredDirectives = [];
  20868. var exportedNonModuleIdentifiers = [];
  20869. var declaredPipes = [];
  20870. var importedModules = [];
  20871. var exportedModules = [];
  20872. var providers = [];
  20873. var entryComponents = [];
  20874. var bootstrapComponents = [];
  20875. var schemas = [];
  20876. if (meta.imports) {
  20877. flattenAndDedupeArray(meta.imports).forEach(function (importedType) {
  20878. var importedModuleType = undefined;
  20879. if (isValidType(importedType)) {
  20880. importedModuleType = importedType;
  20881. }
  20882. else if (importedType && importedType.ngModule) {
  20883. var moduleWithProviders = importedType;
  20884. importedModuleType = moduleWithProviders.ngModule;
  20885. if (moduleWithProviders.providers) {
  20886. providers.push.apply(providers, __spread(_this._getProvidersMetadata(moduleWithProviders.providers, entryComponents, "provider for the NgModule '" + stringifyType(importedModuleType) + "'", [], importedType)));
  20887. }
  20888. }
  20889. if (importedModuleType) {
  20890. if (_this._checkSelfImport(moduleType, importedModuleType))
  20891. return;
  20892. if (!alreadyCollecting)
  20893. alreadyCollecting = new Set();
  20894. if (alreadyCollecting.has(importedModuleType)) {
  20895. _this._reportError(syntaxError(_this._getTypeDescriptor(importedModuleType) + " '" + stringifyType(importedType) + "' is imported recursively by the module '" + stringifyType(moduleType) + "'."), moduleType);
  20896. return;
  20897. }
  20898. alreadyCollecting.add(importedModuleType);
  20899. var importedModuleSummary = _this.getNgModuleSummary(importedModuleType, alreadyCollecting);
  20900. alreadyCollecting.delete(importedModuleType);
  20901. if (!importedModuleSummary) {
  20902. _this._reportError(syntaxError("Unexpected " + _this._getTypeDescriptor(importedType) + " '" + stringifyType(importedType) + "' imported by the module '" + stringifyType(moduleType) + "'. Please add a @NgModule annotation."), moduleType);
  20903. return;
  20904. }
  20905. importedModules.push(importedModuleSummary);
  20906. }
  20907. else {
  20908. _this._reportError(syntaxError("Unexpected value '" + stringifyType(importedType) + "' imported by the module '" + stringifyType(moduleType) + "'"), moduleType);
  20909. return;
  20910. }
  20911. });
  20912. }
  20913. if (meta.exports) {
  20914. flattenAndDedupeArray(meta.exports).forEach(function (exportedType) {
  20915. if (!isValidType(exportedType)) {
  20916. _this._reportError(syntaxError("Unexpected value '" + stringifyType(exportedType) + "' exported by the module '" + stringifyType(moduleType) + "'"), moduleType);
  20917. return;
  20918. }
  20919. if (!alreadyCollecting)
  20920. alreadyCollecting = new Set();
  20921. if (alreadyCollecting.has(exportedType)) {
  20922. _this._reportError(syntaxError(_this._getTypeDescriptor(exportedType) + " '" + stringify(exportedType) + "' is exported recursively by the module '" + stringifyType(moduleType) + "'"), moduleType);
  20923. return;
  20924. }
  20925. alreadyCollecting.add(exportedType);
  20926. var exportedModuleSummary = _this.getNgModuleSummary(exportedType, alreadyCollecting);
  20927. alreadyCollecting.delete(exportedType);
  20928. if (exportedModuleSummary) {
  20929. exportedModules.push(exportedModuleSummary);
  20930. }
  20931. else {
  20932. exportedNonModuleIdentifiers.push(_this._getIdentifierMetadata(exportedType));
  20933. }
  20934. });
  20935. }
  20936. // Note: This will be modified later, so we rely on
  20937. // getting a new instance every time!
  20938. var transitiveModule = this._getTransitiveNgModuleMetadata(importedModules, exportedModules);
  20939. if (meta.declarations) {
  20940. flattenAndDedupeArray(meta.declarations).forEach(function (declaredType) {
  20941. if (!isValidType(declaredType)) {
  20942. _this._reportError(syntaxError("Unexpected value '" + stringifyType(declaredType) + "' declared by the module '" + stringifyType(moduleType) + "'"), moduleType);
  20943. return;
  20944. }
  20945. var declaredIdentifier = _this._getIdentifierMetadata(declaredType);
  20946. if (_this.isDirective(declaredType)) {
  20947. transitiveModule.addDirective(declaredIdentifier);
  20948. declaredDirectives.push(declaredIdentifier);
  20949. _this._addTypeToModule(declaredType, moduleType);
  20950. }
  20951. else if (_this.isPipe(declaredType)) {
  20952. transitiveModule.addPipe(declaredIdentifier);
  20953. transitiveModule.pipes.push(declaredIdentifier);
  20954. declaredPipes.push(declaredIdentifier);
  20955. _this._addTypeToModule(declaredType, moduleType);
  20956. }
  20957. else {
  20958. _this._reportError(syntaxError("Unexpected " + _this._getTypeDescriptor(declaredType) + " '" + stringifyType(declaredType) + "' declared by the module '" + stringifyType(moduleType) + "'. Please add a @Pipe/@Directive/@Component annotation."), moduleType);
  20959. return;
  20960. }
  20961. });
  20962. }
  20963. var exportedDirectives = [];
  20964. var exportedPipes = [];
  20965. exportedNonModuleIdentifiers.forEach(function (exportedId) {
  20966. if (transitiveModule.directivesSet.has(exportedId.reference)) {
  20967. exportedDirectives.push(exportedId);
  20968. transitiveModule.addExportedDirective(exportedId);
  20969. }
  20970. else if (transitiveModule.pipesSet.has(exportedId.reference)) {
  20971. exportedPipes.push(exportedId);
  20972. transitiveModule.addExportedPipe(exportedId);
  20973. }
  20974. else {
  20975. _this._reportError(syntaxError("Can't export " + _this._getTypeDescriptor(exportedId.reference) + " " + stringifyType(exportedId.reference) + " from " + stringifyType(moduleType) + " as it was neither declared nor imported!"), moduleType);
  20976. return;
  20977. }
  20978. });
  20979. // The providers of the module have to go last
  20980. // so that they overwrite any other provider we already added.
  20981. if (meta.providers) {
  20982. providers.push.apply(providers, __spread(this._getProvidersMetadata(meta.providers, entryComponents, "provider for the NgModule '" + stringifyType(moduleType) + "'", [], moduleType)));
  20983. }
  20984. if (meta.entryComponents) {
  20985. entryComponents.push.apply(entryComponents, __spread(flattenAndDedupeArray(meta.entryComponents)
  20986. .map(function (type) { return _this._getEntryComponentMetadata(type); })));
  20987. }
  20988. if (meta.bootstrap) {
  20989. flattenAndDedupeArray(meta.bootstrap).forEach(function (type) {
  20990. if (!isValidType(type)) {
  20991. _this._reportError(syntaxError("Unexpected value '" + stringifyType(type) + "' used in the bootstrap property of module '" + stringifyType(moduleType) + "'"), moduleType);
  20992. return;
  20993. }
  20994. bootstrapComponents.push(_this._getIdentifierMetadata(type));
  20995. });
  20996. }
  20997. entryComponents.push.apply(entryComponents, __spread(bootstrapComponents.map(function (type) { return _this._getEntryComponentMetadata(type.reference); })));
  20998. if (meta.schemas) {
  20999. schemas.push.apply(schemas, __spread(flattenAndDedupeArray(meta.schemas)));
  21000. }
  21001. compileMeta = new CompileNgModuleMetadata({
  21002. type: this._getTypeMetadata(moduleType),
  21003. providers: providers,
  21004. entryComponents: entryComponents,
  21005. bootstrapComponents: bootstrapComponents,
  21006. schemas: schemas,
  21007. declaredDirectives: declaredDirectives,
  21008. exportedDirectives: exportedDirectives,
  21009. declaredPipes: declaredPipes,
  21010. exportedPipes: exportedPipes,
  21011. importedModules: importedModules,
  21012. exportedModules: exportedModules,
  21013. transitiveModule: transitiveModule,
  21014. id: meta.id || null,
  21015. });
  21016. entryComponents.forEach(function (id) { return transitiveModule.addEntryComponent(id); });
  21017. providers.forEach(function (provider) { return transitiveModule.addProvider(provider, compileMeta.type); });
  21018. transitiveModule.addModule(compileMeta.type);
  21019. this._ngModuleCache.set(moduleType, compileMeta);
  21020. return compileMeta;
  21021. };
  21022. CompileMetadataResolver.prototype._checkSelfImport = function (moduleType, importedModuleType) {
  21023. if (moduleType === importedModuleType) {
  21024. this._reportError(syntaxError("'" + stringifyType(moduleType) + "' module can't import itself"), moduleType);
  21025. return true;
  21026. }
  21027. return false;
  21028. };
  21029. CompileMetadataResolver.prototype._getTypeDescriptor = function (type) {
  21030. if (isValidType(type)) {
  21031. if (this.isDirective(type)) {
  21032. return 'directive';
  21033. }
  21034. if (this.isPipe(type)) {
  21035. return 'pipe';
  21036. }
  21037. if (this.isNgModule(type)) {
  21038. return 'module';
  21039. }
  21040. }
  21041. if (type.provide) {
  21042. return 'provider';
  21043. }
  21044. return 'value';
  21045. };
  21046. CompileMetadataResolver.prototype._addTypeToModule = function (type, moduleType) {
  21047. var oldModule = this._ngModuleOfTypes.get(type);
  21048. if (oldModule && oldModule !== moduleType) {
  21049. this._reportError(syntaxError("Type " + stringifyType(type) + " is part of the declarations of 2 modules: " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + "! " +
  21050. ("Please consider moving " + stringifyType(type) + " to a higher module that imports " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + ". ") +
  21051. ("You can also create a new NgModule that exports and includes " + stringifyType(type) + " then import that NgModule in " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + ".")), moduleType);
  21052. return;
  21053. }
  21054. this._ngModuleOfTypes.set(type, moduleType);
  21055. };
  21056. CompileMetadataResolver.prototype._getTransitiveNgModuleMetadata = function (importedModules, exportedModules) {
  21057. // collect `providers` / `entryComponents` from all imported and all exported modules
  21058. var result = new TransitiveCompileNgModuleMetadata();
  21059. var modulesByToken = new Map();
  21060. importedModules.concat(exportedModules).forEach(function (modSummary) {
  21061. modSummary.modules.forEach(function (mod) { return result.addModule(mod); });
  21062. modSummary.entryComponents.forEach(function (comp) { return result.addEntryComponent(comp); });
  21063. var addedTokens = new Set();
  21064. modSummary.providers.forEach(function (entry) {
  21065. var tokenRef = tokenReference(entry.provider.token);
  21066. var prevModules = modulesByToken.get(tokenRef);
  21067. if (!prevModules) {
  21068. prevModules = new Set();
  21069. modulesByToken.set(tokenRef, prevModules);
  21070. }
  21071. var moduleRef = entry.module.reference;
  21072. // Note: the providers of one module may still contain multiple providers
  21073. // per token (e.g. for multi providers), and we need to preserve these.
  21074. if (addedTokens.has(tokenRef) || !prevModules.has(moduleRef)) {
  21075. prevModules.add(moduleRef);
  21076. addedTokens.add(tokenRef);
  21077. result.addProvider(entry.provider, entry.module);
  21078. }
  21079. });
  21080. });
  21081. exportedModules.forEach(function (modSummary) {
  21082. modSummary.exportedDirectives.forEach(function (id) { return result.addExportedDirective(id); });
  21083. modSummary.exportedPipes.forEach(function (id) { return result.addExportedPipe(id); });
  21084. });
  21085. importedModules.forEach(function (modSummary) {
  21086. modSummary.exportedDirectives.forEach(function (id) { return result.addDirective(id); });
  21087. modSummary.exportedPipes.forEach(function (id) { return result.addPipe(id); });
  21088. });
  21089. return result;
  21090. };
  21091. CompileMetadataResolver.prototype._getIdentifierMetadata = function (type) {
  21092. type = resolveForwardRef(type);
  21093. return { reference: type };
  21094. };
  21095. CompileMetadataResolver.prototype.isInjectable = function (type) {
  21096. var annotations = this._reflector.tryAnnotations(type);
  21097. return annotations.some(function (ann) { return createInjectable.isTypeOf(ann); });
  21098. };
  21099. CompileMetadataResolver.prototype.getInjectableSummary = function (type) {
  21100. return {
  21101. summaryKind: exports.CompileSummaryKind.Injectable,
  21102. type: this._getTypeMetadata(type, null, false)
  21103. };
  21104. };
  21105. CompileMetadataResolver.prototype.getInjectableMetadata = function (type, dependencies, throwOnUnknownDeps) {
  21106. if (dependencies === void 0) { dependencies = null; }
  21107. if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
  21108. var typeSummary = this._loadSummary(type, exports.CompileSummaryKind.Injectable);
  21109. var typeMetadata = typeSummary ?
  21110. typeSummary.type :
  21111. this._getTypeMetadata(type, dependencies, throwOnUnknownDeps);
  21112. var annotations = this._reflector.annotations(type).filter(function (ann) { return createInjectable.isTypeOf(ann); });
  21113. if (annotations.length === 0) {
  21114. return null;
  21115. }
  21116. var meta = annotations[annotations.length - 1];
  21117. return {
  21118. symbol: type,
  21119. type: typeMetadata,
  21120. providedIn: meta.providedIn,
  21121. useValue: meta.useValue,
  21122. useClass: meta.useClass,
  21123. useExisting: meta.useExisting,
  21124. useFactory: meta.useFactory,
  21125. deps: meta.deps,
  21126. };
  21127. };
  21128. CompileMetadataResolver.prototype._getTypeMetadata = function (type, dependencies, throwOnUnknownDeps) {
  21129. if (dependencies === void 0) { dependencies = null; }
  21130. if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
  21131. var identifier = this._getIdentifierMetadata(type);
  21132. return {
  21133. reference: identifier.reference,
  21134. diDeps: this._getDependenciesMetadata(identifier.reference, dependencies, throwOnUnknownDeps),
  21135. lifecycleHooks: getAllLifecycleHooks(this._reflector, identifier.reference),
  21136. };
  21137. };
  21138. CompileMetadataResolver.prototype._getFactoryMetadata = function (factory, dependencies) {
  21139. if (dependencies === void 0) { dependencies = null; }
  21140. factory = resolveForwardRef(factory);
  21141. return { reference: factory, diDeps: this._getDependenciesMetadata(factory, dependencies) };
  21142. };
  21143. /**
  21144. * Gets the metadata for the given pipe.
  21145. * This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
  21146. */
  21147. CompileMetadataResolver.prototype.getPipeMetadata = function (pipeType) {
  21148. var pipeMeta = this._pipeCache.get(pipeType);
  21149. if (!pipeMeta) {
  21150. this._reportError(syntaxError("Illegal state: getPipeMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Pipe " + stringifyType(pipeType) + "."), pipeType);
  21151. }
  21152. return pipeMeta || null;
  21153. };
  21154. CompileMetadataResolver.prototype.getPipeSummary = function (pipeType) {
  21155. var pipeSummary = this._loadSummary(pipeType, exports.CompileSummaryKind.Pipe);
  21156. if (!pipeSummary) {
  21157. this._reportError(syntaxError("Illegal state: Could not load the summary for pipe " + stringifyType(pipeType) + "."), pipeType);
  21158. }
  21159. return pipeSummary;
  21160. };
  21161. CompileMetadataResolver.prototype.getOrLoadPipeMetadata = function (pipeType) {
  21162. var pipeMeta = this._pipeCache.get(pipeType);
  21163. if (!pipeMeta) {
  21164. pipeMeta = this._loadPipeMetadata(pipeType);
  21165. }
  21166. return pipeMeta;
  21167. };
  21168. CompileMetadataResolver.prototype._loadPipeMetadata = function (pipeType) {
  21169. pipeType = resolveForwardRef(pipeType);
  21170. var pipeAnnotation = this._pipeResolver.resolve(pipeType);
  21171. var pipeMeta = new CompilePipeMetadata({
  21172. type: this._getTypeMetadata(pipeType),
  21173. name: pipeAnnotation.name,
  21174. pure: !!pipeAnnotation.pure
  21175. });
  21176. this._pipeCache.set(pipeType, pipeMeta);
  21177. this._summaryCache.set(pipeType, pipeMeta.toSummary());
  21178. return pipeMeta;
  21179. };
  21180. CompileMetadataResolver.prototype._getDependenciesMetadata = function (typeOrFunc, dependencies, throwOnUnknownDeps) {
  21181. var _this = this;
  21182. if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
  21183. var hasUnknownDeps = false;
  21184. var params = dependencies || this._reflector.parameters(typeOrFunc) || [];
  21185. var dependenciesMetadata = params.map(function (param) {
  21186. var isAttribute = false;
  21187. var isHost = false;
  21188. var isSelf = false;
  21189. var isSkipSelf = false;
  21190. var isOptional = false;
  21191. var token = null;
  21192. if (Array.isArray(param)) {
  21193. param.forEach(function (paramEntry) {
  21194. if (createHost.isTypeOf(paramEntry)) {
  21195. isHost = true;
  21196. }
  21197. else if (createSelf.isTypeOf(paramEntry)) {
  21198. isSelf = true;
  21199. }
  21200. else if (createSkipSelf.isTypeOf(paramEntry)) {
  21201. isSkipSelf = true;
  21202. }
  21203. else if (createOptional.isTypeOf(paramEntry)) {
  21204. isOptional = true;
  21205. }
  21206. else if (createAttribute.isTypeOf(paramEntry)) {
  21207. isAttribute = true;
  21208. token = paramEntry.attributeName;
  21209. }
  21210. else if (createInject.isTypeOf(paramEntry)) {
  21211. token = paramEntry.token;
  21212. }
  21213. else if (createInjectionToken.isTypeOf(paramEntry) ||
  21214. paramEntry instanceof StaticSymbol) {
  21215. token = paramEntry;
  21216. }
  21217. else if (isValidType(paramEntry) && token == null) {
  21218. token = paramEntry;
  21219. }
  21220. });
  21221. }
  21222. else {
  21223. token = param;
  21224. }
  21225. if (token == null) {
  21226. hasUnknownDeps = true;
  21227. return {};
  21228. }
  21229. return {
  21230. isAttribute: isAttribute,
  21231. isHost: isHost,
  21232. isSelf: isSelf,
  21233. isSkipSelf: isSkipSelf,
  21234. isOptional: isOptional,
  21235. token: _this._getTokenMetadata(token)
  21236. };
  21237. });
  21238. if (hasUnknownDeps) {
  21239. var depsTokens = dependenciesMetadata.map(function (dep) { return dep.token ? stringifyType(dep.token) : '?'; }).join(', ');
  21240. var message = "Can't resolve all parameters for " + stringifyType(typeOrFunc) + ": (" + depsTokens + ").";
  21241. if (throwOnUnknownDeps || this._config.strictInjectionParameters) {
  21242. this._reportError(syntaxError(message), typeOrFunc);
  21243. }
  21244. else {
  21245. this._console.warn("Warning: " + message + " This will become an error in Angular v6.x");
  21246. }
  21247. }
  21248. return dependenciesMetadata;
  21249. };
  21250. CompileMetadataResolver.prototype._getTokenMetadata = function (token) {
  21251. token = resolveForwardRef(token);
  21252. var compileToken;
  21253. if (typeof token === 'string') {
  21254. compileToken = { value: token };
  21255. }
  21256. else {
  21257. compileToken = { identifier: { reference: token } };
  21258. }
  21259. return compileToken;
  21260. };
  21261. CompileMetadataResolver.prototype._getProvidersMetadata = function (providers, targetEntryComponents, debugInfo, compileProviders, type) {
  21262. var _this = this;
  21263. if (compileProviders === void 0) { compileProviders = []; }
  21264. providers.forEach(function (provider, providerIdx) {
  21265. if (Array.isArray(provider)) {
  21266. _this._getProvidersMetadata(provider, targetEntryComponents, debugInfo, compileProviders);
  21267. }
  21268. else {
  21269. provider = resolveForwardRef(provider);
  21270. var providerMeta = undefined;
  21271. if (provider && typeof provider === 'object' && provider.hasOwnProperty('provide')) {
  21272. _this._validateProvider(provider);
  21273. providerMeta = new ProviderMeta(provider.provide, provider);
  21274. }
  21275. else if (isValidType(provider)) {
  21276. providerMeta = new ProviderMeta(provider, { useClass: provider });
  21277. }
  21278. else if (provider === void 0) {
  21279. _this._reportError(syntaxError("Encountered undefined provider! Usually this means you have a circular dependencies. This might be caused by using 'barrel' index.ts files."));
  21280. return;
  21281. }
  21282. else {
  21283. var providersInfo = providers.reduce(function (soFar, seenProvider, seenProviderIdx) {
  21284. if (seenProviderIdx < providerIdx) {
  21285. soFar.push("" + stringifyType(seenProvider));
  21286. }
  21287. else if (seenProviderIdx == providerIdx) {
  21288. soFar.push("?" + stringifyType(seenProvider) + "?");
  21289. }
  21290. else if (seenProviderIdx == providerIdx + 1) {
  21291. soFar.push('...');
  21292. }
  21293. return soFar;
  21294. }, [])
  21295. .join(', ');
  21296. _this._reportError(syntaxError("Invalid " + (debugInfo ? debugInfo : 'provider') + " - only instances of Provider and Type are allowed, got: [" + providersInfo + "]"), type);
  21297. return;
  21298. }
  21299. if (providerMeta.token ===
  21300. _this._reflector.resolveExternalReference(Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS)) {
  21301. targetEntryComponents.push.apply(targetEntryComponents, __spread(_this._getEntryComponentsFromProvider(providerMeta, type)));
  21302. }
  21303. else {
  21304. compileProviders.push(_this.getProviderMetadata(providerMeta));
  21305. }
  21306. }
  21307. });
  21308. return compileProviders;
  21309. };
  21310. CompileMetadataResolver.prototype._validateProvider = function (provider) {
  21311. if (provider.hasOwnProperty('useClass') && provider.useClass == null) {
  21312. 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."));
  21313. }
  21314. };
  21315. CompileMetadataResolver.prototype._getEntryComponentsFromProvider = function (provider, type) {
  21316. var _this = this;
  21317. var components = [];
  21318. var collectedIdentifiers = [];
  21319. if (provider.useFactory || provider.useExisting || provider.useClass) {
  21320. this._reportError(syntaxError("The ANALYZE_FOR_ENTRY_COMPONENTS token only supports useValue!"), type);
  21321. return [];
  21322. }
  21323. if (!provider.multi) {
  21324. this._reportError(syntaxError("The ANALYZE_FOR_ENTRY_COMPONENTS token only supports 'multi = true'!"), type);
  21325. return [];
  21326. }
  21327. extractIdentifiers(provider.useValue, collectedIdentifiers);
  21328. collectedIdentifiers.forEach(function (identifier) {
  21329. var entry = _this._getEntryComponentMetadata(identifier.reference, false);
  21330. if (entry) {
  21331. components.push(entry);
  21332. }
  21333. });
  21334. return components;
  21335. };
  21336. CompileMetadataResolver.prototype._getEntryComponentMetadata = function (dirType, throwIfNotFound) {
  21337. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  21338. var dirMeta = this.getNonNormalizedDirectiveMetadata(dirType);
  21339. if (dirMeta && dirMeta.metadata.isComponent) {
  21340. return { componentType: dirType, componentFactory: dirMeta.metadata.componentFactory };
  21341. }
  21342. var dirSummary = this._loadSummary(dirType, exports.CompileSummaryKind.Directive);
  21343. if (dirSummary && dirSummary.isComponent) {
  21344. return { componentType: dirType, componentFactory: dirSummary.componentFactory };
  21345. }
  21346. if (throwIfNotFound) {
  21347. throw syntaxError(dirType.name + " cannot be used as an entry component.");
  21348. }
  21349. return null;
  21350. };
  21351. CompileMetadataResolver.prototype._getInjectableTypeMetadata = function (type, dependencies) {
  21352. if (dependencies === void 0) { dependencies = null; }
  21353. var typeSummary = this._loadSummary(type, exports.CompileSummaryKind.Injectable);
  21354. if (typeSummary) {
  21355. return typeSummary.type;
  21356. }
  21357. return this._getTypeMetadata(type, dependencies);
  21358. };
  21359. CompileMetadataResolver.prototype.getProviderMetadata = function (provider) {
  21360. var compileDeps = undefined;
  21361. var compileTypeMetadata = null;
  21362. var compileFactoryMetadata = null;
  21363. var token = this._getTokenMetadata(provider.token);
  21364. if (provider.useClass) {
  21365. compileTypeMetadata =
  21366. this._getInjectableTypeMetadata(provider.useClass, provider.dependencies);
  21367. compileDeps = compileTypeMetadata.diDeps;
  21368. if (provider.token === provider.useClass) {
  21369. // use the compileTypeMetadata as it contains information about lifecycleHooks...
  21370. token = { identifier: compileTypeMetadata };
  21371. }
  21372. }
  21373. else if (provider.useFactory) {
  21374. compileFactoryMetadata = this._getFactoryMetadata(provider.useFactory, provider.dependencies);
  21375. compileDeps = compileFactoryMetadata.diDeps;
  21376. }
  21377. return {
  21378. token: token,
  21379. useClass: compileTypeMetadata,
  21380. useValue: provider.useValue,
  21381. useFactory: compileFactoryMetadata,
  21382. useExisting: provider.useExisting ? this._getTokenMetadata(provider.useExisting) : undefined,
  21383. deps: compileDeps,
  21384. multi: provider.multi
  21385. };
  21386. };
  21387. CompileMetadataResolver.prototype._getQueriesMetadata = function (queries, isViewQuery, directiveType) {
  21388. var _this = this;
  21389. var res = [];
  21390. Object.keys(queries).forEach(function (propertyName) {
  21391. var query = queries[propertyName];
  21392. if (query.isViewQuery === isViewQuery) {
  21393. res.push(_this._getQueryMetadata(query, propertyName, directiveType));
  21394. }
  21395. });
  21396. return res;
  21397. };
  21398. CompileMetadataResolver.prototype._queryVarBindings = function (selector) { return selector.split(/\s*,\s*/); };
  21399. CompileMetadataResolver.prototype._getQueryMetadata = function (q, propertyName, typeOrFunc) {
  21400. var _this = this;
  21401. var selectors;
  21402. if (typeof q.selector === 'string') {
  21403. selectors =
  21404. this._queryVarBindings(q.selector).map(function (varName) { return _this._getTokenMetadata(varName); });
  21405. }
  21406. else {
  21407. if (!q.selector) {
  21408. this._reportError(syntaxError("Can't construct a query for the property \"" + propertyName + "\" of \"" + stringifyType(typeOrFunc) + "\" since the query selector wasn't defined."), typeOrFunc);
  21409. selectors = [];
  21410. }
  21411. else {
  21412. selectors = [this._getTokenMetadata(q.selector)];
  21413. }
  21414. }
  21415. return {
  21416. selectors: selectors,
  21417. first: q.first,
  21418. descendants: q.descendants, propertyName: propertyName,
  21419. read: q.read ? this._getTokenMetadata(q.read) : null,
  21420. static: q.static
  21421. };
  21422. };
  21423. CompileMetadataResolver.prototype._reportError = function (error, type, otherType) {
  21424. if (this._errorCollector) {
  21425. this._errorCollector(error, type);
  21426. if (otherType) {
  21427. this._errorCollector(error, otherType);
  21428. }
  21429. }
  21430. else {
  21431. throw error;
  21432. }
  21433. };
  21434. return CompileMetadataResolver;
  21435. }());
  21436. function flattenArray(tree, out) {
  21437. if (out === void 0) { out = []; }
  21438. if (tree) {
  21439. for (var i = 0; i < tree.length; i++) {
  21440. var item = resolveForwardRef(tree[i]);
  21441. if (Array.isArray(item)) {
  21442. flattenArray(item, out);
  21443. }
  21444. else {
  21445. out.push(item);
  21446. }
  21447. }
  21448. }
  21449. return out;
  21450. }
  21451. function dedupeArray(array) {
  21452. if (array) {
  21453. return Array.from(new Set(array));
  21454. }
  21455. return [];
  21456. }
  21457. function flattenAndDedupeArray(tree) {
  21458. return dedupeArray(flattenArray(tree));
  21459. }
  21460. function isValidType(value) {
  21461. return (value instanceof StaticSymbol) || (value instanceof Type);
  21462. }
  21463. function extractIdentifiers(value, targetIdentifiers) {
  21464. visitValue(value, new _CompileValueConverter(), targetIdentifiers);
  21465. }
  21466. var _CompileValueConverter = /** @class */ (function (_super) {
  21467. __extends(_CompileValueConverter, _super);
  21468. function _CompileValueConverter() {
  21469. return _super !== null && _super.apply(this, arguments) || this;
  21470. }
  21471. _CompileValueConverter.prototype.visitOther = function (value, targetIdentifiers) {
  21472. targetIdentifiers.push({ reference: value });
  21473. };
  21474. return _CompileValueConverter;
  21475. }(ValueTransformer));
  21476. function stringifyType(type) {
  21477. if (type instanceof StaticSymbol) {
  21478. return type.name + " in " + type.filePath;
  21479. }
  21480. else {
  21481. return stringify(type);
  21482. }
  21483. }
  21484. /**
  21485. * Indicates that a component is still being loaded in a synchronous compile.
  21486. */
  21487. function componentStillLoadingError(compType) {
  21488. var error = Error("Can't compile synchronously as " + stringify(compType) + " is still being loaded!");
  21489. error[ERROR_COMPONENT_TYPE] = compType;
  21490. return error;
  21491. }
  21492. /**
  21493. * @license
  21494. * Copyright Google Inc. All Rights Reserved.
  21495. *
  21496. * Use of this source code is governed by an MIT-style license that can be
  21497. * found in the LICENSE file at https://angular.io/license
  21498. */
  21499. function providerDef(ctx, providerAst) {
  21500. var flags = 0 /* None */;
  21501. if (!providerAst.eager) {
  21502. flags |= 4096 /* LazyProvider */;
  21503. }
  21504. if (providerAst.providerType === exports.ProviderAstType.PrivateService) {
  21505. flags |= 8192 /* PrivateProvider */;
  21506. }
  21507. if (providerAst.isModule) {
  21508. flags |= 1073741824 /* TypeModuleProvider */;
  21509. }
  21510. providerAst.lifecycleHooks.forEach(function (lifecycleHook) {
  21511. // for regular providers, we only support ngOnDestroy
  21512. if (lifecycleHook === LifecycleHooks.OnDestroy ||
  21513. providerAst.providerType === exports.ProviderAstType.Directive ||
  21514. providerAst.providerType === exports.ProviderAstType.Component) {
  21515. flags |= lifecycleHookToNodeFlag(lifecycleHook);
  21516. }
  21517. });
  21518. var _a = providerAst.multiProvider ?
  21519. multiProviderDef(ctx, flags, providerAst.providers) :
  21520. singleProviderDef(ctx, flags, providerAst.providerType, providerAst.providers[0]), providerExpr = _a.providerExpr, providerFlags = _a.flags, depsExpr = _a.depsExpr;
  21521. return {
  21522. providerExpr: providerExpr,
  21523. flags: providerFlags, depsExpr: depsExpr,
  21524. tokenExpr: tokenExpr(ctx, providerAst.token),
  21525. };
  21526. }
  21527. function multiProviderDef(ctx, flags, providers) {
  21528. var allDepDefs = [];
  21529. var allParams = [];
  21530. var exprs = providers.map(function (provider, providerIndex) {
  21531. var expr;
  21532. if (provider.useClass) {
  21533. var depExprs = convertDeps(providerIndex, provider.deps || provider.useClass.diDeps);
  21534. expr = ctx.importExpr(provider.useClass.reference).instantiate(depExprs);
  21535. }
  21536. else if (provider.useFactory) {
  21537. var depExprs = convertDeps(providerIndex, provider.deps || provider.useFactory.diDeps);
  21538. expr = ctx.importExpr(provider.useFactory.reference).callFn(depExprs);
  21539. }
  21540. else if (provider.useExisting) {
  21541. var depExprs = convertDeps(providerIndex, [{ token: provider.useExisting }]);
  21542. expr = depExprs[0];
  21543. }
  21544. else {
  21545. expr = convertValueToOutputAst(ctx, provider.useValue);
  21546. }
  21547. return expr;
  21548. });
  21549. var providerExpr = fn(allParams, [new ReturnStatement(literalArr(exprs))], INFERRED_TYPE);
  21550. return {
  21551. providerExpr: providerExpr,
  21552. flags: flags | 1024 /* TypeFactoryProvider */,
  21553. depsExpr: literalArr(allDepDefs)
  21554. };
  21555. function convertDeps(providerIndex, deps) {
  21556. return deps.map(function (dep, depIndex) {
  21557. var paramName = "p" + providerIndex + "_" + depIndex;
  21558. allParams.push(new FnParam(paramName, DYNAMIC_TYPE));
  21559. allDepDefs.push(depDef(ctx, dep));
  21560. return variable(paramName);
  21561. });
  21562. }
  21563. }
  21564. function singleProviderDef(ctx, flags, providerType, providerMeta) {
  21565. var providerExpr;
  21566. var deps;
  21567. if (providerType === exports.ProviderAstType.Directive || providerType === exports.ProviderAstType.Component) {
  21568. providerExpr = ctx.importExpr(providerMeta.useClass.reference);
  21569. flags |= 16384 /* TypeDirective */;
  21570. deps = providerMeta.deps || providerMeta.useClass.diDeps;
  21571. }
  21572. else {
  21573. if (providerMeta.useClass) {
  21574. providerExpr = ctx.importExpr(providerMeta.useClass.reference);
  21575. flags |= 512 /* TypeClassProvider */;
  21576. deps = providerMeta.deps || providerMeta.useClass.diDeps;
  21577. }
  21578. else if (providerMeta.useFactory) {
  21579. providerExpr = ctx.importExpr(providerMeta.useFactory.reference);
  21580. flags |= 1024 /* TypeFactoryProvider */;
  21581. deps = providerMeta.deps || providerMeta.useFactory.diDeps;
  21582. }
  21583. else if (providerMeta.useExisting) {
  21584. providerExpr = NULL_EXPR;
  21585. flags |= 2048 /* TypeUseExistingProvider */;
  21586. deps = [{ token: providerMeta.useExisting }];
  21587. }
  21588. else {
  21589. providerExpr = convertValueToOutputAst(ctx, providerMeta.useValue);
  21590. flags |= 256 /* TypeValueProvider */;
  21591. deps = [];
  21592. }
  21593. }
  21594. var depsExpr = literalArr(deps.map(function (dep) { return depDef(ctx, dep); }));
  21595. return { providerExpr: providerExpr, flags: flags, depsExpr: depsExpr };
  21596. }
  21597. function tokenExpr(ctx, tokenMeta) {
  21598. return tokenMeta.identifier ? ctx.importExpr(tokenMeta.identifier.reference) :
  21599. literal(tokenMeta.value);
  21600. }
  21601. function depDef(ctx, dep) {
  21602. // Note: the following fields have already been normalized out by provider_analyzer:
  21603. // - isAttribute, isHost
  21604. var expr = dep.isValue ? convertValueToOutputAst(ctx, dep.value) : tokenExpr(ctx, dep.token);
  21605. var flags = 0 /* None */;
  21606. if (dep.isSkipSelf) {
  21607. flags |= 1 /* SkipSelf */;
  21608. }
  21609. if (dep.isOptional) {
  21610. flags |= 2 /* Optional */;
  21611. }
  21612. if (dep.isSelf) {
  21613. flags |= 4 /* Self */;
  21614. }
  21615. if (dep.isValue) {
  21616. flags |= 8 /* Value */;
  21617. }
  21618. return flags === 0 /* None */ ? expr : literalArr([literal(flags), expr]);
  21619. }
  21620. function lifecycleHookToNodeFlag(lifecycleHook) {
  21621. var nodeFlag = 0 /* None */;
  21622. switch (lifecycleHook) {
  21623. case LifecycleHooks.AfterContentChecked:
  21624. nodeFlag = 2097152 /* AfterContentChecked */;
  21625. break;
  21626. case LifecycleHooks.AfterContentInit:
  21627. nodeFlag = 1048576 /* AfterContentInit */;
  21628. break;
  21629. case LifecycleHooks.AfterViewChecked:
  21630. nodeFlag = 8388608 /* AfterViewChecked */;
  21631. break;
  21632. case LifecycleHooks.AfterViewInit:
  21633. nodeFlag = 4194304 /* AfterViewInit */;
  21634. break;
  21635. case LifecycleHooks.DoCheck:
  21636. nodeFlag = 262144 /* DoCheck */;
  21637. break;
  21638. case LifecycleHooks.OnChanges:
  21639. nodeFlag = 524288 /* OnChanges */;
  21640. break;
  21641. case LifecycleHooks.OnDestroy:
  21642. nodeFlag = 131072 /* OnDestroy */;
  21643. break;
  21644. case LifecycleHooks.OnInit:
  21645. nodeFlag = 65536 /* OnInit */;
  21646. break;
  21647. }
  21648. return nodeFlag;
  21649. }
  21650. function componentFactoryResolverProviderDef(reflector, ctx, flags, entryComponents) {
  21651. var entryComponentFactories = entryComponents.map(function (entryComponent) { return ctx.importExpr(entryComponent.componentFactory); });
  21652. var token = createTokenForExternalReference(reflector, Identifiers.ComponentFactoryResolver);
  21653. var classMeta = {
  21654. diDeps: [
  21655. { isValue: true, value: literalArr(entryComponentFactories) },
  21656. { token: token, isSkipSelf: true, isOptional: true },
  21657. { token: createTokenForExternalReference(reflector, Identifiers.NgModuleRef) },
  21658. ],
  21659. lifecycleHooks: [],
  21660. reference: reflector.resolveExternalReference(Identifiers.CodegenComponentFactoryResolver)
  21661. };
  21662. var _a = singleProviderDef(ctx, flags, exports.ProviderAstType.PrivateService, {
  21663. token: token,
  21664. multi: false,
  21665. useClass: classMeta,
  21666. }), providerExpr = _a.providerExpr, providerFlags = _a.flags, depsExpr = _a.depsExpr;
  21667. return { providerExpr: providerExpr, flags: providerFlags, depsExpr: depsExpr, tokenExpr: tokenExpr(ctx, token) };
  21668. }
  21669. /**
  21670. * @license
  21671. * Copyright Google Inc. All Rights Reserved.
  21672. *
  21673. * Use of this source code is governed by an MIT-style license that can be
  21674. * found in the LICENSE file at https://angular.io/license
  21675. */
  21676. var NgModuleCompileResult = /** @class */ (function () {
  21677. function NgModuleCompileResult(ngModuleFactoryVar) {
  21678. this.ngModuleFactoryVar = ngModuleFactoryVar;
  21679. }
  21680. return NgModuleCompileResult;
  21681. }());
  21682. var LOG_VAR = variable('_l');
  21683. var NgModuleCompiler = /** @class */ (function () {
  21684. function NgModuleCompiler(reflector) {
  21685. this.reflector = reflector;
  21686. }
  21687. NgModuleCompiler.prototype.compile = function (ctx, ngModuleMeta, extraProviders) {
  21688. var sourceSpan = typeSourceSpan('NgModule', ngModuleMeta.type);
  21689. var entryComponentFactories = ngModuleMeta.transitiveModule.entryComponents;
  21690. var bootstrapComponents = ngModuleMeta.bootstrapComponents;
  21691. var providerParser = new NgModuleProviderAnalyzer(this.reflector, ngModuleMeta, extraProviders, sourceSpan);
  21692. var providerDefs = [componentFactoryResolverProviderDef(this.reflector, ctx, 0 /* None */, entryComponentFactories)]
  21693. .concat(providerParser.parse().map(function (provider) { return providerDef(ctx, provider); }))
  21694. .map(function (_a) {
  21695. var providerExpr = _a.providerExpr, depsExpr = _a.depsExpr, flags = _a.flags, tokenExpr = _a.tokenExpr;
  21696. return importExpr(Identifiers.moduleProviderDef).callFn([
  21697. literal(flags), tokenExpr, providerExpr, depsExpr
  21698. ]);
  21699. });
  21700. var ngModuleDef = importExpr(Identifiers.moduleDef).callFn([literalArr(providerDefs)]);
  21701. var ngModuleDefFactory = fn([new FnParam(LOG_VAR.name)], [new ReturnStatement(ngModuleDef)], INFERRED_TYPE);
  21702. var ngModuleFactoryVar = identifierName(ngModuleMeta.type) + "NgFactory";
  21703. this._createNgModuleFactory(ctx, ngModuleMeta.type.reference, importExpr(Identifiers.createModuleFactory).callFn([
  21704. ctx.importExpr(ngModuleMeta.type.reference),
  21705. literalArr(bootstrapComponents.map(function (id) { return ctx.importExpr(id.reference); })),
  21706. ngModuleDefFactory
  21707. ]));
  21708. if (ngModuleMeta.id) {
  21709. var id = typeof ngModuleMeta.id === 'string' ? literal(ngModuleMeta.id) :
  21710. ctx.importExpr(ngModuleMeta.id);
  21711. var registerFactoryStmt = importExpr(Identifiers.RegisterModuleFactoryFn)
  21712. .callFn([id, variable(ngModuleFactoryVar)])
  21713. .toStmt();
  21714. ctx.statements.push(registerFactoryStmt);
  21715. }
  21716. return new NgModuleCompileResult(ngModuleFactoryVar);
  21717. };
  21718. NgModuleCompiler.prototype.createStub = function (ctx, ngModuleReference) {
  21719. this._createNgModuleFactory(ctx, ngModuleReference, NULL_EXPR);
  21720. };
  21721. NgModuleCompiler.prototype._createNgModuleFactory = function (ctx, reference, value) {
  21722. var ngModuleFactoryVar = identifierName({ reference: reference }) + "NgFactory";
  21723. var ngModuleFactoryStmt = variable(ngModuleFactoryVar)
  21724. .set(value)
  21725. .toDeclStmt(importType(Identifiers.NgModuleFactory, [expressionType(ctx.importExpr(reference))], [TypeModifier.Const]), [exports.StmtModifier.Final, exports.StmtModifier.Exported]);
  21726. ctx.statements.push(ngModuleFactoryStmt);
  21727. };
  21728. return NgModuleCompiler;
  21729. }());
  21730. /**
  21731. * @license
  21732. * Copyright Google Inc. All Rights Reserved.
  21733. *
  21734. * Use of this source code is governed by an MIT-style license that can be
  21735. * found in the LICENSE file at https://angular.io/license
  21736. */
  21737. /**
  21738. * Resolves types to {@link NgModule}.
  21739. */
  21740. var NgModuleResolver = /** @class */ (function () {
  21741. function NgModuleResolver(_reflector) {
  21742. this._reflector = _reflector;
  21743. }
  21744. NgModuleResolver.prototype.isNgModule = function (type) { return this._reflector.annotations(type).some(createNgModule.isTypeOf); };
  21745. NgModuleResolver.prototype.resolve = function (type, throwIfNotFound) {
  21746. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  21747. var ngModuleMeta = findLast(this._reflector.annotations(type), createNgModule.isTypeOf);
  21748. if (ngModuleMeta) {
  21749. return ngModuleMeta;
  21750. }
  21751. else {
  21752. if (throwIfNotFound) {
  21753. throw new Error("No NgModule metadata found for '" + stringify(type) + "'.");
  21754. }
  21755. return null;
  21756. }
  21757. };
  21758. return NgModuleResolver;
  21759. }());
  21760. /**
  21761. * @license
  21762. * Copyright Google Inc. All Rights Reserved.
  21763. *
  21764. * Use of this source code is governed by an MIT-style license that can be
  21765. * found in the LICENSE file at https://angular.io/license
  21766. */
  21767. function debugOutputAstAsTypeScript(ast) {
  21768. var converter = new _TsEmitterVisitor();
  21769. var ctx = EmitterVisitorContext.createRoot();
  21770. var asts = Array.isArray(ast) ? ast : [ast];
  21771. asts.forEach(function (ast) {
  21772. if (ast instanceof Statement) {
  21773. ast.visitStatement(converter, ctx);
  21774. }
  21775. else if (ast instanceof Expression) {
  21776. ast.visitExpression(converter, ctx);
  21777. }
  21778. else if (ast instanceof Type$1) {
  21779. ast.visitType(converter, ctx);
  21780. }
  21781. else {
  21782. throw new Error("Don't know how to print debug info for " + ast);
  21783. }
  21784. });
  21785. return ctx.toSource();
  21786. }
  21787. var TypeScriptEmitter = /** @class */ (function () {
  21788. function TypeScriptEmitter() {
  21789. }
  21790. TypeScriptEmitter.prototype.emitStatementsAndContext = function (genFilePath, stmts, preamble, emitSourceMaps, referenceFilter, importFilter) {
  21791. if (preamble === void 0) { preamble = ''; }
  21792. if (emitSourceMaps === void 0) { emitSourceMaps = true; }
  21793. var converter = new _TsEmitterVisitor(referenceFilter, importFilter);
  21794. var ctx = EmitterVisitorContext.createRoot();
  21795. converter.visitAllStatements(stmts, ctx);
  21796. var preambleLines = preamble ? preamble.split('\n') : [];
  21797. converter.reexports.forEach(function (reexports, exportedModuleName) {
  21798. var reexportsCode = reexports.map(function (reexport) { return reexport.name + " as " + reexport.as; }).join(',');
  21799. preambleLines.push("export {" + reexportsCode + "} from '" + exportedModuleName + "';");
  21800. });
  21801. converter.importsWithPrefixes.forEach(function (prefix, importedModuleName) {
  21802. // Note: can't write the real word for import as it screws up system.js auto detection...
  21803. preambleLines.push("imp" +
  21804. ("ort * as " + prefix + " from '" + importedModuleName + "';"));
  21805. });
  21806. var sm = emitSourceMaps ?
  21807. ctx.toSourceMapGenerator(genFilePath, preambleLines.length).toJsComment() :
  21808. '';
  21809. var lines = __spread(preambleLines, [ctx.toSource(), sm]);
  21810. if (sm) {
  21811. // always add a newline at the end, as some tools have bugs without it.
  21812. lines.push('');
  21813. }
  21814. ctx.setPreambleLineCount(preambleLines.length);
  21815. return { sourceText: lines.join('\n'), context: ctx };
  21816. };
  21817. TypeScriptEmitter.prototype.emitStatements = function (genFilePath, stmts, preamble) {
  21818. if (preamble === void 0) { preamble = ''; }
  21819. return this.emitStatementsAndContext(genFilePath, stmts, preamble).sourceText;
  21820. };
  21821. return TypeScriptEmitter;
  21822. }());
  21823. var _TsEmitterVisitor = /** @class */ (function (_super) {
  21824. __extends(_TsEmitterVisitor, _super);
  21825. function _TsEmitterVisitor(referenceFilter, importFilter) {
  21826. var _this = _super.call(this, false) || this;
  21827. _this.referenceFilter = referenceFilter;
  21828. _this.importFilter = importFilter;
  21829. _this.typeExpression = 0;
  21830. _this.importsWithPrefixes = new Map();
  21831. _this.reexports = new Map();
  21832. return _this;
  21833. }
  21834. _TsEmitterVisitor.prototype.visitType = function (t, ctx, defaultType) {
  21835. if (defaultType === void 0) { defaultType = 'any'; }
  21836. if (t) {
  21837. this.typeExpression++;
  21838. t.visitType(this, ctx);
  21839. this.typeExpression--;
  21840. }
  21841. else {
  21842. ctx.print(null, defaultType);
  21843. }
  21844. };
  21845. _TsEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) {
  21846. var value = ast.value;
  21847. if (value == null && ast.type != INFERRED_TYPE) {
  21848. ctx.print(ast, "(" + value + " as any)");
  21849. return null;
  21850. }
  21851. return _super.prototype.visitLiteralExpr.call(this, ast, ctx);
  21852. };
  21853. // Temporary workaround to support strictNullCheck enabled consumers of ngc emit.
  21854. // In SNC mode, [] have the type never[], so we cast here to any[].
  21855. // TODO: narrow the cast to a more explicit type, or use a pattern that does not
  21856. // start with [].concat. see https://github.com/angular/angular/pull/11846
  21857. _TsEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) {
  21858. if (ast.entries.length === 0) {
  21859. ctx.print(ast, '(');
  21860. }
  21861. var result = _super.prototype.visitLiteralArrayExpr.call(this, ast, ctx);
  21862. if (ast.entries.length === 0) {
  21863. ctx.print(ast, ' as any[])');
  21864. }
  21865. return result;
  21866. };
  21867. _TsEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) {
  21868. this._visitIdentifier(ast.value, ast.typeParams, ctx);
  21869. return null;
  21870. };
  21871. _TsEmitterVisitor.prototype.visitAssertNotNullExpr = function (ast, ctx) {
  21872. var result = _super.prototype.visitAssertNotNullExpr.call(this, ast, ctx);
  21873. ctx.print(ast, '!');
  21874. return result;
  21875. };
  21876. _TsEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
  21877. if (stmt.hasModifier(exports.StmtModifier.Exported) && stmt.value instanceof ExternalExpr &&
  21878. !stmt.type) {
  21879. // check for a reexport
  21880. var _a = stmt.value.value, name_1 = _a.name, moduleName = _a.moduleName;
  21881. if (moduleName) {
  21882. var reexports = this.reexports.get(moduleName);
  21883. if (!reexports) {
  21884. reexports = [];
  21885. this.reexports.set(moduleName, reexports);
  21886. }
  21887. reexports.push({ name: name_1, as: stmt.name });
  21888. return null;
  21889. }
  21890. }
  21891. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  21892. ctx.print(stmt, "export ");
  21893. }
  21894. if (stmt.hasModifier(exports.StmtModifier.Final)) {
  21895. ctx.print(stmt, "const");
  21896. }
  21897. else {
  21898. ctx.print(stmt, "var");
  21899. }
  21900. ctx.print(stmt, " " + stmt.name);
  21901. this._printColonType(stmt.type, ctx);
  21902. if (stmt.value) {
  21903. ctx.print(stmt, " = ");
  21904. stmt.value.visitExpression(this, ctx);
  21905. }
  21906. ctx.println(stmt, ";");
  21907. return null;
  21908. };
  21909. _TsEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  21910. throw new Error('Cannot visit a WrappedNodeExpr when outputting Typescript.');
  21911. };
  21912. _TsEmitterVisitor.prototype.visitCastExpr = function (ast, ctx) {
  21913. ctx.print(ast, "(<");
  21914. ast.type.visitType(this, ctx);
  21915. ctx.print(ast, ">");
  21916. ast.value.visitExpression(this, ctx);
  21917. ctx.print(ast, ")");
  21918. return null;
  21919. };
  21920. _TsEmitterVisitor.prototype.visitInstantiateExpr = function (ast, ctx) {
  21921. ctx.print(ast, "new ");
  21922. this.typeExpression++;
  21923. ast.classExpr.visitExpression(this, ctx);
  21924. this.typeExpression--;
  21925. ctx.print(ast, "(");
  21926. this.visitAllExpressions(ast.args, ctx, ',');
  21927. ctx.print(ast, ")");
  21928. return null;
  21929. };
  21930. _TsEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
  21931. var _this = this;
  21932. ctx.pushClass(stmt);
  21933. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  21934. ctx.print(stmt, "export ");
  21935. }
  21936. ctx.print(stmt, "class " + stmt.name);
  21937. if (stmt.parent != null) {
  21938. ctx.print(stmt, " extends ");
  21939. this.typeExpression++;
  21940. stmt.parent.visitExpression(this, ctx);
  21941. this.typeExpression--;
  21942. }
  21943. ctx.println(stmt, " {");
  21944. ctx.incIndent();
  21945. stmt.fields.forEach(function (field) { return _this._visitClassField(field, ctx); });
  21946. if (stmt.constructorMethod != null) {
  21947. this._visitClassConstructor(stmt, ctx);
  21948. }
  21949. stmt.getters.forEach(function (getter) { return _this._visitClassGetter(getter, ctx); });
  21950. stmt.methods.forEach(function (method) { return _this._visitClassMethod(method, ctx); });
  21951. ctx.decIndent();
  21952. ctx.println(stmt, "}");
  21953. ctx.popClass();
  21954. return null;
  21955. };
  21956. _TsEmitterVisitor.prototype._visitClassField = function (field, ctx) {
  21957. if (field.hasModifier(exports.StmtModifier.Private)) {
  21958. // comment out as a workaround for #10967
  21959. ctx.print(null, "/*private*/ ");
  21960. }
  21961. if (field.hasModifier(exports.StmtModifier.Static)) {
  21962. ctx.print(null, 'static ');
  21963. }
  21964. ctx.print(null, field.name);
  21965. this._printColonType(field.type, ctx);
  21966. if (field.initializer) {
  21967. ctx.print(null, ' = ');
  21968. field.initializer.visitExpression(this, ctx);
  21969. }
  21970. ctx.println(null, ";");
  21971. };
  21972. _TsEmitterVisitor.prototype._visitClassGetter = function (getter, ctx) {
  21973. if (getter.hasModifier(exports.StmtModifier.Private)) {
  21974. ctx.print(null, "private ");
  21975. }
  21976. ctx.print(null, "get " + getter.name + "()");
  21977. this._printColonType(getter.type, ctx);
  21978. ctx.println(null, " {");
  21979. ctx.incIndent();
  21980. this.visitAllStatements(getter.body, ctx);
  21981. ctx.decIndent();
  21982. ctx.println(null, "}");
  21983. };
  21984. _TsEmitterVisitor.prototype._visitClassConstructor = function (stmt, ctx) {
  21985. ctx.print(stmt, "constructor(");
  21986. this._visitParams(stmt.constructorMethod.params, ctx);
  21987. ctx.println(stmt, ") {");
  21988. ctx.incIndent();
  21989. this.visitAllStatements(stmt.constructorMethod.body, ctx);
  21990. ctx.decIndent();
  21991. ctx.println(stmt, "}");
  21992. };
  21993. _TsEmitterVisitor.prototype._visitClassMethod = function (method, ctx) {
  21994. if (method.hasModifier(exports.StmtModifier.Private)) {
  21995. ctx.print(null, "private ");
  21996. }
  21997. ctx.print(null, method.name + "(");
  21998. this._visitParams(method.params, ctx);
  21999. ctx.print(null, ")");
  22000. this._printColonType(method.type, ctx, 'void');
  22001. ctx.println(null, " {");
  22002. ctx.incIndent();
  22003. this.visitAllStatements(method.body, ctx);
  22004. ctx.decIndent();
  22005. ctx.println(null, "}");
  22006. };
  22007. _TsEmitterVisitor.prototype.visitFunctionExpr = function (ast, ctx) {
  22008. if (ast.name) {
  22009. ctx.print(ast, 'function ');
  22010. ctx.print(ast, ast.name);
  22011. }
  22012. ctx.print(ast, "(");
  22013. this._visitParams(ast.params, ctx);
  22014. ctx.print(ast, ")");
  22015. this._printColonType(ast.type, ctx, 'void');
  22016. if (!ast.name) {
  22017. ctx.print(ast, " => ");
  22018. }
  22019. ctx.println(ast, '{');
  22020. ctx.incIndent();
  22021. this.visitAllStatements(ast.statements, ctx);
  22022. ctx.decIndent();
  22023. ctx.print(ast, "}");
  22024. return null;
  22025. };
  22026. _TsEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
  22027. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  22028. ctx.print(stmt, "export ");
  22029. }
  22030. ctx.print(stmt, "function " + stmt.name + "(");
  22031. this._visitParams(stmt.params, ctx);
  22032. ctx.print(stmt, ")");
  22033. this._printColonType(stmt.type, ctx, 'void');
  22034. ctx.println(stmt, " {");
  22035. ctx.incIndent();
  22036. this.visitAllStatements(stmt.statements, ctx);
  22037. ctx.decIndent();
  22038. ctx.println(stmt, "}");
  22039. return null;
  22040. };
  22041. _TsEmitterVisitor.prototype.visitTryCatchStmt = function (stmt, ctx) {
  22042. ctx.println(stmt, "try {");
  22043. ctx.incIndent();
  22044. this.visitAllStatements(stmt.bodyStmts, ctx);
  22045. ctx.decIndent();
  22046. ctx.println(stmt, "} catch (" + CATCH_ERROR_VAR$1.name + ") {");
  22047. ctx.incIndent();
  22048. var catchStmts = [CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack', null)).toDeclStmt(null, [
  22049. exports.StmtModifier.Final
  22050. ])].concat(stmt.catchStmts);
  22051. this.visitAllStatements(catchStmts, ctx);
  22052. ctx.decIndent();
  22053. ctx.println(stmt, "}");
  22054. return null;
  22055. };
  22056. _TsEmitterVisitor.prototype.visitBuiltinType = function (type, ctx) {
  22057. var typeStr;
  22058. switch (type.name) {
  22059. case exports.BuiltinTypeName.Bool:
  22060. typeStr = 'boolean';
  22061. break;
  22062. case exports.BuiltinTypeName.Dynamic:
  22063. typeStr = 'any';
  22064. break;
  22065. case exports.BuiltinTypeName.Function:
  22066. typeStr = 'Function';
  22067. break;
  22068. case exports.BuiltinTypeName.Number:
  22069. typeStr = 'number';
  22070. break;
  22071. case exports.BuiltinTypeName.Int:
  22072. typeStr = 'number';
  22073. break;
  22074. case exports.BuiltinTypeName.String:
  22075. typeStr = 'string';
  22076. break;
  22077. case exports.BuiltinTypeName.None:
  22078. typeStr = 'never';
  22079. break;
  22080. default:
  22081. throw new Error("Unsupported builtin type " + type.name);
  22082. }
  22083. ctx.print(null, typeStr);
  22084. return null;
  22085. };
  22086. _TsEmitterVisitor.prototype.visitExpressionType = function (ast, ctx) {
  22087. var _this = this;
  22088. ast.value.visitExpression(this, ctx);
  22089. if (ast.typeParams !== null) {
  22090. ctx.print(null, '<');
  22091. this.visitAllObjects(function (type) { return _this.visitType(type, ctx); }, ast.typeParams, ctx, ',');
  22092. ctx.print(null, '>');
  22093. }
  22094. return null;
  22095. };
  22096. _TsEmitterVisitor.prototype.visitArrayType = function (type, ctx) {
  22097. this.visitType(type.of, ctx);
  22098. ctx.print(null, "[]");
  22099. return null;
  22100. };
  22101. _TsEmitterVisitor.prototype.visitMapType = function (type, ctx) {
  22102. ctx.print(null, "{[key: string]:");
  22103. this.visitType(type.valueType, ctx);
  22104. ctx.print(null, "}");
  22105. return null;
  22106. };
  22107. _TsEmitterVisitor.prototype.getBuiltinMethodName = function (method) {
  22108. var name;
  22109. switch (method) {
  22110. case exports.BuiltinMethod.ConcatArray:
  22111. name = 'concat';
  22112. break;
  22113. case exports.BuiltinMethod.SubscribeObservable:
  22114. name = 'subscribe';
  22115. break;
  22116. case exports.BuiltinMethod.Bind:
  22117. name = 'bind';
  22118. break;
  22119. default:
  22120. throw new Error("Unknown builtin method: " + method);
  22121. }
  22122. return name;
  22123. };
  22124. _TsEmitterVisitor.prototype._visitParams = function (params, ctx) {
  22125. var _this = this;
  22126. this.visitAllObjects(function (param) {
  22127. ctx.print(null, param.name);
  22128. _this._printColonType(param.type, ctx);
  22129. }, params, ctx, ',');
  22130. };
  22131. _TsEmitterVisitor.prototype._visitIdentifier = function (value, typeParams, ctx) {
  22132. var _this = this;
  22133. var name = value.name, moduleName = value.moduleName;
  22134. if (this.referenceFilter && this.referenceFilter(value)) {
  22135. ctx.print(null, '(null as any)');
  22136. return;
  22137. }
  22138. if (moduleName && (!this.importFilter || !this.importFilter(value))) {
  22139. var prefix = this.importsWithPrefixes.get(moduleName);
  22140. if (prefix == null) {
  22141. prefix = "i" + this.importsWithPrefixes.size;
  22142. this.importsWithPrefixes.set(moduleName, prefix);
  22143. }
  22144. ctx.print(null, prefix + ".");
  22145. }
  22146. ctx.print(null, name);
  22147. if (this.typeExpression > 0) {
  22148. // If we are in a type expression that refers to a generic type then supply
  22149. // the required type parameters. If there were not enough type parameters
  22150. // supplied, supply any as the type. Outside a type expression the reference
  22151. // should not supply type parameters and be treated as a simple value reference
  22152. // to the constructor function itself.
  22153. var suppliedParameters = typeParams || [];
  22154. if (suppliedParameters.length > 0) {
  22155. ctx.print(null, "<");
  22156. this.visitAllObjects(function (type) { return type.visitType(_this, ctx); }, typeParams, ctx, ',');
  22157. ctx.print(null, ">");
  22158. }
  22159. }
  22160. };
  22161. _TsEmitterVisitor.prototype._printColonType = function (type, ctx, defaultType) {
  22162. if (type !== INFERRED_TYPE) {
  22163. ctx.print(null, ':');
  22164. this.visitType(type, ctx, defaultType);
  22165. }
  22166. };
  22167. return _TsEmitterVisitor;
  22168. }(AbstractEmitterVisitor));
  22169. /**
  22170. * @license
  22171. * Copyright Google Inc. All Rights Reserved.
  22172. *
  22173. * Use of this source code is governed by an MIT-style license that can be
  22174. * found in the LICENSE file at https://angular.io/license
  22175. */
  22176. /**
  22177. * Resolve a `Type` for {@link Pipe}.
  22178. *
  22179. * This interface can be overridden by the application developer to create custom behavior.
  22180. *
  22181. * See {@link Compiler}
  22182. */
  22183. var PipeResolver = /** @class */ (function () {
  22184. function PipeResolver(_reflector) {
  22185. this._reflector = _reflector;
  22186. }
  22187. PipeResolver.prototype.isPipe = function (type) {
  22188. var typeMetadata = this._reflector.annotations(resolveForwardRef(type));
  22189. return typeMetadata && typeMetadata.some(createPipe.isTypeOf);
  22190. };
  22191. /**
  22192. * Return {@link Pipe} for a given `Type`.
  22193. */
  22194. PipeResolver.prototype.resolve = function (type, throwIfNotFound) {
  22195. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  22196. var metas = this._reflector.annotations(resolveForwardRef(type));
  22197. if (metas) {
  22198. var annotation = findLast(metas, createPipe.isTypeOf);
  22199. if (annotation) {
  22200. return annotation;
  22201. }
  22202. }
  22203. if (throwIfNotFound) {
  22204. throw new Error("No Pipe decorator found on " + stringify(type));
  22205. }
  22206. return null;
  22207. };
  22208. return PipeResolver;
  22209. }());
  22210. /**
  22211. * @license
  22212. * Copyright Google Inc. All Rights Reserved.
  22213. *
  22214. * Use of this source code is governed by an MIT-style license that can be
  22215. * found in the LICENSE file at https://angular.io/license
  22216. */
  22217. /**
  22218. * Generates code that is used to type check templates.
  22219. */
  22220. var TypeCheckCompiler = /** @class */ (function () {
  22221. function TypeCheckCompiler(options, reflector) {
  22222. this.options = options;
  22223. this.reflector = reflector;
  22224. }
  22225. /**
  22226. * Important notes:
  22227. * - This must not produce new `import` statements, but only refer to types outside
  22228. * of the file via the variables provided via externalReferenceVars.
  22229. * This allows Typescript to reuse the old program's structure as no imports have changed.
  22230. * - This must not produce any exports, as this would pollute the .d.ts file
  22231. * and also violate the point above.
  22232. */
  22233. TypeCheckCompiler.prototype.compileComponent = function (componentId, component, template, usedPipes, externalReferenceVars, ctx) {
  22234. var _this = this;
  22235. var pipes = new Map();
  22236. usedPipes.forEach(function (p) { return pipes.set(p.name, p.type.reference); });
  22237. var embeddedViewCount = 0;
  22238. var viewBuilderFactory = function (parent, guards) {
  22239. var embeddedViewIndex = embeddedViewCount++;
  22240. return new ViewBuilder(_this.options, _this.reflector, externalReferenceVars, parent, component.type.reference, component.isHost, embeddedViewIndex, pipes, guards, ctx, viewBuilderFactory);
  22241. };
  22242. var visitor = viewBuilderFactory(null, []);
  22243. visitor.visitAll([], template);
  22244. return visitor.build(componentId);
  22245. };
  22246. return TypeCheckCompiler;
  22247. }());
  22248. var DYNAMIC_VAR_NAME = '_any';
  22249. var TypeCheckLocalResolver = /** @class */ (function () {
  22250. function TypeCheckLocalResolver() {
  22251. }
  22252. TypeCheckLocalResolver.prototype.notifyImplicitReceiverUse = function () { };
  22253. TypeCheckLocalResolver.prototype.getLocal = function (name) {
  22254. if (name === EventHandlerVars.event.name) {
  22255. // References to the event should not be type-checked.
  22256. // TODO(chuckj): determine a better type for the event.
  22257. return variable(DYNAMIC_VAR_NAME);
  22258. }
  22259. return null;
  22260. };
  22261. return TypeCheckLocalResolver;
  22262. }());
  22263. var defaultResolver = new TypeCheckLocalResolver();
  22264. var ViewBuilder = /** @class */ (function () {
  22265. function ViewBuilder(options, reflector, externalReferenceVars, parent, component, isHostComponent, embeddedViewIndex, pipes, guards, ctx, viewBuilderFactory) {
  22266. this.options = options;
  22267. this.reflector = reflector;
  22268. this.externalReferenceVars = externalReferenceVars;
  22269. this.parent = parent;
  22270. this.component = component;
  22271. this.isHostComponent = isHostComponent;
  22272. this.embeddedViewIndex = embeddedViewIndex;
  22273. this.pipes = pipes;
  22274. this.guards = guards;
  22275. this.ctx = ctx;
  22276. this.viewBuilderFactory = viewBuilderFactory;
  22277. this.refOutputVars = new Map();
  22278. this.variables = [];
  22279. this.children = [];
  22280. this.updates = [];
  22281. this.actions = [];
  22282. }
  22283. ViewBuilder.prototype.getOutputVar = function (type) {
  22284. var varName;
  22285. if (type === this.component && this.isHostComponent) {
  22286. varName = DYNAMIC_VAR_NAME;
  22287. }
  22288. else if (type instanceof StaticSymbol) {
  22289. varName = this.externalReferenceVars.get(type);
  22290. }
  22291. else {
  22292. varName = DYNAMIC_VAR_NAME;
  22293. }
  22294. if (!varName) {
  22295. throw new Error("Illegal State: referring to a type without a variable " + JSON.stringify(type));
  22296. }
  22297. return varName;
  22298. };
  22299. ViewBuilder.prototype.getTypeGuardExpressions = function (ast) {
  22300. var e_1, _a, e_2, _b;
  22301. var result = __spread(this.guards);
  22302. try {
  22303. for (var _c = __values(ast.directives), _d = _c.next(); !_d.done; _d = _c.next()) {
  22304. var directive = _d.value;
  22305. try {
  22306. for (var _e = __values(directive.inputs), _f = _e.next(); !_f.done; _f = _e.next()) {
  22307. var input = _f.value;
  22308. var guard = directive.directive.guards[input.directiveName];
  22309. if (guard) {
  22310. var useIf = guard === 'UseIf';
  22311. result.push({
  22312. guard: guard,
  22313. useIf: useIf,
  22314. expression: { context: this.component, value: input.value }
  22315. });
  22316. }
  22317. }
  22318. }
  22319. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  22320. finally {
  22321. try {
  22322. if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
  22323. }
  22324. finally { if (e_2) throw e_2.error; }
  22325. }
  22326. }
  22327. }
  22328. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  22329. finally {
  22330. try {
  22331. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  22332. }
  22333. finally { if (e_1) throw e_1.error; }
  22334. }
  22335. return result;
  22336. };
  22337. ViewBuilder.prototype.visitAll = function (variables, astNodes) {
  22338. this.variables = variables;
  22339. templateVisitAll(this, astNodes);
  22340. };
  22341. ViewBuilder.prototype.build = function (componentId, targetStatements) {
  22342. var _this = this;
  22343. var e_3, _a;
  22344. if (targetStatements === void 0) { targetStatements = []; }
  22345. this.children.forEach(function (child) { return child.build(componentId, targetStatements); });
  22346. var viewStmts = [variable(DYNAMIC_VAR_NAME).set(NULL_EXPR).toDeclStmt(DYNAMIC_TYPE)];
  22347. var bindingCount = 0;
  22348. this.updates.forEach(function (expression) {
  22349. var _a = _this.preprocessUpdateExpression(expression), sourceSpan = _a.sourceSpan, context = _a.context, value = _a.value;
  22350. var bindingId = "" + bindingCount++;
  22351. var nameResolver = context === _this.component ? _this : defaultResolver;
  22352. var _b = convertPropertyBinding(nameResolver, variable(_this.getOutputVar(context)), value, bindingId, BindingForm.General), stmts = _b.stmts, currValExpr = _b.currValExpr;
  22353. stmts.push(new ExpressionStatement(currValExpr));
  22354. viewStmts.push.apply(viewStmts, __spread(stmts.map(function (stmt) { return applySourceSpanToStatementIfNeeded(stmt, sourceSpan); })));
  22355. });
  22356. this.actions.forEach(function (_a) {
  22357. var sourceSpan = _a.sourceSpan, context = _a.context, value = _a.value;
  22358. var bindingId = "" + bindingCount++;
  22359. var nameResolver = context === _this.component ? _this : defaultResolver;
  22360. var stmts = convertActionBinding(nameResolver, variable(_this.getOutputVar(context)), value, bindingId).stmts;
  22361. viewStmts.push.apply(viewStmts, __spread(stmts.map(function (stmt) { return applySourceSpanToStatementIfNeeded(stmt, sourceSpan); })));
  22362. });
  22363. if (this.guards.length) {
  22364. var guardExpression = undefined;
  22365. try {
  22366. for (var _b = __values(this.guards), _c = _b.next(); !_c.done; _c = _b.next()) {
  22367. var guard = _c.value;
  22368. var _d = this.preprocessUpdateExpression(guard.expression), context = _d.context, value = _d.value;
  22369. var bindingId = "" + bindingCount++;
  22370. var nameResolver = context === this.component ? this : defaultResolver;
  22371. // We only support support simple expressions and ignore others as they
  22372. // are unlikely to affect type narrowing.
  22373. var _e = convertPropertyBinding(nameResolver, variable(this.getOutputVar(context)), value, bindingId, BindingForm.TrySimple), stmts = _e.stmts, currValExpr = _e.currValExpr;
  22374. if (stmts.length == 0) {
  22375. var guardClause = guard.useIf ? currValExpr : this.ctx.importExpr(guard.guard).callFn([currValExpr]);
  22376. guardExpression = guardExpression ? guardExpression.and(guardClause) : guardClause;
  22377. }
  22378. }
  22379. }
  22380. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  22381. finally {
  22382. try {
  22383. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  22384. }
  22385. finally { if (e_3) throw e_3.error; }
  22386. }
  22387. if (guardExpression) {
  22388. viewStmts = [new IfStmt(guardExpression, viewStmts)];
  22389. }
  22390. }
  22391. var viewName = "_View_" + componentId + "_" + this.embeddedViewIndex;
  22392. var viewFactory = new DeclareFunctionStmt(viewName, [], viewStmts);
  22393. targetStatements.push(viewFactory);
  22394. return targetStatements;
  22395. };
  22396. ViewBuilder.prototype.visitBoundText = function (ast, context) {
  22397. var _this = this;
  22398. var astWithSource = ast.value;
  22399. var inter = astWithSource.ast;
  22400. inter.expressions.forEach(function (expr) {
  22401. return _this.updates.push({ context: _this.component, value: expr, sourceSpan: ast.sourceSpan });
  22402. });
  22403. };
  22404. ViewBuilder.prototype.visitEmbeddedTemplate = function (ast, context) {
  22405. this.visitElementOrTemplate(ast);
  22406. // Note: The old view compiler used to use an `any` type
  22407. // for the context in any embedded view.
  22408. // We keep this behaivor behind a flag for now.
  22409. if (this.options.fullTemplateTypeCheck) {
  22410. // Find any applicable type guards. For example, NgIf has a type guard on ngIf
  22411. // (see NgIf.ngIfTypeGuard) that can be used to indicate that a template is only
  22412. // stamped out if ngIf is truthy so any bindings in the template can assume that,
  22413. // if a nullable type is used for ngIf, that expression is not null or undefined.
  22414. var guards = this.getTypeGuardExpressions(ast);
  22415. var childVisitor = this.viewBuilderFactory(this, guards);
  22416. this.children.push(childVisitor);
  22417. childVisitor.visitAll(ast.variables, ast.children);
  22418. }
  22419. };
  22420. ViewBuilder.prototype.visitElement = function (ast, context) {
  22421. var _this = this;
  22422. this.visitElementOrTemplate(ast);
  22423. ast.inputs.forEach(function (inputAst) {
  22424. _this.updates.push({ context: _this.component, value: inputAst.value, sourceSpan: inputAst.sourceSpan });
  22425. });
  22426. templateVisitAll(this, ast.children);
  22427. };
  22428. ViewBuilder.prototype.visitElementOrTemplate = function (ast) {
  22429. var _this = this;
  22430. ast.directives.forEach(function (dirAst) { _this.visitDirective(dirAst); });
  22431. ast.references.forEach(function (ref) {
  22432. var outputVarType = null;
  22433. // Note: The old view compiler used to use an `any` type
  22434. // for directives exposed via `exportAs`.
  22435. // We keep this behaivor behind a flag for now.
  22436. if (ref.value && ref.value.identifier && _this.options.fullTemplateTypeCheck) {
  22437. outputVarType = ref.value.identifier.reference;
  22438. }
  22439. else {
  22440. outputVarType = exports.BuiltinTypeName.Dynamic;
  22441. }
  22442. _this.refOutputVars.set(ref.name, outputVarType);
  22443. });
  22444. ast.outputs.forEach(function (outputAst) {
  22445. _this.actions.push({ context: _this.component, value: outputAst.handler, sourceSpan: outputAst.sourceSpan });
  22446. });
  22447. };
  22448. ViewBuilder.prototype.visitDirective = function (dirAst) {
  22449. var _this = this;
  22450. var dirType = dirAst.directive.type.reference;
  22451. dirAst.inputs.forEach(function (input) { return _this.updates.push({ context: _this.component, value: input.value, sourceSpan: input.sourceSpan }); });
  22452. // Note: The old view compiler used to use an `any` type
  22453. // for expressions in host properties / events.
  22454. // We keep this behaivor behind a flag for now.
  22455. if (this.options.fullTemplateTypeCheck) {
  22456. dirAst.hostProperties.forEach(function (inputAst) { return _this.updates.push({ context: dirType, value: inputAst.value, sourceSpan: inputAst.sourceSpan }); });
  22457. dirAst.hostEvents.forEach(function (hostEventAst) { return _this.actions.push({
  22458. context: dirType,
  22459. value: hostEventAst.handler,
  22460. sourceSpan: hostEventAst.sourceSpan
  22461. }); });
  22462. }
  22463. };
  22464. ViewBuilder.prototype.notifyImplicitReceiverUse = function () { };
  22465. ViewBuilder.prototype.getLocal = function (name) {
  22466. if (name == EventHandlerVars.event.name) {
  22467. return variable(this.getOutputVar(exports.BuiltinTypeName.Dynamic));
  22468. }
  22469. for (var currBuilder = this; currBuilder; currBuilder = currBuilder.parent) {
  22470. var outputVarType = void 0;
  22471. // check references
  22472. outputVarType = currBuilder.refOutputVars.get(name);
  22473. if (outputVarType == null) {
  22474. // check variables
  22475. var varAst = currBuilder.variables.find(function (varAst) { return varAst.name === name; });
  22476. if (varAst) {
  22477. outputVarType = exports.BuiltinTypeName.Dynamic;
  22478. }
  22479. }
  22480. if (outputVarType != null) {
  22481. return variable(this.getOutputVar(outputVarType));
  22482. }
  22483. }
  22484. return null;
  22485. };
  22486. ViewBuilder.prototype.pipeOutputVar = function (name) {
  22487. var pipe = this.pipes.get(name);
  22488. if (!pipe) {
  22489. throw new Error("Illegal State: Could not find pipe " + name + " in template of " + this.component);
  22490. }
  22491. return this.getOutputVar(pipe);
  22492. };
  22493. ViewBuilder.prototype.preprocessUpdateExpression = function (expression) {
  22494. var _this = this;
  22495. return {
  22496. sourceSpan: expression.sourceSpan,
  22497. context: expression.context,
  22498. value: convertPropertyBindingBuiltins({
  22499. createLiteralArrayConverter: function (argCount) { return function (args) {
  22500. var arr = literalArr(args);
  22501. // Note: The old view compiler used to use an `any` type
  22502. // for arrays.
  22503. return _this.options.fullTemplateTypeCheck ? arr : arr.cast(DYNAMIC_TYPE);
  22504. }; },
  22505. createLiteralMapConverter: function (keys) { return function (values) {
  22506. var entries = keys.map(function (k, i) { return ({
  22507. key: k.key,
  22508. value: values[i],
  22509. quoted: k.quoted,
  22510. }); });
  22511. var map = literalMap(entries);
  22512. // Note: The old view compiler used to use an `any` type
  22513. // for maps.
  22514. return _this.options.fullTemplateTypeCheck ? map : map.cast(DYNAMIC_TYPE);
  22515. }; },
  22516. createPipeConverter: function (name, argCount) { return function (args) {
  22517. // Note: The old view compiler used to use an `any` type
  22518. // for pipes.
  22519. var pipeExpr = _this.options.fullTemplateTypeCheck ?
  22520. variable(_this.pipeOutputVar(name)) :
  22521. variable(_this.getOutputVar(exports.BuiltinTypeName.Dynamic));
  22522. return pipeExpr.callMethod('transform', args);
  22523. }; },
  22524. }, expression.value)
  22525. };
  22526. };
  22527. ViewBuilder.prototype.visitNgContent = function (ast, context) { };
  22528. ViewBuilder.prototype.visitText = function (ast, context) { };
  22529. ViewBuilder.prototype.visitDirectiveProperty = function (ast, context) { };
  22530. ViewBuilder.prototype.visitReference = function (ast, context) { };
  22531. ViewBuilder.prototype.visitVariable = function (ast, context) { };
  22532. ViewBuilder.prototype.visitEvent = function (ast, context) { };
  22533. ViewBuilder.prototype.visitElementProperty = function (ast, context) { };
  22534. ViewBuilder.prototype.visitAttr = function (ast, context) { };
  22535. return ViewBuilder;
  22536. }());
  22537. /**
  22538. * @license
  22539. * Copyright Google Inc. All Rights Reserved.
  22540. *
  22541. * Use of this source code is governed by an MIT-style license that can be
  22542. * found in the LICENSE file at https://angular.io/license
  22543. */
  22544. var CLASS_ATTR$1 = 'class';
  22545. var STYLE_ATTR = 'style';
  22546. var IMPLICIT_TEMPLATE_VAR = '\$implicit';
  22547. var ViewCompileResult = /** @class */ (function () {
  22548. function ViewCompileResult(viewClassVar, rendererTypeVar) {
  22549. this.viewClassVar = viewClassVar;
  22550. this.rendererTypeVar = rendererTypeVar;
  22551. }
  22552. return ViewCompileResult;
  22553. }());
  22554. var ViewCompiler = /** @class */ (function () {
  22555. function ViewCompiler(_reflector) {
  22556. this._reflector = _reflector;
  22557. }
  22558. ViewCompiler.prototype.compileComponent = function (outputCtx, component, template, styles, usedPipes) {
  22559. var _this = this;
  22560. var _a;
  22561. var embeddedViewCount = 0;
  22562. var staticQueryIds = findStaticQueryIds(template);
  22563. var renderComponentVarName = undefined;
  22564. if (!component.isHost) {
  22565. var template_1 = component.template;
  22566. var customRenderData = [];
  22567. if (template_1.animations && template_1.animations.length) {
  22568. customRenderData.push(new LiteralMapEntry('animation', convertValueToOutputAst(outputCtx, template_1.animations), true));
  22569. }
  22570. var renderComponentVar = variable(rendererTypeName(component.type.reference));
  22571. renderComponentVarName = renderComponentVar.name;
  22572. outputCtx.statements.push(renderComponentVar
  22573. .set(importExpr(Identifiers.createRendererType2).callFn([new LiteralMapExpr([
  22574. new LiteralMapEntry('encapsulation', literal(template_1.encapsulation), false),
  22575. new LiteralMapEntry('styles', styles, false),
  22576. new LiteralMapEntry('data', new LiteralMapExpr(customRenderData), false)
  22577. ])]))
  22578. .toDeclStmt(importType(Identifiers.RendererType2), [exports.StmtModifier.Final, exports.StmtModifier.Exported]));
  22579. }
  22580. var viewBuilderFactory = function (parent) {
  22581. var embeddedViewIndex = embeddedViewCount++;
  22582. return new ViewBuilder$1(_this._reflector, outputCtx, parent, component, embeddedViewIndex, usedPipes, staticQueryIds, viewBuilderFactory);
  22583. };
  22584. var visitor = viewBuilderFactory(null);
  22585. visitor.visitAll([], template);
  22586. (_a = outputCtx.statements).push.apply(_a, __spread(visitor.build()));
  22587. return new ViewCompileResult(visitor.viewName, renderComponentVarName);
  22588. };
  22589. return ViewCompiler;
  22590. }());
  22591. var LOG_VAR$1 = variable('_l');
  22592. var VIEW_VAR = variable('_v');
  22593. var CHECK_VAR = variable('_ck');
  22594. var COMP_VAR = variable('_co');
  22595. var EVENT_NAME_VAR = variable('en');
  22596. var ALLOW_DEFAULT_VAR = variable("ad");
  22597. var ViewBuilder$1 = /** @class */ (function () {
  22598. function ViewBuilder(reflector, outputCtx, parent, component, embeddedViewIndex, usedPipes, staticQueryIds, viewBuilderFactory) {
  22599. this.reflector = reflector;
  22600. this.outputCtx = outputCtx;
  22601. this.parent = parent;
  22602. this.component = component;
  22603. this.embeddedViewIndex = embeddedViewIndex;
  22604. this.usedPipes = usedPipes;
  22605. this.staticQueryIds = staticQueryIds;
  22606. this.viewBuilderFactory = viewBuilderFactory;
  22607. this.nodes = [];
  22608. this.purePipeNodeIndices = Object.create(null);
  22609. // Need Object.create so that we don't have builtin values...
  22610. this.refNodeIndices = Object.create(null);
  22611. this.variables = [];
  22612. this.children = [];
  22613. // TODO(tbosch): The old view compiler used to use an `any` type
  22614. // for the context in any embedded view. We keep this behaivor for now
  22615. // to be able to introduce the new view compiler without too many errors.
  22616. this.compType = this.embeddedViewIndex > 0 ?
  22617. DYNAMIC_TYPE :
  22618. expressionType(outputCtx.importExpr(this.component.type.reference));
  22619. this.viewName = viewClassName(this.component.type.reference, this.embeddedViewIndex);
  22620. }
  22621. ViewBuilder.prototype.visitAll = function (variables, astNodes) {
  22622. var _this = this;
  22623. this.variables = variables;
  22624. // create the pipes for the pure pipes immediately, so that we know their indices.
  22625. if (!this.parent) {
  22626. this.usedPipes.forEach(function (pipe) {
  22627. if (pipe.pure) {
  22628. _this.purePipeNodeIndices[pipe.name] = _this._createPipe(null, pipe);
  22629. }
  22630. });
  22631. }
  22632. if (!this.parent) {
  22633. var queryIds_1 = staticViewQueryIds(this.staticQueryIds);
  22634. this.component.viewQueries.forEach(function (query, queryIndex) {
  22635. // Note: queries start with id 1 so we can use the number in a Bloom filter!
  22636. var queryId = queryIndex + 1;
  22637. var bindingType = query.first ? 0 /* First */ : 1 /* All */;
  22638. var flags = 134217728 /* TypeViewQuery */ | calcStaticDynamicQueryFlags(queryIds_1, queryId, query);
  22639. _this.nodes.push(function () { return ({
  22640. sourceSpan: null,
  22641. nodeFlags: flags,
  22642. nodeDef: importExpr(Identifiers.queryDef).callFn([
  22643. literal(flags), literal(queryId),
  22644. new LiteralMapExpr([new LiteralMapEntry(query.propertyName, literal(bindingType), false)])
  22645. ])
  22646. }); });
  22647. });
  22648. }
  22649. templateVisitAll(this, astNodes);
  22650. if (this.parent && (astNodes.length === 0 || needsAdditionalRootNode(astNodes))) {
  22651. // if the view is an embedded view, then we need to add an additional root node in some cases
  22652. this.nodes.push(function () { return ({
  22653. sourceSpan: null,
  22654. nodeFlags: 1 /* TypeElement */,
  22655. nodeDef: importExpr(Identifiers.anchorDef).callFn([
  22656. literal(0 /* None */), NULL_EXPR, NULL_EXPR, literal(0)
  22657. ])
  22658. }); });
  22659. }
  22660. };
  22661. ViewBuilder.prototype.build = function (targetStatements) {
  22662. if (targetStatements === void 0) { targetStatements = []; }
  22663. this.children.forEach(function (child) { return child.build(targetStatements); });
  22664. var _a = this._createNodeExpressions(), updateRendererStmts = _a.updateRendererStmts, updateDirectivesStmts = _a.updateDirectivesStmts, nodeDefExprs = _a.nodeDefExprs;
  22665. var updateRendererFn = this._createUpdateFn(updateRendererStmts);
  22666. var updateDirectivesFn = this._createUpdateFn(updateDirectivesStmts);
  22667. var viewFlags = 0 /* None */;
  22668. if (!this.parent && this.component.changeDetection === ChangeDetectionStrategy.OnPush) {
  22669. viewFlags |= 2 /* OnPush */;
  22670. }
  22671. var viewFactory = new DeclareFunctionStmt(this.viewName, [new FnParam(LOG_VAR$1.name)], [new ReturnStatement(importExpr(Identifiers.viewDef).callFn([
  22672. literal(viewFlags),
  22673. literalArr(nodeDefExprs),
  22674. updateDirectivesFn,
  22675. updateRendererFn,
  22676. ]))], importType(Identifiers.ViewDefinition), this.embeddedViewIndex === 0 ? [exports.StmtModifier.Exported] : []);
  22677. targetStatements.push(viewFactory);
  22678. return targetStatements;
  22679. };
  22680. ViewBuilder.prototype._createUpdateFn = function (updateStmts) {
  22681. var updateFn;
  22682. if (updateStmts.length > 0) {
  22683. var preStmts = [];
  22684. if (!this.component.isHost && findReadVarNames(updateStmts).has(COMP_VAR.name)) {
  22685. preStmts.push(COMP_VAR.set(VIEW_VAR.prop('component')).toDeclStmt(this.compType));
  22686. }
  22687. updateFn = fn([
  22688. new FnParam(CHECK_VAR.name, INFERRED_TYPE),
  22689. new FnParam(VIEW_VAR.name, INFERRED_TYPE)
  22690. ], __spread(preStmts, updateStmts), INFERRED_TYPE);
  22691. }
  22692. else {
  22693. updateFn = NULL_EXPR;
  22694. }
  22695. return updateFn;
  22696. };
  22697. ViewBuilder.prototype.visitNgContent = function (ast, context) {
  22698. // ngContentDef(ngContentIndex: number, index: number): NodeDef;
  22699. this.nodes.push(function () { return ({
  22700. sourceSpan: ast.sourceSpan,
  22701. nodeFlags: 8 /* TypeNgContent */,
  22702. nodeDef: importExpr(Identifiers.ngContentDef).callFn([
  22703. literal(ast.ngContentIndex), literal(ast.index)
  22704. ])
  22705. }); });
  22706. };
  22707. ViewBuilder.prototype.visitText = function (ast, context) {
  22708. // Static text nodes have no check function
  22709. var checkIndex = -1;
  22710. this.nodes.push(function () { return ({
  22711. sourceSpan: ast.sourceSpan,
  22712. nodeFlags: 2 /* TypeText */,
  22713. nodeDef: importExpr(Identifiers.textDef).callFn([
  22714. literal(checkIndex),
  22715. literal(ast.ngContentIndex),
  22716. literalArr([literal(ast.value)]),
  22717. ])
  22718. }); });
  22719. };
  22720. ViewBuilder.prototype.visitBoundText = function (ast, context) {
  22721. var _this = this;
  22722. var nodeIndex = this.nodes.length;
  22723. // reserve the space in the nodeDefs array
  22724. this.nodes.push(null);
  22725. var astWithSource = ast.value;
  22726. var inter = astWithSource.ast;
  22727. var updateRendererExpressions = inter.expressions.map(function (expr, bindingIndex) { return _this._preprocessUpdateExpression({ nodeIndex: nodeIndex, bindingIndex: bindingIndex, sourceSpan: ast.sourceSpan, context: COMP_VAR, value: expr }); });
  22728. // Check index is the same as the node index during compilation
  22729. // They might only differ at runtime
  22730. var checkIndex = nodeIndex;
  22731. this.nodes[nodeIndex] = function () { return ({
  22732. sourceSpan: ast.sourceSpan,
  22733. nodeFlags: 2 /* TypeText */,
  22734. nodeDef: importExpr(Identifiers.textDef).callFn([
  22735. literal(checkIndex),
  22736. literal(ast.ngContentIndex),
  22737. literalArr(inter.strings.map(function (s) { return literal(s); })),
  22738. ]),
  22739. updateRenderer: updateRendererExpressions
  22740. }); };
  22741. };
  22742. ViewBuilder.prototype.visitEmbeddedTemplate = function (ast, context) {
  22743. var _this = this;
  22744. var nodeIndex = this.nodes.length;
  22745. // reserve the space in the nodeDefs array
  22746. this.nodes.push(null);
  22747. var _a = this._visitElementOrTemplate(nodeIndex, ast), flags = _a.flags, queryMatchesExpr = _a.queryMatchesExpr, hostEvents = _a.hostEvents;
  22748. var childVisitor = this.viewBuilderFactory(this);
  22749. this.children.push(childVisitor);
  22750. childVisitor.visitAll(ast.variables, ast.children);
  22751. var childCount = this.nodes.length - nodeIndex - 1;
  22752. // anchorDef(
  22753. // flags: NodeFlags, matchedQueries: [string, QueryValueType][], ngContentIndex: number,
  22754. // childCount: number, handleEventFn?: ElementHandleEventFn, templateFactory?:
  22755. // ViewDefinitionFactory): NodeDef;
  22756. this.nodes[nodeIndex] = function () { return ({
  22757. sourceSpan: ast.sourceSpan,
  22758. nodeFlags: 1 /* TypeElement */ | flags,
  22759. nodeDef: importExpr(Identifiers.anchorDef).callFn([
  22760. literal(flags),
  22761. queryMatchesExpr,
  22762. literal(ast.ngContentIndex),
  22763. literal(childCount),
  22764. _this._createElementHandleEventFn(nodeIndex, hostEvents),
  22765. variable(childVisitor.viewName),
  22766. ])
  22767. }); };
  22768. };
  22769. ViewBuilder.prototype.visitElement = function (ast, context) {
  22770. var _this = this;
  22771. var nodeIndex = this.nodes.length;
  22772. // reserve the space in the nodeDefs array so we can add children
  22773. this.nodes.push(null);
  22774. // Using a null element name creates an anchor.
  22775. var elName = isNgContainer(ast.name) ? null : ast.name;
  22776. var _a = this._visitElementOrTemplate(nodeIndex, ast), flags = _a.flags, usedEvents = _a.usedEvents, queryMatchesExpr = _a.queryMatchesExpr, dirHostBindings = _a.hostBindings, hostEvents = _a.hostEvents;
  22777. var inputDefs = [];
  22778. var updateRendererExpressions = [];
  22779. var outputDefs = [];
  22780. if (elName) {
  22781. var hostBindings = ast.inputs
  22782. .map(function (inputAst) { return ({
  22783. context: COMP_VAR,
  22784. inputAst: inputAst,
  22785. dirAst: null,
  22786. }); })
  22787. .concat(dirHostBindings);
  22788. if (hostBindings.length) {
  22789. updateRendererExpressions =
  22790. hostBindings.map(function (hostBinding, bindingIndex) { return _this._preprocessUpdateExpression({
  22791. context: hostBinding.context,
  22792. nodeIndex: nodeIndex,
  22793. bindingIndex: bindingIndex,
  22794. sourceSpan: hostBinding.inputAst.sourceSpan,
  22795. value: hostBinding.inputAst.value
  22796. }); });
  22797. inputDefs = hostBindings.map(function (hostBinding) { return elementBindingDef(hostBinding.inputAst, hostBinding.dirAst); });
  22798. }
  22799. outputDefs = usedEvents.map(function (_a) {
  22800. var _b = __read(_a, 2), target = _b[0], eventName = _b[1];
  22801. return literalArr([literal(target), literal(eventName)]);
  22802. });
  22803. }
  22804. templateVisitAll(this, ast.children);
  22805. var childCount = this.nodes.length - nodeIndex - 1;
  22806. var compAst = ast.directives.find(function (dirAst) { return dirAst.directive.isComponent; });
  22807. var compRendererType = NULL_EXPR;
  22808. var compView = NULL_EXPR;
  22809. if (compAst) {
  22810. compView = this.outputCtx.importExpr(compAst.directive.componentViewType);
  22811. compRendererType = this.outputCtx.importExpr(compAst.directive.rendererType);
  22812. }
  22813. // Check index is the same as the node index during compilation
  22814. // They might only differ at runtime
  22815. var checkIndex = nodeIndex;
  22816. this.nodes[nodeIndex] = function () { return ({
  22817. sourceSpan: ast.sourceSpan,
  22818. nodeFlags: 1 /* TypeElement */ | flags,
  22819. nodeDef: importExpr(Identifiers.elementDef).callFn([
  22820. literal(checkIndex),
  22821. literal(flags),
  22822. queryMatchesExpr,
  22823. literal(ast.ngContentIndex),
  22824. literal(childCount),
  22825. literal(elName),
  22826. elName ? fixedAttrsDef(ast) : NULL_EXPR,
  22827. inputDefs.length ? literalArr(inputDefs) : NULL_EXPR,
  22828. outputDefs.length ? literalArr(outputDefs) : NULL_EXPR,
  22829. _this._createElementHandleEventFn(nodeIndex, hostEvents),
  22830. compView,
  22831. compRendererType,
  22832. ]),
  22833. updateRenderer: updateRendererExpressions
  22834. }); };
  22835. };
  22836. ViewBuilder.prototype._visitElementOrTemplate = function (nodeIndex, ast) {
  22837. var _this = this;
  22838. var flags = 0 /* None */;
  22839. if (ast.hasViewContainer) {
  22840. flags |= 16777216 /* EmbeddedViews */;
  22841. }
  22842. var usedEvents = new Map();
  22843. ast.outputs.forEach(function (event) {
  22844. var _a = elementEventNameAndTarget(event, null), name = _a.name, target = _a.target;
  22845. usedEvents.set(elementEventFullName(target, name), [target, name]);
  22846. });
  22847. ast.directives.forEach(function (dirAst) {
  22848. dirAst.hostEvents.forEach(function (event) {
  22849. var _a = elementEventNameAndTarget(event, dirAst), name = _a.name, target = _a.target;
  22850. usedEvents.set(elementEventFullName(target, name), [target, name]);
  22851. });
  22852. });
  22853. var hostBindings = [];
  22854. var hostEvents = [];
  22855. this._visitComponentFactoryResolverProvider(ast.directives);
  22856. ast.providers.forEach(function (providerAst, providerIndex) {
  22857. var dirAst = undefined;
  22858. var dirIndex = undefined;
  22859. ast.directives.forEach(function (localDirAst, i) {
  22860. if (localDirAst.directive.type.reference === tokenReference(providerAst.token)) {
  22861. dirAst = localDirAst;
  22862. dirIndex = i;
  22863. }
  22864. });
  22865. if (dirAst) {
  22866. var _a = _this._visitDirective(providerAst, dirAst, dirIndex, nodeIndex, ast.references, ast.queryMatches, usedEvents, _this.staticQueryIds.get(ast)), dirHostBindings = _a.hostBindings, dirHostEvents = _a.hostEvents;
  22867. hostBindings.push.apply(hostBindings, __spread(dirHostBindings));
  22868. hostEvents.push.apply(hostEvents, __spread(dirHostEvents));
  22869. }
  22870. else {
  22871. _this._visitProvider(providerAst, ast.queryMatches);
  22872. }
  22873. });
  22874. var queryMatchExprs = [];
  22875. ast.queryMatches.forEach(function (match) {
  22876. var valueType = undefined;
  22877. if (tokenReference(match.value) ===
  22878. _this.reflector.resolveExternalReference(Identifiers.ElementRef)) {
  22879. valueType = 0 /* ElementRef */;
  22880. }
  22881. else if (tokenReference(match.value) ===
  22882. _this.reflector.resolveExternalReference(Identifiers.ViewContainerRef)) {
  22883. valueType = 3 /* ViewContainerRef */;
  22884. }
  22885. else if (tokenReference(match.value) ===
  22886. _this.reflector.resolveExternalReference(Identifiers.TemplateRef)) {
  22887. valueType = 2 /* TemplateRef */;
  22888. }
  22889. if (valueType != null) {
  22890. queryMatchExprs.push(literalArr([literal(match.queryId), literal(valueType)]));
  22891. }
  22892. });
  22893. ast.references.forEach(function (ref) {
  22894. var valueType = undefined;
  22895. if (!ref.value) {
  22896. valueType = 1 /* RenderElement */;
  22897. }
  22898. else if (tokenReference(ref.value) ===
  22899. _this.reflector.resolveExternalReference(Identifiers.TemplateRef)) {
  22900. valueType = 2 /* TemplateRef */;
  22901. }
  22902. if (valueType != null) {
  22903. _this.refNodeIndices[ref.name] = nodeIndex;
  22904. queryMatchExprs.push(literalArr([literal(ref.name), literal(valueType)]));
  22905. }
  22906. });
  22907. ast.outputs.forEach(function (outputAst) {
  22908. hostEvents.push({ context: COMP_VAR, eventAst: outputAst, dirAst: null });
  22909. });
  22910. return {
  22911. flags: flags,
  22912. usedEvents: Array.from(usedEvents.values()),
  22913. queryMatchesExpr: queryMatchExprs.length ? literalArr(queryMatchExprs) : NULL_EXPR,
  22914. hostBindings: hostBindings,
  22915. hostEvents: hostEvents
  22916. };
  22917. };
  22918. ViewBuilder.prototype._visitDirective = function (providerAst, dirAst, directiveIndex, elementNodeIndex, refs, queryMatches, usedEvents, queryIds) {
  22919. var _this = this;
  22920. var nodeIndex = this.nodes.length;
  22921. // reserve the space in the nodeDefs array so we can add children
  22922. this.nodes.push(null);
  22923. dirAst.directive.queries.forEach(function (query, queryIndex) {
  22924. var queryId = dirAst.contentQueryStartId + queryIndex;
  22925. var flags = 67108864 /* TypeContentQuery */ | calcStaticDynamicQueryFlags(queryIds, queryId, query);
  22926. var bindingType = query.first ? 0 /* First */ : 1 /* All */;
  22927. _this.nodes.push(function () { return ({
  22928. sourceSpan: dirAst.sourceSpan,
  22929. nodeFlags: flags,
  22930. nodeDef: importExpr(Identifiers.queryDef).callFn([
  22931. literal(flags), literal(queryId),
  22932. new LiteralMapExpr([new LiteralMapEntry(query.propertyName, literal(bindingType), false)])
  22933. ]),
  22934. }); });
  22935. });
  22936. // Note: the operation below might also create new nodeDefs,
  22937. // but we don't want them to be a child of a directive,
  22938. // as they might be a provider/pipe on their own.
  22939. // I.e. we only allow queries as children of directives nodes.
  22940. var childCount = this.nodes.length - nodeIndex - 1;
  22941. var _a = this._visitProviderOrDirective(providerAst, queryMatches), flags = _a.flags, queryMatchExprs = _a.queryMatchExprs, providerExpr = _a.providerExpr, depsExpr = _a.depsExpr;
  22942. refs.forEach(function (ref) {
  22943. if (ref.value && tokenReference(ref.value) === tokenReference(providerAst.token)) {
  22944. _this.refNodeIndices[ref.name] = nodeIndex;
  22945. queryMatchExprs.push(literalArr([literal(ref.name), literal(4 /* Provider */)]));
  22946. }
  22947. });
  22948. if (dirAst.directive.isComponent) {
  22949. flags |= 32768 /* Component */;
  22950. }
  22951. var inputDefs = dirAst.inputs.map(function (inputAst, inputIndex) {
  22952. var mapValue = literalArr([literal(inputIndex), literal(inputAst.directiveName)]);
  22953. // Note: it's important to not quote the key so that we can capture renames by minifiers!
  22954. return new LiteralMapEntry(inputAst.directiveName, mapValue, false);
  22955. });
  22956. var outputDefs = [];
  22957. var dirMeta = dirAst.directive;
  22958. Object.keys(dirMeta.outputs).forEach(function (propName) {
  22959. var eventName = dirMeta.outputs[propName];
  22960. if (usedEvents.has(eventName)) {
  22961. // Note: it's important to not quote the key so that we can capture renames by minifiers!
  22962. outputDefs.push(new LiteralMapEntry(propName, literal(eventName), false));
  22963. }
  22964. });
  22965. var updateDirectiveExpressions = [];
  22966. if (dirAst.inputs.length || (flags & (262144 /* DoCheck */ | 65536 /* OnInit */)) > 0) {
  22967. updateDirectiveExpressions =
  22968. dirAst.inputs.map(function (input, bindingIndex) { return _this._preprocessUpdateExpression({
  22969. nodeIndex: nodeIndex,
  22970. bindingIndex: bindingIndex,
  22971. sourceSpan: input.sourceSpan,
  22972. context: COMP_VAR,
  22973. value: input.value
  22974. }); });
  22975. }
  22976. var dirContextExpr = importExpr(Identifiers.nodeValue).callFn([VIEW_VAR, literal(nodeIndex)]);
  22977. var hostBindings = dirAst.hostProperties.map(function (inputAst) { return ({
  22978. context: dirContextExpr,
  22979. dirAst: dirAst,
  22980. inputAst: inputAst,
  22981. }); });
  22982. var hostEvents = dirAst.hostEvents.map(function (hostEventAst) { return ({
  22983. context: dirContextExpr,
  22984. eventAst: hostEventAst, dirAst: dirAst,
  22985. }); });
  22986. // Check index is the same as the node index during compilation
  22987. // They might only differ at runtime
  22988. var checkIndex = nodeIndex;
  22989. this.nodes[nodeIndex] = function () { return ({
  22990. sourceSpan: dirAst.sourceSpan,
  22991. nodeFlags: 16384 /* TypeDirective */ | flags,
  22992. nodeDef: importExpr(Identifiers.directiveDef).callFn([
  22993. literal(checkIndex),
  22994. literal(flags),
  22995. queryMatchExprs.length ? literalArr(queryMatchExprs) : NULL_EXPR,
  22996. literal(childCount),
  22997. providerExpr,
  22998. depsExpr,
  22999. inputDefs.length ? new LiteralMapExpr(inputDefs) : NULL_EXPR,
  23000. outputDefs.length ? new LiteralMapExpr(outputDefs) : NULL_EXPR,
  23001. ]),
  23002. updateDirectives: updateDirectiveExpressions,
  23003. directive: dirAst.directive.type,
  23004. }); };
  23005. return { hostBindings: hostBindings, hostEvents: hostEvents };
  23006. };
  23007. ViewBuilder.prototype._visitProvider = function (providerAst, queryMatches) {
  23008. this._addProviderNode(this._visitProviderOrDirective(providerAst, queryMatches));
  23009. };
  23010. ViewBuilder.prototype._visitComponentFactoryResolverProvider = function (directives) {
  23011. var componentDirMeta = directives.find(function (dirAst) { return dirAst.directive.isComponent; });
  23012. if (componentDirMeta && componentDirMeta.directive.entryComponents.length) {
  23013. var _a = componentFactoryResolverProviderDef(this.reflector, this.outputCtx, 8192 /* PrivateProvider */, componentDirMeta.directive.entryComponents), providerExpr = _a.providerExpr, depsExpr = _a.depsExpr, flags = _a.flags, tokenExpr = _a.tokenExpr;
  23014. this._addProviderNode({
  23015. providerExpr: providerExpr,
  23016. depsExpr: depsExpr,
  23017. flags: flags,
  23018. tokenExpr: tokenExpr,
  23019. queryMatchExprs: [],
  23020. sourceSpan: componentDirMeta.sourceSpan
  23021. });
  23022. }
  23023. };
  23024. ViewBuilder.prototype._addProviderNode = function (data) {
  23025. var nodeIndex = this.nodes.length;
  23026. // providerDef(
  23027. // flags: NodeFlags, matchedQueries: [string, QueryValueType][], token:any,
  23028. // value: any, deps: ([DepFlags, any] | any)[]): NodeDef;
  23029. this.nodes.push(function () { return ({
  23030. sourceSpan: data.sourceSpan,
  23031. nodeFlags: data.flags,
  23032. nodeDef: importExpr(Identifiers.providerDef).callFn([
  23033. literal(data.flags),
  23034. data.queryMatchExprs.length ? literalArr(data.queryMatchExprs) : NULL_EXPR,
  23035. data.tokenExpr, data.providerExpr, data.depsExpr
  23036. ])
  23037. }); });
  23038. };
  23039. ViewBuilder.prototype._visitProviderOrDirective = function (providerAst, queryMatches) {
  23040. var flags = 0 /* None */;
  23041. var queryMatchExprs = [];
  23042. queryMatches.forEach(function (match) {
  23043. if (tokenReference(match.value) === tokenReference(providerAst.token)) {
  23044. queryMatchExprs.push(literalArr([literal(match.queryId), literal(4 /* Provider */)]));
  23045. }
  23046. });
  23047. var _a = providerDef(this.outputCtx, providerAst), providerExpr = _a.providerExpr, depsExpr = _a.depsExpr, providerFlags = _a.flags, tokenExpr = _a.tokenExpr;
  23048. return {
  23049. flags: flags | providerFlags,
  23050. queryMatchExprs: queryMatchExprs,
  23051. providerExpr: providerExpr,
  23052. depsExpr: depsExpr,
  23053. tokenExpr: tokenExpr,
  23054. sourceSpan: providerAst.sourceSpan
  23055. };
  23056. };
  23057. ViewBuilder.prototype.getLocal = function (name) {
  23058. if (name == EventHandlerVars.event.name) {
  23059. return EventHandlerVars.event;
  23060. }
  23061. var currViewExpr = VIEW_VAR;
  23062. for (var currBuilder = this; currBuilder; currBuilder = currBuilder.parent,
  23063. currViewExpr = currViewExpr.prop('parent').cast(DYNAMIC_TYPE)) {
  23064. // check references
  23065. var refNodeIndex = currBuilder.refNodeIndices[name];
  23066. if (refNodeIndex != null) {
  23067. return importExpr(Identifiers.nodeValue).callFn([currViewExpr, literal(refNodeIndex)]);
  23068. }
  23069. // check variables
  23070. var varAst = currBuilder.variables.find(function (varAst) { return varAst.name === name; });
  23071. if (varAst) {
  23072. var varValue = varAst.value || IMPLICIT_TEMPLATE_VAR;
  23073. return currViewExpr.prop('context').prop(varValue);
  23074. }
  23075. }
  23076. return null;
  23077. };
  23078. ViewBuilder.prototype.notifyImplicitReceiverUse = function () {
  23079. // Not needed in View Engine as View Engine walks through the generated
  23080. // expressions to figure out if the implicit receiver is used and needs
  23081. // to be generated as part of the pre-update statements.
  23082. };
  23083. ViewBuilder.prototype._createLiteralArrayConverter = function (sourceSpan, argCount) {
  23084. if (argCount === 0) {
  23085. var valueExpr_1 = importExpr(Identifiers.EMPTY_ARRAY);
  23086. return function () { return valueExpr_1; };
  23087. }
  23088. var checkIndex = this.nodes.length;
  23089. this.nodes.push(function () { return ({
  23090. sourceSpan: sourceSpan,
  23091. nodeFlags: 32 /* TypePureArray */,
  23092. nodeDef: importExpr(Identifiers.pureArrayDef).callFn([
  23093. literal(checkIndex),
  23094. literal(argCount),
  23095. ])
  23096. }); });
  23097. return function (args) { return callCheckStmt(checkIndex, args); };
  23098. };
  23099. ViewBuilder.prototype._createLiteralMapConverter = function (sourceSpan, keys) {
  23100. if (keys.length === 0) {
  23101. var valueExpr_2 = importExpr(Identifiers.EMPTY_MAP);
  23102. return function () { return valueExpr_2; };
  23103. }
  23104. var map = literalMap(keys.map(function (e, i) { return (__assign({}, e, { value: literal(i) })); }));
  23105. var checkIndex = this.nodes.length;
  23106. this.nodes.push(function () { return ({
  23107. sourceSpan: sourceSpan,
  23108. nodeFlags: 64 /* TypePureObject */,
  23109. nodeDef: importExpr(Identifiers.pureObjectDef).callFn([
  23110. literal(checkIndex),
  23111. map,
  23112. ])
  23113. }); });
  23114. return function (args) { return callCheckStmt(checkIndex, args); };
  23115. };
  23116. ViewBuilder.prototype._createPipeConverter = function (expression, name, argCount) {
  23117. var pipe = this.usedPipes.find(function (pipeSummary) { return pipeSummary.name === name; });
  23118. if (pipe.pure) {
  23119. var checkIndex_1 = this.nodes.length;
  23120. this.nodes.push(function () { return ({
  23121. sourceSpan: expression.sourceSpan,
  23122. nodeFlags: 128 /* TypePurePipe */,
  23123. nodeDef: importExpr(Identifiers.purePipeDef).callFn([
  23124. literal(checkIndex_1),
  23125. literal(argCount),
  23126. ])
  23127. }); });
  23128. // find underlying pipe in the component view
  23129. var compViewExpr = VIEW_VAR;
  23130. var compBuilder = this;
  23131. while (compBuilder.parent) {
  23132. compBuilder = compBuilder.parent;
  23133. compViewExpr = compViewExpr.prop('parent').cast(DYNAMIC_TYPE);
  23134. }
  23135. var pipeNodeIndex = compBuilder.purePipeNodeIndices[name];
  23136. var pipeValueExpr_1 = importExpr(Identifiers.nodeValue).callFn([compViewExpr, literal(pipeNodeIndex)]);
  23137. return function (args) { return callUnwrapValue(expression.nodeIndex, expression.bindingIndex, callCheckStmt(checkIndex_1, [pipeValueExpr_1].concat(args))); };
  23138. }
  23139. else {
  23140. var nodeIndex = this._createPipe(expression.sourceSpan, pipe);
  23141. var nodeValueExpr_1 = importExpr(Identifiers.nodeValue).callFn([VIEW_VAR, literal(nodeIndex)]);
  23142. return function (args) { return callUnwrapValue(expression.nodeIndex, expression.bindingIndex, nodeValueExpr_1.callMethod('transform', args)); };
  23143. }
  23144. };
  23145. ViewBuilder.prototype._createPipe = function (sourceSpan, pipe) {
  23146. var _this = this;
  23147. var nodeIndex = this.nodes.length;
  23148. var flags = 0 /* None */;
  23149. pipe.type.lifecycleHooks.forEach(function (lifecycleHook) {
  23150. // for pipes, we only support ngOnDestroy
  23151. if (lifecycleHook === LifecycleHooks.OnDestroy) {
  23152. flags |= lifecycleHookToNodeFlag(lifecycleHook);
  23153. }
  23154. });
  23155. var depExprs = pipe.type.diDeps.map(function (diDep) { return depDef(_this.outputCtx, diDep); });
  23156. // function pipeDef(
  23157. // flags: NodeFlags, ctor: any, deps: ([DepFlags, any] | any)[]): NodeDef
  23158. this.nodes.push(function () { return ({
  23159. sourceSpan: sourceSpan,
  23160. nodeFlags: 16 /* TypePipe */,
  23161. nodeDef: importExpr(Identifiers.pipeDef).callFn([
  23162. literal(flags), _this.outputCtx.importExpr(pipe.type.reference), literalArr(depExprs)
  23163. ])
  23164. }); });
  23165. return nodeIndex;
  23166. };
  23167. /**
  23168. * For the AST in `UpdateExpression.value`:
  23169. * - create nodes for pipes, literal arrays and, literal maps,
  23170. * - update the AST to replace pipes, literal arrays and, literal maps with calls to check fn.
  23171. *
  23172. * WARNING: This might create new nodeDefs (for pipes and literal arrays and literal maps)!
  23173. */
  23174. ViewBuilder.prototype._preprocessUpdateExpression = function (expression) {
  23175. var _this = this;
  23176. return {
  23177. nodeIndex: expression.nodeIndex,
  23178. bindingIndex: expression.bindingIndex,
  23179. sourceSpan: expression.sourceSpan,
  23180. context: expression.context,
  23181. value: convertPropertyBindingBuiltins({
  23182. createLiteralArrayConverter: function (argCount) { return _this._createLiteralArrayConverter(expression.sourceSpan, argCount); },
  23183. createLiteralMapConverter: function (keys) {
  23184. return _this._createLiteralMapConverter(expression.sourceSpan, keys);
  23185. },
  23186. createPipeConverter: function (name, argCount) {
  23187. return _this._createPipeConverter(expression, name, argCount);
  23188. }
  23189. }, expression.value)
  23190. };
  23191. };
  23192. ViewBuilder.prototype._createNodeExpressions = function () {
  23193. var self = this;
  23194. var updateBindingCount = 0;
  23195. var updateRendererStmts = [];
  23196. var updateDirectivesStmts = [];
  23197. var nodeDefExprs = this.nodes.map(function (factory, nodeIndex) {
  23198. var _a = factory(), nodeDef = _a.nodeDef, nodeFlags = _a.nodeFlags, updateDirectives = _a.updateDirectives, updateRenderer = _a.updateRenderer, sourceSpan = _a.sourceSpan;
  23199. if (updateRenderer) {
  23200. updateRendererStmts.push.apply(updateRendererStmts, __spread(createUpdateStatements(nodeIndex, sourceSpan, updateRenderer, false)));
  23201. }
  23202. if (updateDirectives) {
  23203. updateDirectivesStmts.push.apply(updateDirectivesStmts, __spread(createUpdateStatements(nodeIndex, sourceSpan, updateDirectives, (nodeFlags & (262144 /* DoCheck */ | 65536 /* OnInit */)) > 0)));
  23204. }
  23205. // We use a comma expression to call the log function before
  23206. // the nodeDef function, but still use the result of the nodeDef function
  23207. // as the value.
  23208. // Note: We only add the logger to elements / text nodes,
  23209. // so we don't generate too much code.
  23210. var logWithNodeDef = nodeFlags & 3 /* CatRenderNode */ ?
  23211. new CommaExpr([LOG_VAR$1.callFn([]).callFn([]), nodeDef]) :
  23212. nodeDef;
  23213. return applySourceSpanToExpressionIfNeeded(logWithNodeDef, sourceSpan);
  23214. });
  23215. return { updateRendererStmts: updateRendererStmts, updateDirectivesStmts: updateDirectivesStmts, nodeDefExprs: nodeDefExprs };
  23216. function createUpdateStatements(nodeIndex, sourceSpan, expressions, allowEmptyExprs) {
  23217. var updateStmts = [];
  23218. var exprs = expressions.map(function (_a) {
  23219. var sourceSpan = _a.sourceSpan, context = _a.context, value = _a.value;
  23220. var bindingId = "" + updateBindingCount++;
  23221. var nameResolver = context === COMP_VAR ? self : null;
  23222. var _b = convertPropertyBinding(nameResolver, context, value, bindingId, BindingForm.General), stmts = _b.stmts, currValExpr = _b.currValExpr;
  23223. updateStmts.push.apply(updateStmts, __spread(stmts.map(function (stmt) { return applySourceSpanToStatementIfNeeded(stmt, sourceSpan); })));
  23224. return applySourceSpanToExpressionIfNeeded(currValExpr, sourceSpan);
  23225. });
  23226. if (expressions.length || allowEmptyExprs) {
  23227. updateStmts.push(applySourceSpanToStatementIfNeeded(callCheckStmt(nodeIndex, exprs).toStmt(), sourceSpan));
  23228. }
  23229. return updateStmts;
  23230. }
  23231. };
  23232. ViewBuilder.prototype._createElementHandleEventFn = function (nodeIndex, handlers) {
  23233. var _this = this;
  23234. var handleEventStmts = [];
  23235. var handleEventBindingCount = 0;
  23236. handlers.forEach(function (_a) {
  23237. var context = _a.context, eventAst = _a.eventAst, dirAst = _a.dirAst;
  23238. var bindingId = "" + handleEventBindingCount++;
  23239. var nameResolver = context === COMP_VAR ? _this : null;
  23240. var _b = convertActionBinding(nameResolver, context, eventAst.handler, bindingId), stmts = _b.stmts, allowDefault = _b.allowDefault;
  23241. var trueStmts = stmts;
  23242. if (allowDefault) {
  23243. trueStmts.push(ALLOW_DEFAULT_VAR.set(allowDefault.and(ALLOW_DEFAULT_VAR)).toStmt());
  23244. }
  23245. var _c = elementEventNameAndTarget(eventAst, dirAst), eventTarget = _c.target, eventName = _c.name;
  23246. var fullEventName = elementEventFullName(eventTarget, eventName);
  23247. handleEventStmts.push(applySourceSpanToStatementIfNeeded(new IfStmt(literal(fullEventName).identical(EVENT_NAME_VAR), trueStmts), eventAst.sourceSpan));
  23248. });
  23249. var handleEventFn;
  23250. if (handleEventStmts.length > 0) {
  23251. var preStmts = [ALLOW_DEFAULT_VAR.set(literal(true)).toDeclStmt(BOOL_TYPE)];
  23252. if (!this.component.isHost && findReadVarNames(handleEventStmts).has(COMP_VAR.name)) {
  23253. preStmts.push(COMP_VAR.set(VIEW_VAR.prop('component')).toDeclStmt(this.compType));
  23254. }
  23255. handleEventFn = fn([
  23256. new FnParam(VIEW_VAR.name, INFERRED_TYPE),
  23257. new FnParam(EVENT_NAME_VAR.name, INFERRED_TYPE),
  23258. new FnParam(EventHandlerVars.event.name, INFERRED_TYPE)
  23259. ], __spread(preStmts, handleEventStmts, [new ReturnStatement(ALLOW_DEFAULT_VAR)]), INFERRED_TYPE);
  23260. }
  23261. else {
  23262. handleEventFn = NULL_EXPR;
  23263. }
  23264. return handleEventFn;
  23265. };
  23266. ViewBuilder.prototype.visitDirective = function (ast, context) { };
  23267. ViewBuilder.prototype.visitDirectiveProperty = function (ast, context) { };
  23268. ViewBuilder.prototype.visitReference = function (ast, context) { };
  23269. ViewBuilder.prototype.visitVariable = function (ast, context) { };
  23270. ViewBuilder.prototype.visitEvent = function (ast, context) { };
  23271. ViewBuilder.prototype.visitElementProperty = function (ast, context) { };
  23272. ViewBuilder.prototype.visitAttr = function (ast, context) { };
  23273. return ViewBuilder;
  23274. }());
  23275. function needsAdditionalRootNode(astNodes) {
  23276. var lastAstNode = astNodes[astNodes.length - 1];
  23277. if (lastAstNode instanceof EmbeddedTemplateAst) {
  23278. return lastAstNode.hasViewContainer;
  23279. }
  23280. if (lastAstNode instanceof ElementAst) {
  23281. if (isNgContainer(lastAstNode.name) && lastAstNode.children.length) {
  23282. return needsAdditionalRootNode(lastAstNode.children);
  23283. }
  23284. return lastAstNode.hasViewContainer;
  23285. }
  23286. return lastAstNode instanceof NgContentAst;
  23287. }
  23288. function elementBindingDef(inputAst, dirAst) {
  23289. var inputType = inputAst.type;
  23290. switch (inputType) {
  23291. case 1 /* Attribute */:
  23292. return literalArr([
  23293. literal(1 /* TypeElementAttribute */), literal(inputAst.name),
  23294. literal(inputAst.securityContext)
  23295. ]);
  23296. case 0 /* Property */:
  23297. return literalArr([
  23298. literal(8 /* TypeProperty */), literal(inputAst.name),
  23299. literal(inputAst.securityContext)
  23300. ]);
  23301. case 4 /* Animation */:
  23302. var bindingType = 8 /* TypeProperty */ |
  23303. (dirAst && dirAst.directive.isComponent ? 32 /* SyntheticHostProperty */ :
  23304. 16 /* SyntheticProperty */);
  23305. return literalArr([
  23306. literal(bindingType), literal('@' + inputAst.name), literal(inputAst.securityContext)
  23307. ]);
  23308. case 2 /* Class */:
  23309. return literalArr([literal(2 /* TypeElementClass */), literal(inputAst.name), NULL_EXPR]);
  23310. case 3 /* Style */:
  23311. return literalArr([
  23312. literal(4 /* TypeElementStyle */), literal(inputAst.name), literal(inputAst.unit)
  23313. ]);
  23314. default:
  23315. // This default case is not needed by TypeScript compiler, as the switch is exhaustive.
  23316. // However Closure Compiler does not understand that and reports an error in typed mode.
  23317. // The `throw new Error` below works around the problem, and the unexpected: never variable
  23318. // makes sure tsc still checks this code is unreachable.
  23319. var unexpected = inputType;
  23320. throw new Error("unexpected " + unexpected);
  23321. }
  23322. }
  23323. function fixedAttrsDef(elementAst) {
  23324. var mapResult = Object.create(null);
  23325. elementAst.attrs.forEach(function (attrAst) { mapResult[attrAst.name] = attrAst.value; });
  23326. elementAst.directives.forEach(function (dirAst) {
  23327. Object.keys(dirAst.directive.hostAttributes).forEach(function (name) {
  23328. var value = dirAst.directive.hostAttributes[name];
  23329. var prevValue = mapResult[name];
  23330. mapResult[name] = prevValue != null ? mergeAttributeValue(name, prevValue, value) : value;
  23331. });
  23332. });
  23333. // Note: We need to sort to get a defined output order
  23334. // for tests and for caching generated artifacts...
  23335. return literalArr(Object.keys(mapResult).sort().map(function (attrName) { return literalArr([literal(attrName), literal(mapResult[attrName])]); }));
  23336. }
  23337. function mergeAttributeValue(attrName, attrValue1, attrValue2) {
  23338. if (attrName == CLASS_ATTR$1 || attrName == STYLE_ATTR) {
  23339. return attrValue1 + " " + attrValue2;
  23340. }
  23341. else {
  23342. return attrValue2;
  23343. }
  23344. }
  23345. function callCheckStmt(nodeIndex, exprs) {
  23346. if (exprs.length > 10) {
  23347. return CHECK_VAR.callFn([VIEW_VAR, literal(nodeIndex), literal(1 /* Dynamic */), literalArr(exprs)]);
  23348. }
  23349. else {
  23350. return CHECK_VAR.callFn(__spread([VIEW_VAR, literal(nodeIndex), literal(0 /* Inline */)], exprs));
  23351. }
  23352. }
  23353. function callUnwrapValue(nodeIndex, bindingIdx, expr) {
  23354. return importExpr(Identifiers.unwrapValue).callFn([
  23355. VIEW_VAR, literal(nodeIndex), literal(bindingIdx), expr
  23356. ]);
  23357. }
  23358. function findStaticQueryIds(nodes, result) {
  23359. if (result === void 0) { result = new Map(); }
  23360. nodes.forEach(function (node) {
  23361. var staticQueryIds = new Set();
  23362. var dynamicQueryIds = new Set();
  23363. var queryMatches = undefined;
  23364. if (node instanceof ElementAst) {
  23365. findStaticQueryIds(node.children, result);
  23366. node.children.forEach(function (child) {
  23367. var childData = result.get(child);
  23368. childData.staticQueryIds.forEach(function (queryId) { return staticQueryIds.add(queryId); });
  23369. childData.dynamicQueryIds.forEach(function (queryId) { return dynamicQueryIds.add(queryId); });
  23370. });
  23371. queryMatches = node.queryMatches;
  23372. }
  23373. else if (node instanceof EmbeddedTemplateAst) {
  23374. findStaticQueryIds(node.children, result);
  23375. node.children.forEach(function (child) {
  23376. var childData = result.get(child);
  23377. childData.staticQueryIds.forEach(function (queryId) { return dynamicQueryIds.add(queryId); });
  23378. childData.dynamicQueryIds.forEach(function (queryId) { return dynamicQueryIds.add(queryId); });
  23379. });
  23380. queryMatches = node.queryMatches;
  23381. }
  23382. if (queryMatches) {
  23383. queryMatches.forEach(function (match) { return staticQueryIds.add(match.queryId); });
  23384. }
  23385. dynamicQueryIds.forEach(function (queryId) { return staticQueryIds.delete(queryId); });
  23386. result.set(node, { staticQueryIds: staticQueryIds, dynamicQueryIds: dynamicQueryIds });
  23387. });
  23388. return result;
  23389. }
  23390. function staticViewQueryIds(nodeStaticQueryIds) {
  23391. var staticQueryIds = new Set();
  23392. var dynamicQueryIds = new Set();
  23393. Array.from(nodeStaticQueryIds.values()).forEach(function (entry) {
  23394. entry.staticQueryIds.forEach(function (queryId) { return staticQueryIds.add(queryId); });
  23395. entry.dynamicQueryIds.forEach(function (queryId) { return dynamicQueryIds.add(queryId); });
  23396. });
  23397. dynamicQueryIds.forEach(function (queryId) { return staticQueryIds.delete(queryId); });
  23398. return { staticQueryIds: staticQueryIds, dynamicQueryIds: dynamicQueryIds };
  23399. }
  23400. function elementEventNameAndTarget(eventAst, dirAst) {
  23401. if (eventAst.isAnimation) {
  23402. return {
  23403. name: "@" + eventAst.name + "." + eventAst.phase,
  23404. target: dirAst && dirAst.directive.isComponent ? 'component' : null
  23405. };
  23406. }
  23407. else {
  23408. return eventAst;
  23409. }
  23410. }
  23411. function calcStaticDynamicQueryFlags(queryIds, queryId, query) {
  23412. var flags = 0 /* None */;
  23413. // Note: We only make queries static that query for a single item.
  23414. // This is because of backwards compatibility with the old view compiler...
  23415. if (query.first && shouldResolveAsStaticQuery(queryIds, queryId, query)) {
  23416. flags |= 268435456 /* StaticQuery */;
  23417. }
  23418. else {
  23419. flags |= 536870912 /* DynamicQuery */;
  23420. }
  23421. return flags;
  23422. }
  23423. function shouldResolveAsStaticQuery(queryIds, queryId, query) {
  23424. // If query.static has been set by the user, use that value to determine whether
  23425. // the query is static. If none has been set, sort the query into static/dynamic
  23426. // based on query results (i.e. dynamic if CD needs to run to get all results).
  23427. return query.static ||
  23428. query.static == null &&
  23429. (queryIds.staticQueryIds.has(queryId) || !queryIds.dynamicQueryIds.has(queryId));
  23430. }
  23431. function elementEventFullName(target, name) {
  23432. return target ? target + ":" + name : name;
  23433. }
  23434. /**
  23435. * @license
  23436. * Copyright Google Inc. All Rights Reserved.
  23437. *
  23438. * Use of this source code is governed by an MIT-style license that can be
  23439. * found in the LICENSE file at https://angular.io/license
  23440. */
  23441. /**
  23442. * A container for message extracted from the templates.
  23443. */
  23444. var MessageBundle = /** @class */ (function () {
  23445. function MessageBundle(_htmlParser, _implicitTags, _implicitAttrs, _locale) {
  23446. if (_locale === void 0) { _locale = null; }
  23447. this._htmlParser = _htmlParser;
  23448. this._implicitTags = _implicitTags;
  23449. this._implicitAttrs = _implicitAttrs;
  23450. this._locale = _locale;
  23451. this._messages = [];
  23452. }
  23453. MessageBundle.prototype.updateFromTemplate = function (html, url, interpolationConfig) {
  23454. var _a;
  23455. var htmlParserResult = this._htmlParser.parse(html, url, { tokenizeExpansionForms: true, interpolationConfig: interpolationConfig });
  23456. if (htmlParserResult.errors.length) {
  23457. return htmlParserResult.errors;
  23458. }
  23459. var i18nParserResult = extractMessages(htmlParserResult.rootNodes, interpolationConfig, this._implicitTags, this._implicitAttrs);
  23460. if (i18nParserResult.errors.length) {
  23461. return i18nParserResult.errors;
  23462. }
  23463. (_a = this._messages).push.apply(_a, __spread(i18nParserResult.messages));
  23464. return [];
  23465. };
  23466. // Return the message in the internal format
  23467. // The public (serialized) format might be different, see the `write` method.
  23468. MessageBundle.prototype.getMessages = function () { return this._messages; };
  23469. MessageBundle.prototype.write = function (serializer, filterSources) {
  23470. var messages = {};
  23471. var mapperVisitor = new MapPlaceholderNames();
  23472. // Deduplicate messages based on their ID
  23473. this._messages.forEach(function (message) {
  23474. var _a;
  23475. var id = serializer.digest(message);
  23476. if (!messages.hasOwnProperty(id)) {
  23477. messages[id] = message;
  23478. }
  23479. else {
  23480. (_a = messages[id].sources).push.apply(_a, __spread(message.sources));
  23481. }
  23482. });
  23483. // Transform placeholder names using the serializer mapping
  23484. var msgList = Object.keys(messages).map(function (id) {
  23485. var mapper = serializer.createNameMapper(messages[id]);
  23486. var src = messages[id];
  23487. var nodes = mapper ? mapperVisitor.convert(src.nodes, mapper) : src.nodes;
  23488. var transformedMessage = new Message(nodes, {}, {}, src.meaning, src.description, id);
  23489. transformedMessage.sources = src.sources;
  23490. if (filterSources) {
  23491. transformedMessage.sources.forEach(function (source) { return source.filePath = filterSources(source.filePath); });
  23492. }
  23493. return transformedMessage;
  23494. });
  23495. return serializer.write(msgList, this._locale);
  23496. };
  23497. return MessageBundle;
  23498. }());
  23499. // Transform an i18n AST by renaming the placeholder nodes with the given mapper
  23500. var MapPlaceholderNames = /** @class */ (function (_super) {
  23501. __extends(MapPlaceholderNames, _super);
  23502. function MapPlaceholderNames() {
  23503. return _super !== null && _super.apply(this, arguments) || this;
  23504. }
  23505. MapPlaceholderNames.prototype.convert = function (nodes, mapper) {
  23506. var _this = this;
  23507. return mapper ? nodes.map(function (n) { return n.visit(_this, mapper); }) : nodes;
  23508. };
  23509. MapPlaceholderNames.prototype.visitTagPlaceholder = function (ph, mapper) {
  23510. var _this = this;
  23511. var startName = mapper.toPublicName(ph.startName);
  23512. var closeName = ph.closeName ? mapper.toPublicName(ph.closeName) : ph.closeName;
  23513. var children = ph.children.map(function (n) { return n.visit(_this, mapper); });
  23514. return new TagPlaceholder(ph.tag, ph.attrs, startName, closeName, children, ph.isVoid, ph.sourceSpan);
  23515. };
  23516. MapPlaceholderNames.prototype.visitPlaceholder = function (ph, mapper) {
  23517. return new Placeholder(ph.value, mapper.toPublicName(ph.name), ph.sourceSpan);
  23518. };
  23519. MapPlaceholderNames.prototype.visitIcuPlaceholder = function (ph, mapper) {
  23520. return new IcuPlaceholder(ph.value, mapper.toPublicName(ph.name), ph.sourceSpan);
  23521. };
  23522. return MapPlaceholderNames;
  23523. }(CloneVisitor));
  23524. /**
  23525. * @license
  23526. * Copyright Google Inc. All Rights Reserved.
  23527. *
  23528. * Use of this source code is governed by an MIT-style license that can be
  23529. * found in the LICENSE file at https://angular.io/license
  23530. */
  23531. var GeneratedFile = /** @class */ (function () {
  23532. function GeneratedFile(srcFileUrl, genFileUrl, sourceOrStmts) {
  23533. this.srcFileUrl = srcFileUrl;
  23534. this.genFileUrl = genFileUrl;
  23535. if (typeof sourceOrStmts === 'string') {
  23536. this.source = sourceOrStmts;
  23537. this.stmts = null;
  23538. }
  23539. else {
  23540. this.source = null;
  23541. this.stmts = sourceOrStmts;
  23542. }
  23543. }
  23544. GeneratedFile.prototype.isEquivalent = function (other) {
  23545. if (this.genFileUrl !== other.genFileUrl) {
  23546. return false;
  23547. }
  23548. if (this.source) {
  23549. return this.source === other.source;
  23550. }
  23551. if (other.stmts == null) {
  23552. return false;
  23553. }
  23554. // Note: the constructor guarantees that if this.source is not filled,
  23555. // then this.stmts is.
  23556. return areAllEquivalent(this.stmts, other.stmts);
  23557. };
  23558. return GeneratedFile;
  23559. }());
  23560. function toTypeScript(file, preamble) {
  23561. if (preamble === void 0) { preamble = ''; }
  23562. if (!file.stmts) {
  23563. throw new Error("Illegal state: No stmts present on GeneratedFile " + file.genFileUrl);
  23564. }
  23565. return new TypeScriptEmitter().emitStatements(file.genFileUrl, file.stmts, preamble);
  23566. }
  23567. /**
  23568. * @license
  23569. * Copyright Google Inc. All Rights Reserved.
  23570. *
  23571. * Use of this source code is governed by an MIT-style license that can be
  23572. * found in the LICENSE file at https://angular.io/license
  23573. */
  23574. function listLazyRoutes(moduleMeta, reflector) {
  23575. var e_1, _a, e_2, _b;
  23576. var allLazyRoutes = [];
  23577. try {
  23578. for (var _c = __values(moduleMeta.transitiveModule.providers), _d = _c.next(); !_d.done; _d = _c.next()) {
  23579. var _e = _d.value, provider = _e.provider, module = _e.module;
  23580. if (tokenReference(provider.token) === reflector.ROUTES) {
  23581. var loadChildren = _collectLoadChildren(provider.useValue);
  23582. try {
  23583. for (var loadChildren_1 = __values(loadChildren), loadChildren_1_1 = loadChildren_1.next(); !loadChildren_1_1.done; loadChildren_1_1 = loadChildren_1.next()) {
  23584. var route = loadChildren_1_1.value;
  23585. allLazyRoutes.push(parseLazyRoute(route, reflector, module.reference));
  23586. }
  23587. }
  23588. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  23589. finally {
  23590. try {
  23591. if (loadChildren_1_1 && !loadChildren_1_1.done && (_b = loadChildren_1.return)) _b.call(loadChildren_1);
  23592. }
  23593. finally { if (e_2) throw e_2.error; }
  23594. }
  23595. }
  23596. }
  23597. }
  23598. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  23599. finally {
  23600. try {
  23601. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  23602. }
  23603. finally { if (e_1) throw e_1.error; }
  23604. }
  23605. return allLazyRoutes;
  23606. }
  23607. function _collectLoadChildren(routes, target) {
  23608. var e_3, _a;
  23609. if (target === void 0) { target = []; }
  23610. if (typeof routes === 'string') {
  23611. target.push(routes);
  23612. }
  23613. else if (Array.isArray(routes)) {
  23614. try {
  23615. for (var routes_1 = __values(routes), routes_1_1 = routes_1.next(); !routes_1_1.done; routes_1_1 = routes_1.next()) {
  23616. var route = routes_1_1.value;
  23617. _collectLoadChildren(route, target);
  23618. }
  23619. }
  23620. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  23621. finally {
  23622. try {
  23623. if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
  23624. }
  23625. finally { if (e_3) throw e_3.error; }
  23626. }
  23627. }
  23628. else if (routes.loadChildren) {
  23629. _collectLoadChildren(routes.loadChildren, target);
  23630. }
  23631. else if (routes.children) {
  23632. _collectLoadChildren(routes.children, target);
  23633. }
  23634. return target;
  23635. }
  23636. function parseLazyRoute(route, reflector, module) {
  23637. var _a = __read(route.split('#'), 2), routePath = _a[0], routeName = _a[1];
  23638. var referencedModule = reflector.resolveExternalReference({
  23639. moduleName: routePath,
  23640. name: routeName,
  23641. }, module ? module.filePath : undefined);
  23642. return { route: route, module: module || referencedModule, referencedModule: referencedModule };
  23643. }
  23644. /**
  23645. * @license
  23646. * Copyright Google Inc. All Rights Reserved.
  23647. *
  23648. * Use of this source code is governed by an MIT-style license that can be
  23649. * found in the LICENSE file at https://angular.io/license
  23650. */
  23651. var TS = /^(?!.*\.d\.ts$).*\.ts$/;
  23652. var ResolvedStaticSymbol = /** @class */ (function () {
  23653. function ResolvedStaticSymbol(symbol, metadata) {
  23654. this.symbol = symbol;
  23655. this.metadata = metadata;
  23656. }
  23657. return ResolvedStaticSymbol;
  23658. }());
  23659. var SUPPORTED_SCHEMA_VERSION = 4;
  23660. /**
  23661. * This class is responsible for loading metadata per symbol,
  23662. * and normalizing references between symbols.
  23663. *
  23664. * Internally, it only uses symbols without members,
  23665. * and deduces the values for symbols with members based
  23666. * on these symbols.
  23667. */
  23668. var StaticSymbolResolver = /** @class */ (function () {
  23669. function StaticSymbolResolver(host, staticSymbolCache, summaryResolver, errorRecorder) {
  23670. this.host = host;
  23671. this.staticSymbolCache = staticSymbolCache;
  23672. this.summaryResolver = summaryResolver;
  23673. this.errorRecorder = errorRecorder;
  23674. this.metadataCache = new Map();
  23675. // Note: this will only contain StaticSymbols without members!
  23676. this.resolvedSymbols = new Map();
  23677. this.resolvedFilePaths = new Set();
  23678. // Note: this will only contain StaticSymbols without members!
  23679. this.importAs = new Map();
  23680. this.symbolResourcePaths = new Map();
  23681. this.symbolFromFile = new Map();
  23682. this.knownFileNameToModuleNames = new Map();
  23683. }
  23684. StaticSymbolResolver.prototype.resolveSymbol = function (staticSymbol) {
  23685. if (staticSymbol.members.length > 0) {
  23686. return this._resolveSymbolMembers(staticSymbol);
  23687. }
  23688. // Note: always ask for a summary first,
  23689. // as we might have read shallow metadata via a .d.ts file
  23690. // for the symbol.
  23691. var resultFromSummary = this._resolveSymbolFromSummary(staticSymbol);
  23692. if (resultFromSummary) {
  23693. return resultFromSummary;
  23694. }
  23695. var resultFromCache = this.resolvedSymbols.get(staticSymbol);
  23696. if (resultFromCache) {
  23697. return resultFromCache;
  23698. }
  23699. // Note: Some users use libraries that were not compiled with ngc, i.e. they don't
  23700. // have summaries, only .d.ts files. So we always need to check both, the summary
  23701. // and metadata.
  23702. this._createSymbolsOf(staticSymbol.filePath);
  23703. return this.resolvedSymbols.get(staticSymbol);
  23704. };
  23705. /**
  23706. * getImportAs produces a symbol that can be used to import the given symbol.
  23707. * The import might be different than the symbol if the symbol is exported from
  23708. * a library with a summary; in which case we want to import the symbol from the
  23709. * ngfactory re-export instead of directly to avoid introducing a direct dependency
  23710. * on an otherwise indirect dependency.
  23711. *
  23712. * @param staticSymbol the symbol for which to generate a import symbol
  23713. */
  23714. StaticSymbolResolver.prototype.getImportAs = function (staticSymbol, useSummaries) {
  23715. if (useSummaries === void 0) { useSummaries = true; }
  23716. if (staticSymbol.members.length) {
  23717. var baseSymbol = this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name);
  23718. var baseImportAs = this.getImportAs(baseSymbol, useSummaries);
  23719. return baseImportAs ?
  23720. this.getStaticSymbol(baseImportAs.filePath, baseImportAs.name, staticSymbol.members) :
  23721. null;
  23722. }
  23723. var summarizedFileName = stripSummaryForJitFileSuffix(staticSymbol.filePath);
  23724. if (summarizedFileName !== staticSymbol.filePath) {
  23725. var summarizedName = stripSummaryForJitNameSuffix(staticSymbol.name);
  23726. var baseSymbol = this.getStaticSymbol(summarizedFileName, summarizedName, staticSymbol.members);
  23727. var baseImportAs = this.getImportAs(baseSymbol, useSummaries);
  23728. return baseImportAs ?
  23729. this.getStaticSymbol(summaryForJitFileName(baseImportAs.filePath), summaryForJitName(baseImportAs.name), baseSymbol.members) :
  23730. null;
  23731. }
  23732. var result = (useSummaries && this.summaryResolver.getImportAs(staticSymbol)) || null;
  23733. if (!result) {
  23734. result = this.importAs.get(staticSymbol);
  23735. }
  23736. return result;
  23737. };
  23738. /**
  23739. * getResourcePath produces the path to the original location of the symbol and should
  23740. * be used to determine the relative location of resource references recorded in
  23741. * symbol metadata.
  23742. */
  23743. StaticSymbolResolver.prototype.getResourcePath = function (staticSymbol) {
  23744. return this.symbolResourcePaths.get(staticSymbol) || staticSymbol.filePath;
  23745. };
  23746. /**
  23747. * getTypeArity returns the number of generic type parameters the given symbol
  23748. * has. If the symbol is not a type the result is null.
  23749. */
  23750. StaticSymbolResolver.prototype.getTypeArity = function (staticSymbol) {
  23751. // If the file is a factory/ngsummary file, don't resolve the symbol as doing so would
  23752. // cause the metadata for an factory/ngsummary file to be loaded which doesn't exist.
  23753. // All references to generated classes must include the correct arity whenever
  23754. // generating code.
  23755. if (isGeneratedFile(staticSymbol.filePath)) {
  23756. return null;
  23757. }
  23758. var resolvedSymbol = unwrapResolvedMetadata(this.resolveSymbol(staticSymbol));
  23759. while (resolvedSymbol && resolvedSymbol.metadata instanceof StaticSymbol) {
  23760. resolvedSymbol = unwrapResolvedMetadata(this.resolveSymbol(resolvedSymbol.metadata));
  23761. }
  23762. return (resolvedSymbol && resolvedSymbol.metadata && resolvedSymbol.metadata.arity) || null;
  23763. };
  23764. StaticSymbolResolver.prototype.getKnownModuleName = function (filePath) {
  23765. return this.knownFileNameToModuleNames.get(filePath) || null;
  23766. };
  23767. StaticSymbolResolver.prototype.recordImportAs = function (sourceSymbol, targetSymbol) {
  23768. sourceSymbol.assertNoMembers();
  23769. targetSymbol.assertNoMembers();
  23770. this.importAs.set(sourceSymbol, targetSymbol);
  23771. };
  23772. StaticSymbolResolver.prototype.recordModuleNameForFileName = function (fileName, moduleName) {
  23773. this.knownFileNameToModuleNames.set(fileName, moduleName);
  23774. };
  23775. /**
  23776. * Invalidate all information derived from the given file.
  23777. *
  23778. * @param fileName the file to invalidate
  23779. */
  23780. StaticSymbolResolver.prototype.invalidateFile = function (fileName) {
  23781. var e_1, _a;
  23782. this.metadataCache.delete(fileName);
  23783. this.resolvedFilePaths.delete(fileName);
  23784. var symbols = this.symbolFromFile.get(fileName);
  23785. if (symbols) {
  23786. this.symbolFromFile.delete(fileName);
  23787. try {
  23788. for (var symbols_1 = __values(symbols), symbols_1_1 = symbols_1.next(); !symbols_1_1.done; symbols_1_1 = symbols_1.next()) {
  23789. var symbol = symbols_1_1.value;
  23790. this.resolvedSymbols.delete(symbol);
  23791. this.importAs.delete(symbol);
  23792. this.symbolResourcePaths.delete(symbol);
  23793. }
  23794. }
  23795. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  23796. finally {
  23797. try {
  23798. if (symbols_1_1 && !symbols_1_1.done && (_a = symbols_1.return)) _a.call(symbols_1);
  23799. }
  23800. finally { if (e_1) throw e_1.error; }
  23801. }
  23802. }
  23803. };
  23804. /** @internal */
  23805. StaticSymbolResolver.prototype.ignoreErrorsFor = function (cb) {
  23806. var recorder = this.errorRecorder;
  23807. this.errorRecorder = function () { };
  23808. try {
  23809. return cb();
  23810. }
  23811. finally {
  23812. this.errorRecorder = recorder;
  23813. }
  23814. };
  23815. StaticSymbolResolver.prototype._resolveSymbolMembers = function (staticSymbol) {
  23816. var members = staticSymbol.members;
  23817. var baseResolvedSymbol = this.resolveSymbol(this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name));
  23818. if (!baseResolvedSymbol) {
  23819. return null;
  23820. }
  23821. var baseMetadata = unwrapResolvedMetadata(baseResolvedSymbol.metadata);
  23822. if (baseMetadata instanceof StaticSymbol) {
  23823. return new ResolvedStaticSymbol(staticSymbol, this.getStaticSymbol(baseMetadata.filePath, baseMetadata.name, members));
  23824. }
  23825. else if (baseMetadata && baseMetadata.__symbolic === 'class') {
  23826. if (baseMetadata.statics && members.length === 1) {
  23827. return new ResolvedStaticSymbol(staticSymbol, baseMetadata.statics[members[0]]);
  23828. }
  23829. }
  23830. else {
  23831. var value = baseMetadata;
  23832. for (var i = 0; i < members.length && value; i++) {
  23833. value = value[members[i]];
  23834. }
  23835. return new ResolvedStaticSymbol(staticSymbol, value);
  23836. }
  23837. return null;
  23838. };
  23839. StaticSymbolResolver.prototype._resolveSymbolFromSummary = function (staticSymbol) {
  23840. var summary = this.summaryResolver.resolveSummary(staticSymbol);
  23841. return summary ? new ResolvedStaticSymbol(staticSymbol, summary.metadata) : null;
  23842. };
  23843. /**
  23844. * getStaticSymbol produces a Type whose metadata is known but whose implementation is not loaded.
  23845. * All types passed to the StaticResolver should be pseudo-types returned by this method.
  23846. *
  23847. * @param declarationFile the absolute path of the file where the symbol is declared
  23848. * @param name the name of the type.
  23849. * @param members a symbol for a static member of the named type
  23850. */
  23851. StaticSymbolResolver.prototype.getStaticSymbol = function (declarationFile, name, members) {
  23852. return this.staticSymbolCache.get(declarationFile, name, members);
  23853. };
  23854. /**
  23855. * hasDecorators checks a file's metadata for the presence of decorators without evaluating the
  23856. * metadata.
  23857. *
  23858. * @param filePath the absolute path to examine for decorators.
  23859. * @returns true if any class in the file has a decorator.
  23860. */
  23861. StaticSymbolResolver.prototype.hasDecorators = function (filePath) {
  23862. var metadata = this.getModuleMetadata(filePath);
  23863. if (metadata['metadata']) {
  23864. return Object.keys(metadata['metadata']).some(function (metadataKey) {
  23865. var entry = metadata['metadata'][metadataKey];
  23866. return entry && entry.__symbolic === 'class' && entry.decorators;
  23867. });
  23868. }
  23869. return false;
  23870. };
  23871. StaticSymbolResolver.prototype.getSymbolsOf = function (filePath) {
  23872. var summarySymbols = this.summaryResolver.getSymbolsOf(filePath);
  23873. if (summarySymbols) {
  23874. return summarySymbols;
  23875. }
  23876. // Note: Some users use libraries that were not compiled with ngc, i.e. they don't
  23877. // have summaries, only .d.ts files, but `summaryResolver.isLibraryFile` returns true.
  23878. this._createSymbolsOf(filePath);
  23879. var metadataSymbols = [];
  23880. this.resolvedSymbols.forEach(function (resolvedSymbol) {
  23881. if (resolvedSymbol.symbol.filePath === filePath) {
  23882. metadataSymbols.push(resolvedSymbol.symbol);
  23883. }
  23884. });
  23885. return metadataSymbols;
  23886. };
  23887. StaticSymbolResolver.prototype._createSymbolsOf = function (filePath) {
  23888. var _this = this;
  23889. var e_2, _a;
  23890. if (this.resolvedFilePaths.has(filePath)) {
  23891. return;
  23892. }
  23893. this.resolvedFilePaths.add(filePath);
  23894. var resolvedSymbols = [];
  23895. var metadata = this.getModuleMetadata(filePath);
  23896. if (metadata['importAs']) {
  23897. // Index bundle indices should use the importAs module name defined
  23898. // in the bundle.
  23899. this.knownFileNameToModuleNames.set(filePath, metadata['importAs']);
  23900. }
  23901. // handle the symbols in one of the re-export location
  23902. if (metadata['exports']) {
  23903. var _loop_1 = function (moduleExport) {
  23904. // handle the symbols in the list of explicitly re-exported symbols.
  23905. if (moduleExport.export) {
  23906. moduleExport.export.forEach(function (exportSymbol) {
  23907. var symbolName;
  23908. if (typeof exportSymbol === 'string') {
  23909. symbolName = exportSymbol;
  23910. }
  23911. else {
  23912. symbolName = exportSymbol.as;
  23913. }
  23914. symbolName = unescapeIdentifier(symbolName);
  23915. var symName = symbolName;
  23916. if (typeof exportSymbol !== 'string') {
  23917. symName = unescapeIdentifier(exportSymbol.name);
  23918. }
  23919. var resolvedModule = _this.resolveModule(moduleExport.from, filePath);
  23920. if (resolvedModule) {
  23921. var targetSymbol = _this.getStaticSymbol(resolvedModule, symName);
  23922. var sourceSymbol = _this.getStaticSymbol(filePath, symbolName);
  23923. resolvedSymbols.push(_this.createExport(sourceSymbol, targetSymbol));
  23924. }
  23925. });
  23926. }
  23927. else {
  23928. // handle the symbols via export * directives.
  23929. var resolvedModule = this_1.resolveModule(moduleExport.from, filePath);
  23930. if (resolvedModule) {
  23931. var nestedExports = this_1.getSymbolsOf(resolvedModule);
  23932. nestedExports.forEach(function (targetSymbol) {
  23933. var sourceSymbol = _this.getStaticSymbol(filePath, targetSymbol.name);
  23934. resolvedSymbols.push(_this.createExport(sourceSymbol, targetSymbol));
  23935. });
  23936. }
  23937. }
  23938. };
  23939. var this_1 = this;
  23940. try {
  23941. for (var _b = __values(metadata['exports']), _c = _b.next(); !_c.done; _c = _b.next()) {
  23942. var moduleExport = _c.value;
  23943. _loop_1(moduleExport);
  23944. }
  23945. }
  23946. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  23947. finally {
  23948. try {
  23949. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  23950. }
  23951. finally { if (e_2) throw e_2.error; }
  23952. }
  23953. }
  23954. // handle the actual metadata. Has to be after the exports
  23955. // as there might be collisions in the names, and we want the symbols
  23956. // of the current module to win ofter reexports.
  23957. if (metadata['metadata']) {
  23958. // handle direct declarations of the symbol
  23959. var topLevelSymbolNames_1 = new Set(Object.keys(metadata['metadata']).map(unescapeIdentifier));
  23960. var origins_1 = metadata['origins'] || {};
  23961. Object.keys(metadata['metadata']).forEach(function (metadataKey) {
  23962. var symbolMeta = metadata['metadata'][metadataKey];
  23963. var name = unescapeIdentifier(metadataKey);
  23964. var symbol = _this.getStaticSymbol(filePath, name);
  23965. var origin = origins_1.hasOwnProperty(metadataKey) && origins_1[metadataKey];
  23966. if (origin) {
  23967. // If the symbol is from a bundled index, use the declaration location of the
  23968. // symbol so relative references (such as './my.html') will be calculated
  23969. // correctly.
  23970. var originFilePath = _this.resolveModule(origin, filePath);
  23971. if (!originFilePath) {
  23972. _this.reportError(new Error("Couldn't resolve original symbol for " + origin + " from " + _this.host.getOutputName(filePath)));
  23973. }
  23974. else {
  23975. _this.symbolResourcePaths.set(symbol, originFilePath);
  23976. }
  23977. }
  23978. resolvedSymbols.push(_this.createResolvedSymbol(symbol, filePath, topLevelSymbolNames_1, symbolMeta));
  23979. });
  23980. }
  23981. resolvedSymbols.forEach(function (resolvedSymbol) { return _this.resolvedSymbols.set(resolvedSymbol.symbol, resolvedSymbol); });
  23982. this.symbolFromFile.set(filePath, resolvedSymbols.map(function (resolvedSymbol) { return resolvedSymbol.symbol; }));
  23983. };
  23984. StaticSymbolResolver.prototype.createResolvedSymbol = function (sourceSymbol, topLevelPath, topLevelSymbolNames, metadata) {
  23985. var _this = this;
  23986. // For classes that don't have Angular summaries / metadata,
  23987. // we only keep their arity, but nothing else
  23988. // (e.g. their constructor parameters).
  23989. // We do this to prevent introducing deep imports
  23990. // as we didn't generate .ngfactory.ts files with proper reexports.
  23991. var isTsFile = TS.test(sourceSymbol.filePath);
  23992. if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) && !isTsFile && metadata &&
  23993. metadata['__symbolic'] === 'class') {
  23994. var transformedMeta_1 = { __symbolic: 'class', arity: metadata.arity };
  23995. return new ResolvedStaticSymbol(sourceSymbol, transformedMeta_1);
  23996. }
  23997. var _originalFileMemo;
  23998. var getOriginalName = function () {
  23999. if (!_originalFileMemo) {
  24000. // Guess what the original file name is from the reference. If it has a `.d.ts` extension
  24001. // replace it with `.ts`. If it already has `.ts` just leave it in place. If it doesn't have
  24002. // .ts or .d.ts, append `.ts'. Also, if it is in `node_modules`, trim the `node_module`
  24003. // location as it is not important to finding the file.
  24004. _originalFileMemo =
  24005. _this.host.getOutputName(topLevelPath.replace(/((\.ts)|(\.d\.ts)|)$/, '.ts')
  24006. .replace(/^.*node_modules[/\\]/, ''));
  24007. }
  24008. return _originalFileMemo;
  24009. };
  24010. var self = this;
  24011. var ReferenceTransformer = /** @class */ (function (_super) {
  24012. __extends(ReferenceTransformer, _super);
  24013. function ReferenceTransformer() {
  24014. return _super !== null && _super.apply(this, arguments) || this;
  24015. }
  24016. ReferenceTransformer.prototype.visitStringMap = function (map, functionParams) {
  24017. var symbolic = map['__symbolic'];
  24018. if (symbolic === 'function') {
  24019. var oldLen = functionParams.length;
  24020. functionParams.push.apply(functionParams, __spread((map['parameters'] || [])));
  24021. var result = _super.prototype.visitStringMap.call(this, map, functionParams);
  24022. functionParams.length = oldLen;
  24023. return result;
  24024. }
  24025. else if (symbolic === 'reference') {
  24026. var module = map['module'];
  24027. var name_1 = map['name'] ? unescapeIdentifier(map['name']) : map['name'];
  24028. if (!name_1) {
  24029. return null;
  24030. }
  24031. var filePath = void 0;
  24032. if (module) {
  24033. filePath = self.resolveModule(module, sourceSymbol.filePath);
  24034. if (!filePath) {
  24035. return {
  24036. __symbolic: 'error',
  24037. message: "Could not resolve " + module + " relative to " + self.host.getMetadataFor(sourceSymbol.filePath) + ".",
  24038. line: map['line'],
  24039. character: map['character'],
  24040. fileName: getOriginalName()
  24041. };
  24042. }
  24043. return {
  24044. __symbolic: 'resolved',
  24045. symbol: self.getStaticSymbol(filePath, name_1),
  24046. line: map['line'],
  24047. character: map['character'],
  24048. fileName: getOriginalName()
  24049. };
  24050. }
  24051. else if (functionParams.indexOf(name_1) >= 0) {
  24052. // reference to a function parameter
  24053. return { __symbolic: 'reference', name: name_1 };
  24054. }
  24055. else {
  24056. if (topLevelSymbolNames.has(name_1)) {
  24057. return self.getStaticSymbol(topLevelPath, name_1);
  24058. }
  24059. }
  24060. }
  24061. else if (symbolic === 'error') {
  24062. return __assign({}, map, { fileName: getOriginalName() });
  24063. }
  24064. else {
  24065. return _super.prototype.visitStringMap.call(this, map, functionParams);
  24066. }
  24067. };
  24068. return ReferenceTransformer;
  24069. }(ValueTransformer));
  24070. var transformedMeta = visitValue(metadata, new ReferenceTransformer(), []);
  24071. var unwrappedTransformedMeta = unwrapResolvedMetadata(transformedMeta);
  24072. if (unwrappedTransformedMeta instanceof StaticSymbol) {
  24073. return this.createExport(sourceSymbol, unwrappedTransformedMeta);
  24074. }
  24075. return new ResolvedStaticSymbol(sourceSymbol, transformedMeta);
  24076. };
  24077. StaticSymbolResolver.prototype.createExport = function (sourceSymbol, targetSymbol) {
  24078. sourceSymbol.assertNoMembers();
  24079. targetSymbol.assertNoMembers();
  24080. if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) &&
  24081. this.summaryResolver.isLibraryFile(targetSymbol.filePath)) {
  24082. // This case is for an ng library importing symbols from a plain ts library
  24083. // transitively.
  24084. // Note: We rely on the fact that we discover symbols in the direction
  24085. // from source files to library files
  24086. this.importAs.set(targetSymbol, this.getImportAs(sourceSymbol) || sourceSymbol);
  24087. }
  24088. return new ResolvedStaticSymbol(sourceSymbol, targetSymbol);
  24089. };
  24090. StaticSymbolResolver.prototype.reportError = function (error, context, path) {
  24091. if (this.errorRecorder) {
  24092. this.errorRecorder(error, (context && context.filePath) || path);
  24093. }
  24094. else {
  24095. throw error;
  24096. }
  24097. };
  24098. /**
  24099. * @param module an absolute path to a module file.
  24100. */
  24101. StaticSymbolResolver.prototype.getModuleMetadata = function (module) {
  24102. var moduleMetadata = this.metadataCache.get(module);
  24103. if (!moduleMetadata) {
  24104. var moduleMetadatas = this.host.getMetadataFor(module);
  24105. if (moduleMetadatas) {
  24106. var maxVersion_1 = -1;
  24107. moduleMetadatas.forEach(function (md) {
  24108. if (md && md['version'] > maxVersion_1) {
  24109. maxVersion_1 = md['version'];
  24110. moduleMetadata = md;
  24111. }
  24112. });
  24113. }
  24114. if (!moduleMetadata) {
  24115. moduleMetadata =
  24116. { __symbolic: 'module', version: SUPPORTED_SCHEMA_VERSION, module: module, metadata: {} };
  24117. }
  24118. if (moduleMetadata['version'] != SUPPORTED_SCHEMA_VERSION) {
  24119. var errorMessage = moduleMetadata['version'] == 2 ?
  24120. "Unsupported metadata version " + moduleMetadata['version'] + " for module " + module + ". This module should be compiled with a newer version of ngc" :
  24121. "Metadata version mismatch for module " + this.host.getOutputName(module) + ", found version " + moduleMetadata['version'] + ", expected " + SUPPORTED_SCHEMA_VERSION;
  24122. this.reportError(new Error(errorMessage));
  24123. }
  24124. this.metadataCache.set(module, moduleMetadata);
  24125. }
  24126. return moduleMetadata;
  24127. };
  24128. StaticSymbolResolver.prototype.getSymbolByModule = function (module, symbolName, containingFile) {
  24129. var filePath = this.resolveModule(module, containingFile);
  24130. if (!filePath) {
  24131. this.reportError(new Error("Could not resolve module " + module + (containingFile ? ' relative to ' +
  24132. this.host.getOutputName(containingFile) : '')));
  24133. return this.getStaticSymbol("ERROR:" + module, symbolName);
  24134. }
  24135. return this.getStaticSymbol(filePath, symbolName);
  24136. };
  24137. StaticSymbolResolver.prototype.resolveModule = function (module, containingFile) {
  24138. try {
  24139. return this.host.moduleNameToFileName(module, containingFile);
  24140. }
  24141. catch (e) {
  24142. console.error("Could not resolve module '" + module + "' relative to file " + containingFile);
  24143. this.reportError(e, undefined, containingFile);
  24144. }
  24145. return null;
  24146. };
  24147. return StaticSymbolResolver;
  24148. }());
  24149. // Remove extra underscore from escaped identifier.
  24150. // See https://github.com/Microsoft/TypeScript/blob/master/src/compiler/utilities.ts
  24151. function unescapeIdentifier(identifier) {
  24152. return identifier.startsWith('___') ? identifier.substr(1) : identifier;
  24153. }
  24154. function unwrapResolvedMetadata(metadata) {
  24155. if (metadata && metadata.__symbolic === 'resolved') {
  24156. return metadata.symbol;
  24157. }
  24158. return metadata;
  24159. }
  24160. function serializeSummaries(srcFileName, forJitCtx, summaryResolver, symbolResolver, symbols, types, createExternalSymbolReexports) {
  24161. if (createExternalSymbolReexports === void 0) { createExternalSymbolReexports = false; }
  24162. var toJsonSerializer = new ToJsonSerializer(symbolResolver, summaryResolver, srcFileName);
  24163. // for symbols, we use everything except for the class metadata itself
  24164. // (we keep the statics though), as the class metadata is contained in the
  24165. // CompileTypeSummary.
  24166. symbols.forEach(function (resolvedSymbol) { return toJsonSerializer.addSummary({ symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata }); });
  24167. // Add type summaries.
  24168. types.forEach(function (_a) {
  24169. var summary = _a.summary, metadata = _a.metadata;
  24170. toJsonSerializer.addSummary({ symbol: summary.type.reference, metadata: undefined, type: summary });
  24171. });
  24172. var _a = toJsonSerializer.serialize(createExternalSymbolReexports), json = _a.json, exportAs = _a.exportAs;
  24173. if (forJitCtx) {
  24174. var forJitSerializer_1 = new ForJitSerializer(forJitCtx, symbolResolver, summaryResolver);
  24175. types.forEach(function (_a) {
  24176. var summary = _a.summary, metadata = _a.metadata;
  24177. forJitSerializer_1.addSourceType(summary, metadata);
  24178. });
  24179. toJsonSerializer.unprocessedSymbolSummariesBySymbol.forEach(function (summary) {
  24180. if (summaryResolver.isLibraryFile(summary.symbol.filePath) && summary.type) {
  24181. forJitSerializer_1.addLibType(summary.type);
  24182. }
  24183. });
  24184. forJitSerializer_1.serialize(exportAs);
  24185. }
  24186. return { json: json, exportAs: exportAs };
  24187. }
  24188. function deserializeSummaries(symbolCache, summaryResolver, libraryFileName, json) {
  24189. var deserializer = new FromJsonDeserializer(symbolCache, summaryResolver);
  24190. return deserializer.deserialize(libraryFileName, json);
  24191. }
  24192. function createForJitStub(outputCtx, reference) {
  24193. return createSummaryForJitFunction(outputCtx, reference, NULL_EXPR);
  24194. }
  24195. function createSummaryForJitFunction(outputCtx, reference, value) {
  24196. var fnName = summaryForJitName(reference.name);
  24197. outputCtx.statements.push(fn([], [new ReturnStatement(value)], new ArrayType(DYNAMIC_TYPE)).toDeclStmt(fnName, [
  24198. exports.StmtModifier.Final, exports.StmtModifier.Exported
  24199. ]));
  24200. }
  24201. var ToJsonSerializer = /** @class */ (function (_super) {
  24202. __extends(ToJsonSerializer, _super);
  24203. function ToJsonSerializer(symbolResolver, summaryResolver, srcFileName) {
  24204. var _this = _super.call(this) || this;
  24205. _this.symbolResolver = symbolResolver;
  24206. _this.summaryResolver = summaryResolver;
  24207. _this.srcFileName = srcFileName;
  24208. // Note: This only contains symbols without members.
  24209. _this.symbols = [];
  24210. _this.indexBySymbol = new Map();
  24211. _this.reexportedBy = new Map();
  24212. // This now contains a `__symbol: number` in the place of
  24213. // StaticSymbols, but otherwise has the same shape as the original objects.
  24214. _this.processedSummaryBySymbol = new Map();
  24215. _this.processedSummaries = [];
  24216. _this.unprocessedSymbolSummariesBySymbol = new Map();
  24217. _this.moduleName = symbolResolver.getKnownModuleName(srcFileName);
  24218. return _this;
  24219. }
  24220. ToJsonSerializer.prototype.addSummary = function (summary) {
  24221. var _this = this;
  24222. var unprocessedSummary = this.unprocessedSymbolSummariesBySymbol.get(summary.symbol);
  24223. var processedSummary = this.processedSummaryBySymbol.get(summary.symbol);
  24224. if (!unprocessedSummary) {
  24225. unprocessedSummary = { symbol: summary.symbol, metadata: undefined };
  24226. this.unprocessedSymbolSummariesBySymbol.set(summary.symbol, unprocessedSummary);
  24227. processedSummary = { symbol: this.processValue(summary.symbol, 0 /* None */) };
  24228. this.processedSummaries.push(processedSummary);
  24229. this.processedSummaryBySymbol.set(summary.symbol, processedSummary);
  24230. }
  24231. if (!unprocessedSummary.metadata && summary.metadata) {
  24232. var metadata_1 = summary.metadata || {};
  24233. if (metadata_1.__symbolic === 'class') {
  24234. // For classes, we keep everything except their class decorators.
  24235. // We need to keep e.g. the ctor args, method names, method decorators
  24236. // so that the class can be extended in another compilation unit.
  24237. // We don't keep the class decorators as
  24238. // 1) they refer to data
  24239. // that should not cause a rebuild of downstream compilation units
  24240. // (e.g. inline templates of @Component, or @NgModule.declarations)
  24241. // 2) their data is already captured in TypeSummaries, e.g. DirectiveSummary.
  24242. var clone_1 = {};
  24243. Object.keys(metadata_1).forEach(function (propName) {
  24244. if (propName !== 'decorators') {
  24245. clone_1[propName] = metadata_1[propName];
  24246. }
  24247. });
  24248. metadata_1 = clone_1;
  24249. }
  24250. else if (isCall(metadata_1)) {
  24251. if (!isFunctionCall(metadata_1) && !isMethodCallOnVariable(metadata_1)) {
  24252. // Don't store complex calls as we won't be able to simplify them anyways later on.
  24253. metadata_1 = {
  24254. __symbolic: 'error',
  24255. message: 'Complex function calls are not supported.',
  24256. };
  24257. }
  24258. }
  24259. // Note: We need to keep storing ctor calls for e.g.
  24260. // `export const x = new InjectionToken(...)`
  24261. unprocessedSummary.metadata = metadata_1;
  24262. processedSummary.metadata = this.processValue(metadata_1, 1 /* ResolveValue */);
  24263. if (metadata_1 instanceof StaticSymbol &&
  24264. this.summaryResolver.isLibraryFile(metadata_1.filePath)) {
  24265. var declarationSymbol = this.symbols[this.indexBySymbol.get(metadata_1)];
  24266. if (!isLoweredSymbol(declarationSymbol.name)) {
  24267. // Note: symbols that were introduced during codegen in the user file can have a reexport
  24268. // if a user used `export *`. However, we can't rely on this as tsickle will change
  24269. // `export *` into named exports, using only the information from the typechecker.
  24270. // As we introduce the new symbols after typecheck, Tsickle does not know about them,
  24271. // and omits them when expanding `export *`.
  24272. // So we have to keep reexporting these symbols manually via .ngfactory files.
  24273. this.reexportedBy.set(declarationSymbol, summary.symbol);
  24274. }
  24275. }
  24276. }
  24277. if (!unprocessedSummary.type && summary.type) {
  24278. unprocessedSummary.type = summary.type;
  24279. // Note: We don't add the summaries of all referenced symbols as for the ResolvedSymbols,
  24280. // as the type summaries already contain the transitive data that they require
  24281. // (in a minimal way).
  24282. processedSummary.type = this.processValue(summary.type, 0 /* None */);
  24283. // except for reexported directives / pipes, so we need to store
  24284. // their summaries explicitly.
  24285. if (summary.type.summaryKind === exports.CompileSummaryKind.NgModule) {
  24286. var ngModuleSummary = summary.type;
  24287. ngModuleSummary.exportedDirectives.concat(ngModuleSummary.exportedPipes).forEach(function (id) {
  24288. var symbol = id.reference;
  24289. if (_this.summaryResolver.isLibraryFile(symbol.filePath) &&
  24290. !_this.unprocessedSymbolSummariesBySymbol.has(symbol)) {
  24291. var summary_1 = _this.summaryResolver.resolveSummary(symbol);
  24292. if (summary_1) {
  24293. _this.addSummary(summary_1);
  24294. }
  24295. }
  24296. });
  24297. }
  24298. }
  24299. };
  24300. /**
  24301. * @param createExternalSymbolReexports Whether external static symbols should be re-exported.
  24302. * This can be enabled if external symbols should be re-exported by the current module in
  24303. * order to avoid dynamically generated module dependencies which can break strict dependency
  24304. * enforcements (as in Google3). Read more here: https://github.com/angular/angular/issues/25644
  24305. */
  24306. ToJsonSerializer.prototype.serialize = function (createExternalSymbolReexports) {
  24307. var _this = this;
  24308. var exportAs = [];
  24309. var json = JSON.stringify({
  24310. moduleName: this.moduleName,
  24311. summaries: this.processedSummaries,
  24312. symbols: this.symbols.map(function (symbol, index) {
  24313. symbol.assertNoMembers();
  24314. var importAs = undefined;
  24315. if (_this.summaryResolver.isLibraryFile(symbol.filePath)) {
  24316. var reexportSymbol = _this.reexportedBy.get(symbol);
  24317. if (reexportSymbol) {
  24318. // In case the given external static symbol is already manually exported by the
  24319. // user, we just proxy the external static symbol reference to the manual export.
  24320. // This ensures that the AOT compiler imports the external symbol through the
  24321. // user export and does not introduce another dependency which is not needed.
  24322. importAs = _this.indexBySymbol.get(reexportSymbol);
  24323. }
  24324. else if (createExternalSymbolReexports) {
  24325. // In this case, the given external static symbol is *not* manually exported by
  24326. // the user, and we manually create a re-export in the factory file so that we
  24327. // don't introduce another module dependency. This is useful when running within
  24328. // Bazel so that the AOT compiler does not introduce any module dependencies
  24329. // which can break the strict dependency enforcement. (e.g. as in Google3)
  24330. // Read more about this here: https://github.com/angular/angular/issues/25644
  24331. var summary = _this.unprocessedSymbolSummariesBySymbol.get(symbol);
  24332. if (!summary || !summary.metadata || summary.metadata.__symbolic !== 'interface') {
  24333. importAs = symbol.name + "_" + index;
  24334. exportAs.push({ symbol: symbol, exportAs: importAs });
  24335. }
  24336. }
  24337. }
  24338. return {
  24339. __symbol: index,
  24340. name: symbol.name,
  24341. filePath: _this.summaryResolver.toSummaryFileName(symbol.filePath, _this.srcFileName),
  24342. importAs: importAs
  24343. };
  24344. })
  24345. });
  24346. return { json: json, exportAs: exportAs };
  24347. };
  24348. ToJsonSerializer.prototype.processValue = function (value, flags) {
  24349. return visitValue(value, this, flags);
  24350. };
  24351. ToJsonSerializer.prototype.visitOther = function (value, context) {
  24352. if (value instanceof StaticSymbol) {
  24353. var baseSymbol = this.symbolResolver.getStaticSymbol(value.filePath, value.name);
  24354. var index = this.visitStaticSymbol(baseSymbol, context);
  24355. return { __symbol: index, members: value.members };
  24356. }
  24357. };
  24358. /**
  24359. * Strip line and character numbers from ngsummaries.
  24360. * Emitting them causes white spaces changes to retrigger upstream
  24361. * recompilations in bazel.
  24362. * TODO: find out a way to have line and character numbers in errors without
  24363. * excessive recompilation in bazel.
  24364. */
  24365. ToJsonSerializer.prototype.visitStringMap = function (map, context) {
  24366. if (map['__symbolic'] === 'resolved') {
  24367. return visitValue(map['symbol'], this, context);
  24368. }
  24369. if (map['__symbolic'] === 'error') {
  24370. delete map['line'];
  24371. delete map['character'];
  24372. }
  24373. return _super.prototype.visitStringMap.call(this, map, context);
  24374. };
  24375. /**
  24376. * Returns null if the options.resolveValue is true, and the summary for the symbol
  24377. * resolved to a type or could not be resolved.
  24378. */
  24379. ToJsonSerializer.prototype.visitStaticSymbol = function (baseSymbol, flags) {
  24380. var index = this.indexBySymbol.get(baseSymbol);
  24381. var summary = null;
  24382. if (flags & 1 /* ResolveValue */ &&
  24383. this.summaryResolver.isLibraryFile(baseSymbol.filePath)) {
  24384. if (this.unprocessedSymbolSummariesBySymbol.has(baseSymbol)) {
  24385. // the summary for this symbol was already added
  24386. // -> nothing to do.
  24387. return index;
  24388. }
  24389. summary = this.loadSummary(baseSymbol);
  24390. if (summary && summary.metadata instanceof StaticSymbol) {
  24391. // The summary is a reexport
  24392. index = this.visitStaticSymbol(summary.metadata, flags);
  24393. // reset the summary as it is just a reexport, so we don't want to store it.
  24394. summary = null;
  24395. }
  24396. }
  24397. else if (index != null) {
  24398. // Note: == on purpose to compare with undefined!
  24399. // No summary and the symbol is already added -> nothing to do.
  24400. return index;
  24401. }
  24402. // Note: == on purpose to compare with undefined!
  24403. if (index == null) {
  24404. index = this.symbols.length;
  24405. this.symbols.push(baseSymbol);
  24406. }
  24407. this.indexBySymbol.set(baseSymbol, index);
  24408. if (summary) {
  24409. this.addSummary(summary);
  24410. }
  24411. return index;
  24412. };
  24413. ToJsonSerializer.prototype.loadSummary = function (symbol) {
  24414. var summary = this.summaryResolver.resolveSummary(symbol);
  24415. if (!summary) {
  24416. // some symbols might originate from a plain typescript library
  24417. // that just exported .d.ts and .metadata.json files, i.e. where no summary
  24418. // files were created.
  24419. var resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
  24420. if (resolvedSymbol) {
  24421. summary = { symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata };
  24422. }
  24423. }
  24424. return summary;
  24425. };
  24426. return ToJsonSerializer;
  24427. }(ValueTransformer));
  24428. var ForJitSerializer = /** @class */ (function () {
  24429. function ForJitSerializer(outputCtx, symbolResolver, summaryResolver) {
  24430. this.outputCtx = outputCtx;
  24431. this.symbolResolver = symbolResolver;
  24432. this.summaryResolver = summaryResolver;
  24433. this.data = [];
  24434. }
  24435. ForJitSerializer.prototype.addSourceType = function (summary, metadata) {
  24436. this.data.push({ summary: summary, metadata: metadata, isLibrary: false });
  24437. };
  24438. ForJitSerializer.prototype.addLibType = function (summary) {
  24439. this.data.push({ summary: summary, metadata: null, isLibrary: true });
  24440. };
  24441. ForJitSerializer.prototype.serialize = function (exportAsArr) {
  24442. var _this = this;
  24443. var e_1, _a, e_2, _b, e_3, _c;
  24444. var exportAsBySymbol = new Map();
  24445. try {
  24446. for (var exportAsArr_1 = __values(exportAsArr), exportAsArr_1_1 = exportAsArr_1.next(); !exportAsArr_1_1.done; exportAsArr_1_1 = exportAsArr_1.next()) {
  24447. var _d = exportAsArr_1_1.value, symbol = _d.symbol, exportAs = _d.exportAs;
  24448. exportAsBySymbol.set(symbol, exportAs);
  24449. }
  24450. }
  24451. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  24452. finally {
  24453. try {
  24454. if (exportAsArr_1_1 && !exportAsArr_1_1.done && (_a = exportAsArr_1.return)) _a.call(exportAsArr_1);
  24455. }
  24456. finally { if (e_1) throw e_1.error; }
  24457. }
  24458. var ngModuleSymbols = new Set();
  24459. try {
  24460. for (var _e = __values(this.data), _f = _e.next(); !_f.done; _f = _e.next()) {
  24461. var _g = _f.value, summary = _g.summary, metadata = _g.metadata, isLibrary = _g.isLibrary;
  24462. if (summary.summaryKind === exports.CompileSummaryKind.NgModule) {
  24463. // collect the symbols that refer to NgModule classes.
  24464. // Note: we can't just rely on `summary.type.summaryKind` to determine this as
  24465. // we don't add the summaries of all referenced symbols when we serialize type summaries.
  24466. // See serializeSummaries for details.
  24467. ngModuleSymbols.add(summary.type.reference);
  24468. var modSummary = summary;
  24469. try {
  24470. for (var _h = __values(modSummary.modules), _j = _h.next(); !_j.done; _j = _h.next()) {
  24471. var mod = _j.value;
  24472. ngModuleSymbols.add(mod.reference);
  24473. }
  24474. }
  24475. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  24476. finally {
  24477. try {
  24478. if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
  24479. }
  24480. finally { if (e_3) throw e_3.error; }
  24481. }
  24482. }
  24483. if (!isLibrary) {
  24484. var fnName = summaryForJitName(summary.type.reference.name);
  24485. createSummaryForJitFunction(this.outputCtx, summary.type.reference, this.serializeSummaryWithDeps(summary, metadata));
  24486. }
  24487. }
  24488. }
  24489. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  24490. finally {
  24491. try {
  24492. if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
  24493. }
  24494. finally { if (e_2) throw e_2.error; }
  24495. }
  24496. ngModuleSymbols.forEach(function (ngModuleSymbol) {
  24497. if (_this.summaryResolver.isLibraryFile(ngModuleSymbol.filePath)) {
  24498. var exportAs = exportAsBySymbol.get(ngModuleSymbol) || ngModuleSymbol.name;
  24499. var jitExportAsName = summaryForJitName(exportAs);
  24500. _this.outputCtx.statements.push(variable(jitExportAsName)
  24501. .set(_this.serializeSummaryRef(ngModuleSymbol))
  24502. .toDeclStmt(null, [exports.StmtModifier.Exported]));
  24503. }
  24504. });
  24505. };
  24506. ForJitSerializer.prototype.serializeSummaryWithDeps = function (summary, metadata) {
  24507. var _this = this;
  24508. var expressions = [this.serializeSummary(summary)];
  24509. var providers = [];
  24510. if (metadata instanceof CompileNgModuleMetadata) {
  24511. expressions.push.apply(expressions, __spread(
  24512. // For directives / pipes, we only add the declared ones,
  24513. // and rely on transitively importing NgModules to get the transitive
  24514. // summaries.
  24515. metadata.declaredDirectives.concat(metadata.declaredPipes)
  24516. .map(function (type) { return type.reference; })
  24517. // For modules,
  24518. // we also add the summaries for modules
  24519. // from libraries.
  24520. // This is ok as we produce reexports for all transitive modules.
  24521. .concat(metadata.transitiveModule.modules.map(function (type) { return type.reference; })
  24522. .filter(function (ref) { return ref !== metadata.type.reference; }))
  24523. .map(function (ref) { return _this.serializeSummaryRef(ref); })));
  24524. // Note: We don't use `NgModuleSummary.providers`, as that one is transitive,
  24525. // and we already have transitive modules.
  24526. providers = metadata.providers;
  24527. }
  24528. else if (summary.summaryKind === exports.CompileSummaryKind.Directive) {
  24529. var dirSummary = summary;
  24530. providers = dirSummary.providers.concat(dirSummary.viewProviders);
  24531. }
  24532. // Note: We can't just refer to the `ngsummary.ts` files for `useClass` providers (as we do for
  24533. // declaredDirectives / declaredPipes), as we allow
  24534. // providers without ctor arguments to skip the `@Injectable` decorator,
  24535. // i.e. we didn't generate .ngsummary.ts files for these.
  24536. expressions.push.apply(expressions, __spread(providers.filter(function (provider) { return !!provider.useClass; }).map(function (provider) { return _this.serializeSummary({
  24537. summaryKind: exports.CompileSummaryKind.Injectable, type: provider.useClass
  24538. }); })));
  24539. return literalArr(expressions);
  24540. };
  24541. ForJitSerializer.prototype.serializeSummaryRef = function (typeSymbol) {
  24542. var jitImportedSymbol = this.symbolResolver.getStaticSymbol(summaryForJitFileName(typeSymbol.filePath), summaryForJitName(typeSymbol.name));
  24543. return this.outputCtx.importExpr(jitImportedSymbol);
  24544. };
  24545. ForJitSerializer.prototype.serializeSummary = function (data) {
  24546. var outputCtx = this.outputCtx;
  24547. var Transformer = /** @class */ (function () {
  24548. function Transformer() {
  24549. }
  24550. Transformer.prototype.visitArray = function (arr, context) {
  24551. var _this = this;
  24552. return literalArr(arr.map(function (entry) { return visitValue(entry, _this, context); }));
  24553. };
  24554. Transformer.prototype.visitStringMap = function (map, context) {
  24555. var _this = this;
  24556. return new LiteralMapExpr(Object.keys(map).map(function (key) { return new LiteralMapEntry(key, visitValue(map[key], _this, context), false); }));
  24557. };
  24558. Transformer.prototype.visitPrimitive = function (value, context) { return literal(value); };
  24559. Transformer.prototype.visitOther = function (value, context) {
  24560. if (value instanceof StaticSymbol) {
  24561. return outputCtx.importExpr(value);
  24562. }
  24563. else {
  24564. throw new Error("Illegal State: Encountered value " + value);
  24565. }
  24566. };
  24567. return Transformer;
  24568. }());
  24569. return visitValue(data, new Transformer(), null);
  24570. };
  24571. return ForJitSerializer;
  24572. }());
  24573. var FromJsonDeserializer = /** @class */ (function (_super) {
  24574. __extends(FromJsonDeserializer, _super);
  24575. function FromJsonDeserializer(symbolCache, summaryResolver) {
  24576. var _this = _super.call(this) || this;
  24577. _this.symbolCache = symbolCache;
  24578. _this.summaryResolver = summaryResolver;
  24579. return _this;
  24580. }
  24581. FromJsonDeserializer.prototype.deserialize = function (libraryFileName, json) {
  24582. var _this = this;
  24583. var data = JSON.parse(json);
  24584. var allImportAs = [];
  24585. this.symbols = data.symbols.map(function (serializedSymbol) { return _this.symbolCache.get(_this.summaryResolver.fromSummaryFileName(serializedSymbol.filePath, libraryFileName), serializedSymbol.name); });
  24586. data.symbols.forEach(function (serializedSymbol, index) {
  24587. var symbol = _this.symbols[index];
  24588. var importAs = serializedSymbol.importAs;
  24589. if (typeof importAs === 'number') {
  24590. allImportAs.push({ symbol: symbol, importAs: _this.symbols[importAs] });
  24591. }
  24592. else if (typeof importAs === 'string') {
  24593. allImportAs.push({ symbol: symbol, importAs: _this.symbolCache.get(ngfactoryFilePath(libraryFileName), importAs) });
  24594. }
  24595. });
  24596. var summaries = visitValue(data.summaries, this, null);
  24597. return { moduleName: data.moduleName, summaries: summaries, importAs: allImportAs };
  24598. };
  24599. FromJsonDeserializer.prototype.visitStringMap = function (map, context) {
  24600. if ('__symbol' in map) {
  24601. var baseSymbol = this.symbols[map['__symbol']];
  24602. var members = map['members'];
  24603. return members.length ? this.symbolCache.get(baseSymbol.filePath, baseSymbol.name, members) :
  24604. baseSymbol;
  24605. }
  24606. else {
  24607. return _super.prototype.visitStringMap.call(this, map, context);
  24608. }
  24609. };
  24610. return FromJsonDeserializer;
  24611. }(ValueTransformer));
  24612. function isCall(metadata) {
  24613. return metadata && metadata.__symbolic === 'call';
  24614. }
  24615. function isFunctionCall(metadata) {
  24616. return isCall(metadata) && unwrapResolvedMetadata(metadata.expression) instanceof StaticSymbol;
  24617. }
  24618. function isMethodCallOnVariable(metadata) {
  24619. return isCall(metadata) && metadata.expression && metadata.expression.__symbolic === 'select' &&
  24620. unwrapResolvedMetadata(metadata.expression.expression) instanceof StaticSymbol;
  24621. }
  24622. /**
  24623. * @license
  24624. * Copyright Google Inc. All Rights Reserved.
  24625. *
  24626. * Use of this source code is governed by an MIT-style license that can be
  24627. * found in the LICENSE file at https://angular.io/license
  24628. */
  24629. var AotCompiler = /** @class */ (function () {
  24630. function AotCompiler(_config, _options, _host, reflector, _metadataResolver, _templateParser, _styleCompiler, _viewCompiler, _typeCheckCompiler, _ngModuleCompiler, _injectableCompiler, _outputEmitter, _summaryResolver, _symbolResolver) {
  24631. this._config = _config;
  24632. this._options = _options;
  24633. this._host = _host;
  24634. this.reflector = reflector;
  24635. this._metadataResolver = _metadataResolver;
  24636. this._templateParser = _templateParser;
  24637. this._styleCompiler = _styleCompiler;
  24638. this._viewCompiler = _viewCompiler;
  24639. this._typeCheckCompiler = _typeCheckCompiler;
  24640. this._ngModuleCompiler = _ngModuleCompiler;
  24641. this._injectableCompiler = _injectableCompiler;
  24642. this._outputEmitter = _outputEmitter;
  24643. this._summaryResolver = _summaryResolver;
  24644. this._symbolResolver = _symbolResolver;
  24645. this._templateAstCache = new Map();
  24646. this._analyzedFiles = new Map();
  24647. this._analyzedFilesForInjectables = new Map();
  24648. }
  24649. AotCompiler.prototype.clearCache = function () { this._metadataResolver.clearCache(); };
  24650. AotCompiler.prototype.analyzeModulesSync = function (rootFiles) {
  24651. var _this = this;
  24652. var analyzeResult = analyzeAndValidateNgModules(rootFiles, this._host, this._symbolResolver, this._metadataResolver);
  24653. analyzeResult.ngModules.forEach(function (ngModule) { return _this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, true); });
  24654. return analyzeResult;
  24655. };
  24656. AotCompiler.prototype.analyzeModulesAsync = function (rootFiles) {
  24657. var _this = this;
  24658. var analyzeResult = analyzeAndValidateNgModules(rootFiles, this._host, this._symbolResolver, this._metadataResolver);
  24659. return Promise
  24660. .all(analyzeResult.ngModules.map(function (ngModule) { return _this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false); }))
  24661. .then(function () { return analyzeResult; });
  24662. };
  24663. AotCompiler.prototype._analyzeFile = function (fileName) {
  24664. var analyzedFile = this._analyzedFiles.get(fileName);
  24665. if (!analyzedFile) {
  24666. analyzedFile =
  24667. analyzeFile(this._host, this._symbolResolver, this._metadataResolver, fileName);
  24668. this._analyzedFiles.set(fileName, analyzedFile);
  24669. }
  24670. return analyzedFile;
  24671. };
  24672. AotCompiler.prototype._analyzeFileForInjectables = function (fileName) {
  24673. var analyzedFile = this._analyzedFilesForInjectables.get(fileName);
  24674. if (!analyzedFile) {
  24675. analyzedFile = analyzeFileForInjectables(this._host, this._symbolResolver, this._metadataResolver, fileName);
  24676. this._analyzedFilesForInjectables.set(fileName, analyzedFile);
  24677. }
  24678. return analyzedFile;
  24679. };
  24680. AotCompiler.prototype.findGeneratedFileNames = function (fileName) {
  24681. var _this = this;
  24682. var genFileNames = [];
  24683. var file = this._analyzeFile(fileName);
  24684. // Make sure we create a .ngfactory if we have a injectable/directive/pipe/NgModule
  24685. // or a reference to a non source file.
  24686. // Note: This is overestimating the required .ngfactory files as the real calculation is harder.
  24687. // Only do this for StubEmitFlags.Basic, as adding a type check block
  24688. // does not change this file (as we generate type check blocks based on NgModules).
  24689. if (this._options.allowEmptyCodegenFiles || file.directives.length || file.pipes.length ||
  24690. file.injectables.length || file.ngModules.length || file.exportsNonSourceFiles) {
  24691. genFileNames.push(ngfactoryFilePath(file.fileName, true));
  24692. if (this._options.enableSummariesForJit) {
  24693. genFileNames.push(summaryForJitFileName(file.fileName, true));
  24694. }
  24695. }
  24696. var fileSuffix = normalizeGenFileSuffix(splitTypescriptSuffix(file.fileName, true)[1]);
  24697. file.directives.forEach(function (dirSymbol) {
  24698. var compMeta = _this._metadataResolver.getNonNormalizedDirectiveMetadata(dirSymbol).metadata;
  24699. if (!compMeta.isComponent) {
  24700. return;
  24701. }
  24702. // Note: compMeta is a component and therefore template is non null.
  24703. compMeta.template.styleUrls.forEach(function (styleUrl) {
  24704. var normalizedUrl = _this._host.resourceNameToFileName(styleUrl, file.fileName);
  24705. if (!normalizedUrl) {
  24706. throw syntaxError("Couldn't resolve resource " + styleUrl + " relative to " + file.fileName);
  24707. }
  24708. var needsShim = (compMeta.template.encapsulation ||
  24709. _this._config.defaultEncapsulation) === ViewEncapsulation.Emulated;
  24710. genFileNames.push(_stylesModuleUrl(normalizedUrl, needsShim, fileSuffix));
  24711. if (_this._options.allowEmptyCodegenFiles) {
  24712. genFileNames.push(_stylesModuleUrl(normalizedUrl, !needsShim, fileSuffix));
  24713. }
  24714. });
  24715. });
  24716. return genFileNames;
  24717. };
  24718. AotCompiler.prototype.emitBasicStub = function (genFileName, originalFileName) {
  24719. var outputCtx = this._createOutputContext(genFileName);
  24720. if (genFileName.endsWith('.ngfactory.ts')) {
  24721. if (!originalFileName) {
  24722. throw new Error("Assertion error: require the original file for .ngfactory.ts stubs. File: " + genFileName);
  24723. }
  24724. var originalFile = this._analyzeFile(originalFileName);
  24725. this._createNgFactoryStub(outputCtx, originalFile, 1 /* Basic */);
  24726. }
  24727. else if (genFileName.endsWith('.ngsummary.ts')) {
  24728. if (this._options.enableSummariesForJit) {
  24729. if (!originalFileName) {
  24730. throw new Error("Assertion error: require the original file for .ngsummary.ts stubs. File: " + genFileName);
  24731. }
  24732. var originalFile = this._analyzeFile(originalFileName);
  24733. _createEmptyStub(outputCtx);
  24734. originalFile.ngModules.forEach(function (ngModule) {
  24735. // create exports that user code can reference
  24736. createForJitStub(outputCtx, ngModule.type.reference);
  24737. });
  24738. }
  24739. }
  24740. else if (genFileName.endsWith('.ngstyle.ts')) {
  24741. _createEmptyStub(outputCtx);
  24742. }
  24743. // Note: for the stubs, we don't need a property srcFileUrl,
  24744. // as later on in emitAllImpls we will create the proper GeneratedFiles with the
  24745. // correct srcFileUrl.
  24746. // This is good as e.g. for .ngstyle.ts files we can't derive
  24747. // the url of components based on the genFileUrl.
  24748. return this._codegenSourceModule('unknown', outputCtx);
  24749. };
  24750. AotCompiler.prototype.emitTypeCheckStub = function (genFileName, originalFileName) {
  24751. var originalFile = this._analyzeFile(originalFileName);
  24752. var outputCtx = this._createOutputContext(genFileName);
  24753. if (genFileName.endsWith('.ngfactory.ts')) {
  24754. this._createNgFactoryStub(outputCtx, originalFile, 2 /* TypeCheck */);
  24755. }
  24756. return outputCtx.statements.length > 0 ?
  24757. this._codegenSourceModule(originalFile.fileName, outputCtx) :
  24758. null;
  24759. };
  24760. AotCompiler.prototype.loadFilesAsync = function (fileNames, tsFiles) {
  24761. var _this = this;
  24762. var files = fileNames.map(function (fileName) { return _this._analyzeFile(fileName); });
  24763. var loadingPromises = [];
  24764. files.forEach(function (file) { return file.ngModules.forEach(function (ngModule) {
  24765. return loadingPromises.push(_this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false));
  24766. }); });
  24767. var analyzedInjectables = tsFiles.map(function (tsFile) { return _this._analyzeFileForInjectables(tsFile); });
  24768. return Promise.all(loadingPromises).then(function (_) { return ({
  24769. analyzedModules: mergeAndValidateNgFiles(files),
  24770. analyzedInjectables: analyzedInjectables,
  24771. }); });
  24772. };
  24773. AotCompiler.prototype.loadFilesSync = function (fileNames, tsFiles) {
  24774. var _this = this;
  24775. var files = fileNames.map(function (fileName) { return _this._analyzeFile(fileName); });
  24776. files.forEach(function (file) { return file.ngModules.forEach(function (ngModule) { return _this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, true); }); });
  24777. var analyzedInjectables = tsFiles.map(function (tsFile) { return _this._analyzeFileForInjectables(tsFile); });
  24778. return {
  24779. analyzedModules: mergeAndValidateNgFiles(files),
  24780. analyzedInjectables: analyzedInjectables,
  24781. };
  24782. };
  24783. AotCompiler.prototype._createNgFactoryStub = function (outputCtx, file, emitFlags) {
  24784. var _this = this;
  24785. var componentId = 0;
  24786. file.ngModules.forEach(function (ngModuleMeta, ngModuleIndex) {
  24787. // Note: the code below needs to executed for StubEmitFlags.Basic and StubEmitFlags.TypeCheck,
  24788. // so we don't change the .ngfactory file too much when adding the type-check block.
  24789. // create exports that user code can reference
  24790. _this._ngModuleCompiler.createStub(outputCtx, ngModuleMeta.type.reference);
  24791. // add references to the symbols from the metadata.
  24792. // These can be used by the type check block for components,
  24793. // and they also cause TypeScript to include these files into the program too,
  24794. // which will make them part of the analyzedFiles.
  24795. 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]));
  24796. var externalReferenceVars = new Map();
  24797. externalReferences.forEach(function (ref, typeIndex) {
  24798. externalReferenceVars.set(ref, "_decl" + ngModuleIndex + "_" + typeIndex);
  24799. });
  24800. externalReferenceVars.forEach(function (varName, reference) {
  24801. outputCtx.statements.push(variable(varName)
  24802. .set(NULL_EXPR.cast(DYNAMIC_TYPE))
  24803. .toDeclStmt(expressionType(outputCtx.importExpr(reference, /* typeParams */ null, /* useSummaries */ false))));
  24804. });
  24805. if (emitFlags & 2 /* TypeCheck */) {
  24806. // add the type-check block for all components of the NgModule
  24807. ngModuleMeta.declaredDirectives.forEach(function (dirId) {
  24808. var compMeta = _this._metadataResolver.getDirectiveMetadata(dirId.reference);
  24809. if (!compMeta.isComponent) {
  24810. return;
  24811. }
  24812. componentId++;
  24813. _this._createTypeCheckBlock(outputCtx, compMeta.type.reference.name + "_Host_" + componentId, ngModuleMeta, _this._metadataResolver.getHostComponentMetadata(compMeta), [compMeta.type], externalReferenceVars);
  24814. _this._createTypeCheckBlock(outputCtx, compMeta.type.reference.name + "_" + componentId, ngModuleMeta, compMeta, ngModuleMeta.transitiveModule.directives, externalReferenceVars);
  24815. });
  24816. }
  24817. });
  24818. if (outputCtx.statements.length === 0) {
  24819. _createEmptyStub(outputCtx);
  24820. }
  24821. };
  24822. AotCompiler.prototype._externalIdentifierReferences = function (references) {
  24823. var e_1, _a;
  24824. var result = [];
  24825. try {
  24826. for (var references_1 = __values(references), references_1_1 = references_1.next(); !references_1_1.done; references_1_1 = references_1.next()) {
  24827. var reference = references_1_1.value;
  24828. var token = createTokenForExternalReference(this.reflector, reference);
  24829. if (token.identifier) {
  24830. result.push(token.identifier.reference);
  24831. }
  24832. }
  24833. }
  24834. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  24835. finally {
  24836. try {
  24837. if (references_1_1 && !references_1_1.done && (_a = references_1.return)) _a.call(references_1);
  24838. }
  24839. finally { if (e_1) throw e_1.error; }
  24840. }
  24841. return result;
  24842. };
  24843. AotCompiler.prototype._createTypeCheckBlock = function (ctx, componentId, moduleMeta, compMeta, directives, externalReferenceVars) {
  24844. var _a;
  24845. var _b = this._parseTemplate(compMeta, moduleMeta, directives), parsedTemplate = _b.template, usedPipes = _b.pipes;
  24846. (_a = ctx.statements).push.apply(_a, __spread(this._typeCheckCompiler.compileComponent(componentId, compMeta, parsedTemplate, usedPipes, externalReferenceVars, ctx)));
  24847. };
  24848. AotCompiler.prototype.emitMessageBundle = function (analyzeResult, locale) {
  24849. var _this = this;
  24850. var errors = [];
  24851. var htmlParser = new HtmlParser();
  24852. // TODO(vicb): implicit tags & attributes
  24853. var messageBundle = new MessageBundle(htmlParser, [], {}, locale);
  24854. analyzeResult.files.forEach(function (file) {
  24855. var compMetas = [];
  24856. file.directives.forEach(function (directiveType) {
  24857. var dirMeta = _this._metadataResolver.getDirectiveMetadata(directiveType);
  24858. if (dirMeta && dirMeta.isComponent) {
  24859. compMetas.push(dirMeta);
  24860. }
  24861. });
  24862. compMetas.forEach(function (compMeta) {
  24863. var html = compMeta.template.template;
  24864. // Template URL points to either an HTML or TS file depending on whether
  24865. // the file is used with `templateUrl:` or `template:`, respectively.
  24866. var templateUrl = compMeta.template.templateUrl;
  24867. var interpolationConfig = InterpolationConfig.fromArray(compMeta.template.interpolation);
  24868. errors.push.apply(errors, __spread(messageBundle.updateFromTemplate(html, templateUrl, interpolationConfig)));
  24869. });
  24870. });
  24871. if (errors.length) {
  24872. throw new Error(errors.map(function (e) { return e.toString(); }).join('\n'));
  24873. }
  24874. return messageBundle;
  24875. };
  24876. AotCompiler.prototype.emitAllPartialModules = function (_a, r3Files) {
  24877. var _this = this;
  24878. var ngModuleByPipeOrDirective = _a.ngModuleByPipeOrDirective, files = _a.files;
  24879. var contextMap = new Map();
  24880. var getContext = function (fileName) {
  24881. if (!contextMap.has(fileName)) {
  24882. contextMap.set(fileName, _this._createOutputContext(fileName));
  24883. }
  24884. return contextMap.get(fileName);
  24885. };
  24886. files.forEach(function (file) { return _this._compilePartialModule(file.fileName, ngModuleByPipeOrDirective, file.directives, file.pipes, file.ngModules, file.injectables, getContext(file.fileName)); });
  24887. r3Files.forEach(function (file) { return _this._compileShallowModules(file.fileName, file.shallowModules, getContext(file.fileName)); });
  24888. return Array.from(contextMap.values())
  24889. .map(function (context) { return ({
  24890. fileName: context.genFilePath,
  24891. statements: __spread(context.constantPool.statements, context.statements),
  24892. }); });
  24893. };
  24894. AotCompiler.prototype._compileShallowModules = function (fileName, shallowModules, context) {
  24895. var _this = this;
  24896. shallowModules.forEach(function (module) { return compileNgModuleFromRender2(context, module, _this._injectableCompiler); });
  24897. };
  24898. AotCompiler.prototype._compilePartialModule = function (fileName, ngModuleByPipeOrDirective, directives, pipes, ngModules, injectables, context) {
  24899. var _this = this;
  24900. var errors = [];
  24901. var schemaRegistry = new DomElementSchemaRegistry();
  24902. var hostBindingParser = new BindingParser(this._templateParser.expressionParser, DEFAULT_INTERPOLATION_CONFIG, schemaRegistry, [], errors);
  24903. // Process all components and directives
  24904. directives.forEach(function (directiveType) {
  24905. var directiveMetadata = _this._metadataResolver.getDirectiveMetadata(directiveType);
  24906. if (directiveMetadata.isComponent) {
  24907. var module = ngModuleByPipeOrDirective.get(directiveType);
  24908. module ||
  24909. error("Cannot determine the module for component '" + identifierName(directiveMetadata.type) + "'");
  24910. var htmlAst = directiveMetadata.template.htmlAst;
  24911. var preserveWhitespaces = directiveMetadata.template.preserveWhitespaces;
  24912. if (!preserveWhitespaces) {
  24913. htmlAst = removeWhitespaces(htmlAst);
  24914. }
  24915. var render3Ast = htmlAstToRender3Ast(htmlAst.rootNodes, hostBindingParser);
  24916. // Map of StaticType by directive selectors
  24917. var directiveTypeBySel_1 = new Map();
  24918. var directives_1 = module.transitiveModule.directives.map(function (dir) { return _this._metadataResolver.getDirectiveSummary(dir.reference); });
  24919. directives_1.forEach(function (directive) {
  24920. if (directive.selector) {
  24921. directiveTypeBySel_1.set(directive.selector, directive.type.reference);
  24922. }
  24923. });
  24924. // Map of StaticType by pipe names
  24925. var pipeTypeByName_1 = new Map();
  24926. var pipes_1 = module.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
  24927. pipes_1.forEach(function (pipe) { pipeTypeByName_1.set(pipe.name, pipe.type.reference); });
  24928. compileComponentFromRender2(context, directiveMetadata, render3Ast, _this.reflector, hostBindingParser, directiveTypeBySel_1, pipeTypeByName_1);
  24929. }
  24930. else {
  24931. compileDirectiveFromRender2(context, directiveMetadata, _this.reflector, hostBindingParser);
  24932. }
  24933. });
  24934. pipes.forEach(function (pipeType) {
  24935. var pipeMetadata = _this._metadataResolver.getPipeMetadata(pipeType);
  24936. if (pipeMetadata) {
  24937. compilePipeFromRender2(context, pipeMetadata, _this.reflector);
  24938. }
  24939. });
  24940. injectables.forEach(function (injectable) { return _this._injectableCompiler.compile(injectable, context); });
  24941. };
  24942. AotCompiler.prototype.emitAllPartialModules2 = function (files) {
  24943. var _this = this;
  24944. // Using reduce like this is a select many pattern (where map is a select pattern)
  24945. return files.reduce(function (r, file) {
  24946. r.push.apply(r, __spread(_this._emitPartialModule2(file.fileName, file.injectables)));
  24947. return r;
  24948. }, []);
  24949. };
  24950. AotCompiler.prototype._emitPartialModule2 = function (fileName, injectables) {
  24951. var _this = this;
  24952. var context = this._createOutputContext(fileName);
  24953. injectables.forEach(function (injectable) { return _this._injectableCompiler.compile(injectable, context); });
  24954. if (context.statements && context.statements.length > 0) {
  24955. return [{ fileName: fileName, statements: __spread(context.constantPool.statements, context.statements) }];
  24956. }
  24957. return [];
  24958. };
  24959. AotCompiler.prototype.emitAllImpls = function (analyzeResult) {
  24960. var _this = this;
  24961. var ngModuleByPipeOrDirective = analyzeResult.ngModuleByPipeOrDirective, files = analyzeResult.files;
  24962. var sourceModules = files.map(function (file) { return _this._compileImplFile(file.fileName, ngModuleByPipeOrDirective, file.directives, file.pipes, file.ngModules, file.injectables); });
  24963. return flatten(sourceModules);
  24964. };
  24965. AotCompiler.prototype._compileImplFile = function (srcFileUrl, ngModuleByPipeOrDirective, directives, pipes, ngModules, injectables) {
  24966. var _this = this;
  24967. var fileSuffix = normalizeGenFileSuffix(splitTypescriptSuffix(srcFileUrl, true)[1]);
  24968. var generatedFiles = [];
  24969. var outputCtx = this._createOutputContext(ngfactoryFilePath(srcFileUrl, true));
  24970. generatedFiles.push.apply(generatedFiles, __spread(this._createSummary(srcFileUrl, directives, pipes, ngModules, injectables, outputCtx)));
  24971. // compile all ng modules
  24972. ngModules.forEach(function (ngModuleMeta) { return _this._compileModule(outputCtx, ngModuleMeta); });
  24973. // compile components
  24974. directives.forEach(function (dirType) {
  24975. var compMeta = _this._metadataResolver.getDirectiveMetadata(dirType);
  24976. if (!compMeta.isComponent) {
  24977. return;
  24978. }
  24979. var ngModule = ngModuleByPipeOrDirective.get(dirType);
  24980. if (!ngModule) {
  24981. throw new Error("Internal Error: cannot determine the module for component " + identifierName(compMeta.type) + "!");
  24982. }
  24983. // compile styles
  24984. var componentStylesheet = _this._styleCompiler.compileComponent(outputCtx, compMeta);
  24985. // Note: compMeta is a component and therefore template is non null.
  24986. compMeta.template.externalStylesheets.forEach(function (stylesheetMeta) {
  24987. // Note: fill non shim and shim style files as they might
  24988. // be shared by component with and without ViewEncapsulation.
  24989. var shim = _this._styleCompiler.needsStyleShim(compMeta);
  24990. generatedFiles.push(_this._codegenStyles(srcFileUrl, compMeta, stylesheetMeta, shim, fileSuffix));
  24991. if (_this._options.allowEmptyCodegenFiles) {
  24992. generatedFiles.push(_this._codegenStyles(srcFileUrl, compMeta, stylesheetMeta, !shim, fileSuffix));
  24993. }
  24994. });
  24995. // compile components
  24996. var compViewVars = _this._compileComponent(outputCtx, compMeta, ngModule, ngModule.transitiveModule.directives, componentStylesheet, fileSuffix);
  24997. _this._compileComponentFactory(outputCtx, compMeta, ngModule, fileSuffix);
  24998. });
  24999. if (outputCtx.statements.length > 0 || this._options.allowEmptyCodegenFiles) {
  25000. var srcModule = this._codegenSourceModule(srcFileUrl, outputCtx);
  25001. generatedFiles.unshift(srcModule);
  25002. }
  25003. return generatedFiles;
  25004. };
  25005. AotCompiler.prototype._createSummary = function (srcFileName, directives, pipes, ngModules, injectables, ngFactoryCtx) {
  25006. var _this = this;
  25007. var symbolSummaries = this._symbolResolver.getSymbolsOf(srcFileName)
  25008. .map(function (symbol) { return _this._symbolResolver.resolveSymbol(symbol); });
  25009. var typeData = __spread(ngModules.map(function (meta) { return ({
  25010. summary: _this._metadataResolver.getNgModuleSummary(meta.type.reference),
  25011. metadata: _this._metadataResolver.getNgModuleMetadata(meta.type.reference)
  25012. }); }), directives.map(function (ref) { return ({
  25013. summary: _this._metadataResolver.getDirectiveSummary(ref),
  25014. metadata: _this._metadataResolver.getDirectiveMetadata(ref)
  25015. }); }), pipes.map(function (ref) { return ({
  25016. summary: _this._metadataResolver.getPipeSummary(ref),
  25017. metadata: _this._metadataResolver.getPipeMetadata(ref)
  25018. }); }), injectables.map(function (ref) { return ({
  25019. summary: _this._metadataResolver.getInjectableSummary(ref.symbol),
  25020. metadata: _this._metadataResolver.getInjectableSummary(ref.symbol).type
  25021. }); }));
  25022. var forJitOutputCtx = this._options.enableSummariesForJit ?
  25023. this._createOutputContext(summaryForJitFileName(srcFileName, true)) :
  25024. null;
  25025. var _a = serializeSummaries(srcFileName, forJitOutputCtx, this._summaryResolver, this._symbolResolver, symbolSummaries, typeData, this._options.createExternalSymbolFactoryReexports), json = _a.json, exportAs = _a.exportAs;
  25026. exportAs.forEach(function (entry) {
  25027. ngFactoryCtx.statements.push(variable(entry.exportAs).set(ngFactoryCtx.importExpr(entry.symbol)).toDeclStmt(null, [
  25028. exports.StmtModifier.Exported
  25029. ]));
  25030. });
  25031. var summaryJson = new GeneratedFile(srcFileName, summaryFileName(srcFileName), json);
  25032. var result = [summaryJson];
  25033. if (forJitOutputCtx) {
  25034. result.push(this._codegenSourceModule(srcFileName, forJitOutputCtx));
  25035. }
  25036. return result;
  25037. };
  25038. AotCompiler.prototype._compileModule = function (outputCtx, ngModule) {
  25039. var providers = [];
  25040. if (this._options.locale) {
  25041. var normalizedLocale = this._options.locale.replace(/_/g, '-');
  25042. providers.push({
  25043. token: createTokenForExternalReference(this.reflector, Identifiers.LOCALE_ID),
  25044. useValue: normalizedLocale,
  25045. });
  25046. }
  25047. if (this._options.i18nFormat) {
  25048. providers.push({
  25049. token: createTokenForExternalReference(this.reflector, Identifiers.TRANSLATIONS_FORMAT),
  25050. useValue: this._options.i18nFormat
  25051. });
  25052. }
  25053. this._ngModuleCompiler.compile(outputCtx, ngModule, providers);
  25054. };
  25055. AotCompiler.prototype._compileComponentFactory = function (outputCtx, compMeta, ngModule, fileSuffix) {
  25056. var hostMeta = this._metadataResolver.getHostComponentMetadata(compMeta);
  25057. var hostViewFactoryVar = this._compileComponent(outputCtx, hostMeta, ngModule, [compMeta.type], null, fileSuffix)
  25058. .viewClassVar;
  25059. var compFactoryVar = componentFactoryName(compMeta.type.reference);
  25060. var inputsExprs = [];
  25061. for (var propName in compMeta.inputs) {
  25062. var templateName = compMeta.inputs[propName];
  25063. // Don't quote so that the key gets minified...
  25064. inputsExprs.push(new LiteralMapEntry(propName, literal(templateName), false));
  25065. }
  25066. var outputsExprs = [];
  25067. for (var propName in compMeta.outputs) {
  25068. var templateName = compMeta.outputs[propName];
  25069. // Don't quote so that the key gets minified...
  25070. outputsExprs.push(new LiteralMapEntry(propName, literal(templateName), false));
  25071. }
  25072. outputCtx.statements.push(variable(compFactoryVar)
  25073. .set(importExpr(Identifiers.createComponentFactory).callFn([
  25074. literal(compMeta.selector), outputCtx.importExpr(compMeta.type.reference),
  25075. variable(hostViewFactoryVar), new LiteralMapExpr(inputsExprs),
  25076. new LiteralMapExpr(outputsExprs),
  25077. literalArr(compMeta.template.ngContentSelectors.map(function (selector) { return literal(selector); }))
  25078. ]))
  25079. .toDeclStmt(importType(Identifiers.ComponentFactory, [expressionType(outputCtx.importExpr(compMeta.type.reference))], [TypeModifier.Const]), [exports.StmtModifier.Final, exports.StmtModifier.Exported]));
  25080. };
  25081. AotCompiler.prototype._compileComponent = function (outputCtx, compMeta, ngModule, directiveIdentifiers, componentStyles, fileSuffix) {
  25082. var _a = this._parseTemplate(compMeta, ngModule, directiveIdentifiers), parsedTemplate = _a.template, usedPipes = _a.pipes;
  25083. var stylesExpr = componentStyles ? variable(componentStyles.stylesVar) : literalArr([]);
  25084. var viewResult = this._viewCompiler.compileComponent(outputCtx, compMeta, parsedTemplate, stylesExpr, usedPipes);
  25085. if (componentStyles) {
  25086. _resolveStyleStatements(this._symbolResolver, componentStyles, this._styleCompiler.needsStyleShim(compMeta), fileSuffix);
  25087. }
  25088. return viewResult;
  25089. };
  25090. AotCompiler.prototype._parseTemplate = function (compMeta, ngModule, directiveIdentifiers) {
  25091. var _this = this;
  25092. if (this._templateAstCache.has(compMeta.type.reference)) {
  25093. return this._templateAstCache.get(compMeta.type.reference);
  25094. }
  25095. var preserveWhitespaces = compMeta.template.preserveWhitespaces;
  25096. var directives = directiveIdentifiers.map(function (dir) { return _this._metadataResolver.getDirectiveSummary(dir.reference); });
  25097. var pipes = ngModule.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
  25098. var result = this._templateParser.parse(compMeta, compMeta.template.htmlAst, directives, pipes, ngModule.schemas, templateSourceUrl(ngModule.type, compMeta, compMeta.template), preserveWhitespaces);
  25099. this._templateAstCache.set(compMeta.type.reference, result);
  25100. return result;
  25101. };
  25102. AotCompiler.prototype._createOutputContext = function (genFilePath) {
  25103. var _this = this;
  25104. var importExpr$1 = function (symbol, typeParams, useSummaries) {
  25105. if (typeParams === void 0) { typeParams = null; }
  25106. if (useSummaries === void 0) { useSummaries = true; }
  25107. if (!(symbol instanceof StaticSymbol)) {
  25108. throw new Error("Internal error: unknown identifier " + JSON.stringify(symbol));
  25109. }
  25110. var arity = _this._symbolResolver.getTypeArity(symbol) || 0;
  25111. var _a = _this._symbolResolver.getImportAs(symbol, useSummaries) || symbol, filePath = _a.filePath, name = _a.name, members = _a.members;
  25112. var importModule = _this._fileNameToModuleName(filePath, genFilePath);
  25113. // It should be good enough to compare filePath to genFilePath and if they are equal
  25114. // there is a self reference. However, ngfactory files generate to .ts but their
  25115. // symbols have .d.ts so a simple compare is insufficient. They should be canonical
  25116. // and is tracked by #17705.
  25117. var selfReference = _this._fileNameToModuleName(genFilePath, genFilePath);
  25118. var moduleName = importModule === selfReference ? null : importModule;
  25119. // If we are in a type expression that refers to a generic type then supply
  25120. // the required type parameters. If there were not enough type parameters
  25121. // supplied, supply any as the type. Outside a type expression the reference
  25122. // should not supply type parameters and be treated as a simple value reference
  25123. // to the constructor function itself.
  25124. var suppliedTypeParams = typeParams || [];
  25125. var missingTypeParamsCount = arity - suppliedTypeParams.length;
  25126. var allTypeParams = suppliedTypeParams.concat(new Array(missingTypeParamsCount).fill(DYNAMIC_TYPE));
  25127. return members.reduce(function (expr, memberName) { return expr.prop(memberName); }, importExpr(new ExternalReference(moduleName, name, null), allTypeParams));
  25128. };
  25129. return { statements: [], genFilePath: genFilePath, importExpr: importExpr$1, constantPool: new ConstantPool() };
  25130. };
  25131. AotCompiler.prototype._fileNameToModuleName = function (importedFilePath, containingFilePath) {
  25132. return this._summaryResolver.getKnownModuleName(importedFilePath) ||
  25133. this._symbolResolver.getKnownModuleName(importedFilePath) ||
  25134. this._host.fileNameToModuleName(importedFilePath, containingFilePath);
  25135. };
  25136. AotCompiler.prototype._codegenStyles = function (srcFileUrl, compMeta, stylesheetMetadata, isShimmed, fileSuffix) {
  25137. var outputCtx = this._createOutputContext(_stylesModuleUrl(stylesheetMetadata.moduleUrl, isShimmed, fileSuffix));
  25138. var compiledStylesheet = this._styleCompiler.compileStyles(outputCtx, compMeta, stylesheetMetadata, isShimmed);
  25139. _resolveStyleStatements(this._symbolResolver, compiledStylesheet, isShimmed, fileSuffix);
  25140. return this._codegenSourceModule(srcFileUrl, outputCtx);
  25141. };
  25142. AotCompiler.prototype._codegenSourceModule = function (srcFileUrl, ctx) {
  25143. return new GeneratedFile(srcFileUrl, ctx.genFilePath, ctx.statements);
  25144. };
  25145. AotCompiler.prototype.listLazyRoutes = function (entryRoute, analyzedModules) {
  25146. var e_2, _a, e_3, _b;
  25147. var self = this;
  25148. if (entryRoute) {
  25149. var symbol = parseLazyRoute(entryRoute, this.reflector).referencedModule;
  25150. return visitLazyRoute(symbol);
  25151. }
  25152. else if (analyzedModules) {
  25153. var allLazyRoutes = [];
  25154. try {
  25155. for (var _c = __values(analyzedModules.ngModules), _d = _c.next(); !_d.done; _d = _c.next()) {
  25156. var ngModule = _d.value;
  25157. var lazyRoutes = listLazyRoutes(ngModule, this.reflector);
  25158. try {
  25159. for (var lazyRoutes_1 = __values(lazyRoutes), lazyRoutes_1_1 = lazyRoutes_1.next(); !lazyRoutes_1_1.done; lazyRoutes_1_1 = lazyRoutes_1.next()) {
  25160. var lazyRoute = lazyRoutes_1_1.value;
  25161. allLazyRoutes.push(lazyRoute);
  25162. }
  25163. }
  25164. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  25165. finally {
  25166. try {
  25167. if (lazyRoutes_1_1 && !lazyRoutes_1_1.done && (_b = lazyRoutes_1.return)) _b.call(lazyRoutes_1);
  25168. }
  25169. finally { if (e_3) throw e_3.error; }
  25170. }
  25171. }
  25172. }
  25173. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  25174. finally {
  25175. try {
  25176. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  25177. }
  25178. finally { if (e_2) throw e_2.error; }
  25179. }
  25180. return allLazyRoutes;
  25181. }
  25182. else {
  25183. throw new Error("Either route or analyzedModules has to be specified!");
  25184. }
  25185. function visitLazyRoute(symbol, seenRoutes, allLazyRoutes) {
  25186. var e_4, _a;
  25187. if (seenRoutes === void 0) { seenRoutes = new Set(); }
  25188. if (allLazyRoutes === void 0) { allLazyRoutes = []; }
  25189. // Support pointing to default exports, but stop recursing there,
  25190. // as the StaticReflector does not yet support default exports.
  25191. if (seenRoutes.has(symbol) || !symbol.name) {
  25192. return allLazyRoutes;
  25193. }
  25194. seenRoutes.add(symbol);
  25195. var lazyRoutes = listLazyRoutes(self._metadataResolver.getNgModuleMetadata(symbol, true), self.reflector);
  25196. try {
  25197. for (var lazyRoutes_2 = __values(lazyRoutes), lazyRoutes_2_1 = lazyRoutes_2.next(); !lazyRoutes_2_1.done; lazyRoutes_2_1 = lazyRoutes_2.next()) {
  25198. var lazyRoute = lazyRoutes_2_1.value;
  25199. allLazyRoutes.push(lazyRoute);
  25200. visitLazyRoute(lazyRoute.referencedModule, seenRoutes, allLazyRoutes);
  25201. }
  25202. }
  25203. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  25204. finally {
  25205. try {
  25206. if (lazyRoutes_2_1 && !lazyRoutes_2_1.done && (_a = lazyRoutes_2.return)) _a.call(lazyRoutes_2);
  25207. }
  25208. finally { if (e_4) throw e_4.error; }
  25209. }
  25210. return allLazyRoutes;
  25211. }
  25212. };
  25213. return AotCompiler;
  25214. }());
  25215. function _createEmptyStub(outputCtx) {
  25216. // Note: We need to produce at least one import statement so that
  25217. // TypeScript knows that the file is an es6 module. Otherwise our generated
  25218. // exports / imports won't be emitted properly by TypeScript.
  25219. outputCtx.statements.push(importExpr(Identifiers.ComponentFactory).toStmt());
  25220. }
  25221. function _resolveStyleStatements(symbolResolver, compileResult, needsShim, fileSuffix) {
  25222. compileResult.dependencies.forEach(function (dep) {
  25223. dep.setValue(symbolResolver.getStaticSymbol(_stylesModuleUrl(dep.moduleUrl, needsShim, fileSuffix), dep.name));
  25224. });
  25225. }
  25226. function _stylesModuleUrl(stylesheetUrl, shim, suffix) {
  25227. return "" + stylesheetUrl + (shim ? '.shim' : '') + ".ngstyle" + suffix;
  25228. }
  25229. function analyzeNgModules(fileNames, host, staticSymbolResolver, metadataResolver) {
  25230. var files = _analyzeFilesIncludingNonProgramFiles(fileNames, host, staticSymbolResolver, metadataResolver);
  25231. return mergeAnalyzedFiles(files);
  25232. }
  25233. function analyzeAndValidateNgModules(fileNames, host, staticSymbolResolver, metadataResolver) {
  25234. return validateAnalyzedModules(analyzeNgModules(fileNames, host, staticSymbolResolver, metadataResolver));
  25235. }
  25236. function validateAnalyzedModules(analyzedModules) {
  25237. if (analyzedModules.symbolsMissingModule && analyzedModules.symbolsMissingModule.length) {
  25238. var messages = analyzedModules.symbolsMissingModule.map(function (s) {
  25239. return "Cannot determine the module for class " + s.name + " in " + s.filePath + "! Add " + s.name + " to the NgModule to fix it.";
  25240. });
  25241. throw syntaxError(messages.join('\n'));
  25242. }
  25243. return analyzedModules;
  25244. }
  25245. // Analyzes all of the program files,
  25246. // including files that are not part of the program
  25247. // but are referenced by an NgModule.
  25248. function _analyzeFilesIncludingNonProgramFiles(fileNames, host, staticSymbolResolver, metadataResolver) {
  25249. var seenFiles = new Set();
  25250. var files = [];
  25251. var visitFile = function (fileName) {
  25252. if (seenFiles.has(fileName) || !host.isSourceFile(fileName)) {
  25253. return false;
  25254. }
  25255. seenFiles.add(fileName);
  25256. var analyzedFile = analyzeFile(host, staticSymbolResolver, metadataResolver, fileName);
  25257. files.push(analyzedFile);
  25258. analyzedFile.ngModules.forEach(function (ngModule) {
  25259. ngModule.transitiveModule.modules.forEach(function (modMeta) { return visitFile(modMeta.reference.filePath); });
  25260. });
  25261. };
  25262. fileNames.forEach(function (fileName) { return visitFile(fileName); });
  25263. return files;
  25264. }
  25265. function analyzeFile(host, staticSymbolResolver, metadataResolver, fileName) {
  25266. var directives = [];
  25267. var pipes = [];
  25268. var injectables = [];
  25269. var ngModules = [];
  25270. var hasDecorators = staticSymbolResolver.hasDecorators(fileName);
  25271. var exportsNonSourceFiles = false;
  25272. // Don't analyze .d.ts files that have no decorators as a shortcut
  25273. // to speed up the analysis. This prevents us from
  25274. // resolving the references in these files.
  25275. // Note: exportsNonSourceFiles is only needed when compiling with summaries,
  25276. // which is not the case when .d.ts files are treated as input files.
  25277. if (!fileName.endsWith('.d.ts') || hasDecorators) {
  25278. staticSymbolResolver.getSymbolsOf(fileName).forEach(function (symbol) {
  25279. var resolvedSymbol = staticSymbolResolver.resolveSymbol(symbol);
  25280. var symbolMeta = resolvedSymbol.metadata;
  25281. if (!symbolMeta || symbolMeta.__symbolic === 'error') {
  25282. return;
  25283. }
  25284. var isNgSymbol = false;
  25285. if (symbolMeta.__symbolic === 'class') {
  25286. if (metadataResolver.isDirective(symbol)) {
  25287. isNgSymbol = true;
  25288. directives.push(symbol);
  25289. }
  25290. else if (metadataResolver.isPipe(symbol)) {
  25291. isNgSymbol = true;
  25292. pipes.push(symbol);
  25293. }
  25294. else if (metadataResolver.isNgModule(symbol)) {
  25295. var ngModule = metadataResolver.getNgModuleMetadata(symbol, false);
  25296. if (ngModule) {
  25297. isNgSymbol = true;
  25298. ngModules.push(ngModule);
  25299. }
  25300. }
  25301. else if (metadataResolver.isInjectable(symbol)) {
  25302. isNgSymbol = true;
  25303. var injectable = metadataResolver.getInjectableMetadata(symbol, null, false);
  25304. if (injectable) {
  25305. injectables.push(injectable);
  25306. }
  25307. }
  25308. }
  25309. if (!isNgSymbol) {
  25310. exportsNonSourceFiles =
  25311. exportsNonSourceFiles || isValueExportingNonSourceFile(host, symbolMeta);
  25312. }
  25313. });
  25314. }
  25315. return {
  25316. fileName: fileName, directives: directives, pipes: pipes, ngModules: ngModules, injectables: injectables, exportsNonSourceFiles: exportsNonSourceFiles,
  25317. };
  25318. }
  25319. function analyzeFileForInjectables(host, staticSymbolResolver, metadataResolver, fileName) {
  25320. var injectables = [];
  25321. var shallowModules = [];
  25322. if (staticSymbolResolver.hasDecorators(fileName)) {
  25323. staticSymbolResolver.getSymbolsOf(fileName).forEach(function (symbol) {
  25324. var resolvedSymbol = staticSymbolResolver.resolveSymbol(symbol);
  25325. var symbolMeta = resolvedSymbol.metadata;
  25326. if (!symbolMeta || symbolMeta.__symbolic === 'error') {
  25327. return;
  25328. }
  25329. if (symbolMeta.__symbolic === 'class') {
  25330. if (metadataResolver.isInjectable(symbol)) {
  25331. var injectable = metadataResolver.getInjectableMetadata(symbol, null, false);
  25332. if (injectable) {
  25333. injectables.push(injectable);
  25334. }
  25335. }
  25336. else if (metadataResolver.isNgModule(symbol)) {
  25337. var module = metadataResolver.getShallowModuleMetadata(symbol);
  25338. if (module) {
  25339. shallowModules.push(module);
  25340. }
  25341. }
  25342. }
  25343. });
  25344. }
  25345. return { fileName: fileName, injectables: injectables, shallowModules: shallowModules };
  25346. }
  25347. function isValueExportingNonSourceFile(host, metadata) {
  25348. var exportsNonSourceFiles = false;
  25349. var Visitor = /** @class */ (function () {
  25350. function Visitor() {
  25351. }
  25352. Visitor.prototype.visitArray = function (arr, context) {
  25353. var _this = this;
  25354. arr.forEach(function (v) { return visitValue(v, _this, context); });
  25355. };
  25356. Visitor.prototype.visitStringMap = function (map, context) {
  25357. var _this = this;
  25358. Object.keys(map).forEach(function (key) { return visitValue(map[key], _this, context); });
  25359. };
  25360. Visitor.prototype.visitPrimitive = function (value, context) { };
  25361. Visitor.prototype.visitOther = function (value, context) {
  25362. if (value instanceof StaticSymbol && !host.isSourceFile(value.filePath)) {
  25363. exportsNonSourceFiles = true;
  25364. }
  25365. };
  25366. return Visitor;
  25367. }());
  25368. visitValue(metadata, new Visitor(), null);
  25369. return exportsNonSourceFiles;
  25370. }
  25371. function mergeAnalyzedFiles(analyzedFiles) {
  25372. var allNgModules = [];
  25373. var ngModuleByPipeOrDirective = new Map();
  25374. var allPipesAndDirectives = new Set();
  25375. analyzedFiles.forEach(function (af) {
  25376. af.ngModules.forEach(function (ngModule) {
  25377. allNgModules.push(ngModule);
  25378. ngModule.declaredDirectives.forEach(function (d) { return ngModuleByPipeOrDirective.set(d.reference, ngModule); });
  25379. ngModule.declaredPipes.forEach(function (p) { return ngModuleByPipeOrDirective.set(p.reference, ngModule); });
  25380. });
  25381. af.directives.forEach(function (d) { return allPipesAndDirectives.add(d); });
  25382. af.pipes.forEach(function (p) { return allPipesAndDirectives.add(p); });
  25383. });
  25384. var symbolsMissingModule = [];
  25385. allPipesAndDirectives.forEach(function (ref) {
  25386. if (!ngModuleByPipeOrDirective.has(ref)) {
  25387. symbolsMissingModule.push(ref);
  25388. }
  25389. });
  25390. return {
  25391. ngModules: allNgModules,
  25392. ngModuleByPipeOrDirective: ngModuleByPipeOrDirective,
  25393. symbolsMissingModule: symbolsMissingModule,
  25394. files: analyzedFiles
  25395. };
  25396. }
  25397. function mergeAndValidateNgFiles(files) {
  25398. return validateAnalyzedModules(mergeAnalyzedFiles(files));
  25399. }
  25400. /**
  25401. * @license
  25402. * Copyright Google Inc. All Rights Reserved.
  25403. *
  25404. * Use of this source code is governed by an MIT-style license that can be
  25405. * found in the LICENSE file at https://angular.io/license
  25406. */
  25407. var FORMATTED_MESSAGE = 'ngFormattedMessage';
  25408. function indentStr(level) {
  25409. if (level <= 0)
  25410. return '';
  25411. if (level < 6)
  25412. return ['', ' ', ' ', ' ', ' ', ' '][level];
  25413. var half = indentStr(Math.floor(level / 2));
  25414. return half + half + (level % 2 === 1 ? ' ' : '');
  25415. }
  25416. function formatChain(chain, indent) {
  25417. if (indent === void 0) { indent = 0; }
  25418. if (!chain)
  25419. return '';
  25420. var position = chain.position ?
  25421. chain.position.fileName + "(" + (chain.position.line + 1) + "," + (chain.position.column + 1) + ")" :
  25422. '';
  25423. var prefix = position && indent === 0 ? position + ": " : '';
  25424. var postfix = position && indent !== 0 ? " at " + position : '';
  25425. var message = "" + prefix + chain.message + postfix;
  25426. return "" + indentStr(indent) + message + ((chain.next && ('\n' + formatChain(chain.next, indent + 2))) || '');
  25427. }
  25428. function formattedError(chain) {
  25429. var message = formatChain(chain) + '.';
  25430. var error = syntaxError(message);
  25431. error[FORMATTED_MESSAGE] = true;
  25432. error.chain = chain;
  25433. error.position = chain.position;
  25434. return error;
  25435. }
  25436. function isFormattedError(error) {
  25437. return !!error[FORMATTED_MESSAGE];
  25438. }
  25439. /**
  25440. * @license
  25441. * Copyright Google Inc. All Rights Reserved.
  25442. *
  25443. * Use of this source code is governed by an MIT-style license that can be
  25444. * found in the LICENSE file at https://angular.io/license
  25445. */
  25446. var ANGULAR_CORE = '@angular/core';
  25447. var ANGULAR_ROUTER = '@angular/router';
  25448. var HIDDEN_KEY = /^\$.*\$$/;
  25449. var IGNORE = {
  25450. __symbolic: 'ignore'
  25451. };
  25452. var USE_VALUE$1 = 'useValue';
  25453. var PROVIDE = 'provide';
  25454. var REFERENCE_SET = new Set([USE_VALUE$1, 'useFactory', 'data', 'id', 'loadChildren']);
  25455. var TYPEGUARD_POSTFIX = 'TypeGuard';
  25456. var USE_IF = 'UseIf';
  25457. function shouldIgnore(value) {
  25458. return value && value.__symbolic == 'ignore';
  25459. }
  25460. /**
  25461. * A static reflector implements enough of the Reflector API that is necessary to compile
  25462. * templates statically.
  25463. */
  25464. var StaticReflector = /** @class */ (function () {
  25465. function StaticReflector(summaryResolver, symbolResolver, knownMetadataClasses, knownMetadataFunctions, errorRecorder) {
  25466. var _this = this;
  25467. if (knownMetadataClasses === void 0) { knownMetadataClasses = []; }
  25468. if (knownMetadataFunctions === void 0) { knownMetadataFunctions = []; }
  25469. this.summaryResolver = summaryResolver;
  25470. this.symbolResolver = symbolResolver;
  25471. this.errorRecorder = errorRecorder;
  25472. this.annotationCache = new Map();
  25473. this.shallowAnnotationCache = new Map();
  25474. this.propertyCache = new Map();
  25475. this.parameterCache = new Map();
  25476. this.methodCache = new Map();
  25477. this.staticCache = new Map();
  25478. this.conversionMap = new Map();
  25479. this.resolvedExternalReferences = new Map();
  25480. this.annotationForParentClassWithSummaryKind = new Map();
  25481. this.initializeConversionMap();
  25482. knownMetadataClasses.forEach(function (kc) { return _this._registerDecoratorOrConstructor(_this.getStaticSymbol(kc.filePath, kc.name), kc.ctor); });
  25483. knownMetadataFunctions.forEach(function (kf) { return _this._registerFunction(_this.getStaticSymbol(kf.filePath, kf.name), kf.fn); });
  25484. this.annotationForParentClassWithSummaryKind.set(exports.CompileSummaryKind.Directive, [createDirective, createComponent]);
  25485. this.annotationForParentClassWithSummaryKind.set(exports.CompileSummaryKind.Pipe, [createPipe]);
  25486. this.annotationForParentClassWithSummaryKind.set(exports.CompileSummaryKind.NgModule, [createNgModule]);
  25487. this.annotationForParentClassWithSummaryKind.set(exports.CompileSummaryKind.Injectable, [createInjectable, createPipe, createDirective, createComponent, createNgModule]);
  25488. }
  25489. StaticReflector.prototype.componentModuleUrl = function (typeOrFunc) {
  25490. var staticSymbol = this.findSymbolDeclaration(typeOrFunc);
  25491. return this.symbolResolver.getResourcePath(staticSymbol);
  25492. };
  25493. StaticReflector.prototype.resolveExternalReference = function (ref, containingFile) {
  25494. var key = undefined;
  25495. if (!containingFile) {
  25496. key = ref.moduleName + ":" + ref.name;
  25497. var declarationSymbol_1 = this.resolvedExternalReferences.get(key);
  25498. if (declarationSymbol_1)
  25499. return declarationSymbol_1;
  25500. }
  25501. var refSymbol = this.symbolResolver.getSymbolByModule(ref.moduleName, ref.name, containingFile);
  25502. var declarationSymbol = this.findSymbolDeclaration(refSymbol);
  25503. if (!containingFile) {
  25504. this.symbolResolver.recordModuleNameForFileName(refSymbol.filePath, ref.moduleName);
  25505. this.symbolResolver.recordImportAs(declarationSymbol, refSymbol);
  25506. }
  25507. if (key) {
  25508. this.resolvedExternalReferences.set(key, declarationSymbol);
  25509. }
  25510. return declarationSymbol;
  25511. };
  25512. StaticReflector.prototype.findDeclaration = function (moduleUrl, name, containingFile) {
  25513. return this.findSymbolDeclaration(this.symbolResolver.getSymbolByModule(moduleUrl, name, containingFile));
  25514. };
  25515. StaticReflector.prototype.tryFindDeclaration = function (moduleUrl, name, containingFile) {
  25516. var _this = this;
  25517. return this.symbolResolver.ignoreErrorsFor(function () { return _this.findDeclaration(moduleUrl, name, containingFile); });
  25518. };
  25519. StaticReflector.prototype.findSymbolDeclaration = function (symbol) {
  25520. var resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
  25521. if (resolvedSymbol) {
  25522. var resolvedMetadata = resolvedSymbol.metadata;
  25523. if (resolvedMetadata && resolvedMetadata.__symbolic === 'resolved') {
  25524. resolvedMetadata = resolvedMetadata.symbol;
  25525. }
  25526. if (resolvedMetadata instanceof StaticSymbol) {
  25527. return this.findSymbolDeclaration(resolvedSymbol.metadata);
  25528. }
  25529. }
  25530. return symbol;
  25531. };
  25532. StaticReflector.prototype.tryAnnotations = function (type) {
  25533. var originalRecorder = this.errorRecorder;
  25534. this.errorRecorder = function (error, fileName) { };
  25535. try {
  25536. return this.annotations(type);
  25537. }
  25538. finally {
  25539. this.errorRecorder = originalRecorder;
  25540. }
  25541. };
  25542. StaticReflector.prototype.annotations = function (type) {
  25543. var _this = this;
  25544. return this._annotations(type, function (type, decorators) { return _this.simplify(type, decorators); }, this.annotationCache);
  25545. };
  25546. StaticReflector.prototype.shallowAnnotations = function (type) {
  25547. var _this = this;
  25548. return this._annotations(type, function (type, decorators) { return _this.simplify(type, decorators, true); }, this.shallowAnnotationCache);
  25549. };
  25550. StaticReflector.prototype._annotations = function (type, simplify, annotationCache) {
  25551. var annotations = annotationCache.get(type);
  25552. if (!annotations) {
  25553. annotations = [];
  25554. var classMetadata = this.getTypeMetadata(type);
  25555. var parentType = this.findParentType(type, classMetadata);
  25556. if (parentType) {
  25557. var parentAnnotations = this.annotations(parentType);
  25558. annotations.push.apply(annotations, __spread(parentAnnotations));
  25559. }
  25560. var ownAnnotations_1 = [];
  25561. if (classMetadata['decorators']) {
  25562. ownAnnotations_1 = simplify(type, classMetadata['decorators']);
  25563. if (ownAnnotations_1) {
  25564. annotations.push.apply(annotations, __spread(ownAnnotations_1));
  25565. }
  25566. }
  25567. if (parentType && !this.summaryResolver.isLibraryFile(type.filePath) &&
  25568. this.summaryResolver.isLibraryFile(parentType.filePath)) {
  25569. var summary = this.summaryResolver.resolveSummary(parentType);
  25570. if (summary && summary.type) {
  25571. var requiredAnnotationTypes = this.annotationForParentClassWithSummaryKind.get(summary.type.summaryKind);
  25572. var typeHasRequiredAnnotation = requiredAnnotationTypes.some(function (requiredType) { return ownAnnotations_1.some(function (ann) { return requiredType.isTypeOf(ann); }); });
  25573. if (!typeHasRequiredAnnotation) {
  25574. this.reportError(formatMetadataError(metadataError("Class " + type.name + " in " + type.filePath + " extends from a " + exports.CompileSummaryKind[summary.type.summaryKind] + " in another compilation unit without duplicating the decorator",
  25575. /* summary */ undefined, "Please add a " + requiredAnnotationTypes.map(function (type) { return type.ngMetadataName; }).join(' or ') + " decorator to the class"), type), type);
  25576. }
  25577. }
  25578. }
  25579. annotationCache.set(type, annotations.filter(function (ann) { return !!ann; }));
  25580. }
  25581. return annotations;
  25582. };
  25583. StaticReflector.prototype.propMetadata = function (type) {
  25584. var _this = this;
  25585. var propMetadata = this.propertyCache.get(type);
  25586. if (!propMetadata) {
  25587. var classMetadata = this.getTypeMetadata(type);
  25588. propMetadata = {};
  25589. var parentType = this.findParentType(type, classMetadata);
  25590. if (parentType) {
  25591. var parentPropMetadata_1 = this.propMetadata(parentType);
  25592. Object.keys(parentPropMetadata_1).forEach(function (parentProp) {
  25593. propMetadata[parentProp] = parentPropMetadata_1[parentProp];
  25594. });
  25595. }
  25596. var members_1 = classMetadata['members'] || {};
  25597. Object.keys(members_1).forEach(function (propName) {
  25598. var propData = members_1[propName];
  25599. var prop = propData
  25600. .find(function (a) { return a['__symbolic'] == 'property' || a['__symbolic'] == 'method'; });
  25601. var decorators = [];
  25602. if (propMetadata[propName]) {
  25603. decorators.push.apply(decorators, __spread(propMetadata[propName]));
  25604. }
  25605. propMetadata[propName] = decorators;
  25606. if (prop && prop['decorators']) {
  25607. decorators.push.apply(decorators, __spread(_this.simplify(type, prop['decorators'])));
  25608. }
  25609. });
  25610. this.propertyCache.set(type, propMetadata);
  25611. }
  25612. return propMetadata;
  25613. };
  25614. StaticReflector.prototype.parameters = function (type) {
  25615. var _this = this;
  25616. if (!(type instanceof StaticSymbol)) {
  25617. this.reportError(new Error("parameters received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
  25618. return [];
  25619. }
  25620. try {
  25621. var parameters_1 = this.parameterCache.get(type);
  25622. if (!parameters_1) {
  25623. var classMetadata = this.getTypeMetadata(type);
  25624. var parentType = this.findParentType(type, classMetadata);
  25625. var members = classMetadata ? classMetadata['members'] : null;
  25626. var ctorData = members ? members['__ctor__'] : null;
  25627. if (ctorData) {
  25628. var ctor = ctorData.find(function (a) { return a['__symbolic'] == 'constructor'; });
  25629. var rawParameterTypes = ctor['parameters'] || [];
  25630. var parameterDecorators_1 = this.simplify(type, ctor['parameterDecorators'] || []);
  25631. parameters_1 = [];
  25632. rawParameterTypes.forEach(function (rawParamType, index) {
  25633. var nestedResult = [];
  25634. var paramType = _this.trySimplify(type, rawParamType);
  25635. if (paramType)
  25636. nestedResult.push(paramType);
  25637. var decorators = parameterDecorators_1 ? parameterDecorators_1[index] : null;
  25638. if (decorators) {
  25639. nestedResult.push.apply(nestedResult, __spread(decorators));
  25640. }
  25641. parameters_1.push(nestedResult);
  25642. });
  25643. }
  25644. else if (parentType) {
  25645. parameters_1 = this.parameters(parentType);
  25646. }
  25647. if (!parameters_1) {
  25648. parameters_1 = [];
  25649. }
  25650. this.parameterCache.set(type, parameters_1);
  25651. }
  25652. return parameters_1;
  25653. }
  25654. catch (e) {
  25655. console.error("Failed on type " + JSON.stringify(type) + " with error " + e);
  25656. throw e;
  25657. }
  25658. };
  25659. StaticReflector.prototype._methodNames = function (type) {
  25660. var methodNames = this.methodCache.get(type);
  25661. if (!methodNames) {
  25662. var classMetadata = this.getTypeMetadata(type);
  25663. methodNames = {};
  25664. var parentType = this.findParentType(type, classMetadata);
  25665. if (parentType) {
  25666. var parentMethodNames_1 = this._methodNames(parentType);
  25667. Object.keys(parentMethodNames_1).forEach(function (parentProp) {
  25668. methodNames[parentProp] = parentMethodNames_1[parentProp];
  25669. });
  25670. }
  25671. var members_2 = classMetadata['members'] || {};
  25672. Object.keys(members_2).forEach(function (propName) {
  25673. var propData = members_2[propName];
  25674. var isMethod = propData.some(function (a) { return a['__symbolic'] == 'method'; });
  25675. methodNames[propName] = methodNames[propName] || isMethod;
  25676. });
  25677. this.methodCache.set(type, methodNames);
  25678. }
  25679. return methodNames;
  25680. };
  25681. StaticReflector.prototype._staticMembers = function (type) {
  25682. var staticMembers = this.staticCache.get(type);
  25683. if (!staticMembers) {
  25684. var classMetadata = this.getTypeMetadata(type);
  25685. var staticMemberData = classMetadata['statics'] || {};
  25686. staticMembers = Object.keys(staticMemberData);
  25687. this.staticCache.set(type, staticMembers);
  25688. }
  25689. return staticMembers;
  25690. };
  25691. StaticReflector.prototype.findParentType = function (type, classMetadata) {
  25692. var parentType = this.trySimplify(type, classMetadata['extends']);
  25693. if (parentType instanceof StaticSymbol) {
  25694. return parentType;
  25695. }
  25696. };
  25697. StaticReflector.prototype.hasLifecycleHook = function (type, lcProperty) {
  25698. if (!(type instanceof StaticSymbol)) {
  25699. this.reportError(new Error("hasLifecycleHook received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
  25700. }
  25701. try {
  25702. return !!this._methodNames(type)[lcProperty];
  25703. }
  25704. catch (e) {
  25705. console.error("Failed on type " + JSON.stringify(type) + " with error " + e);
  25706. throw e;
  25707. }
  25708. };
  25709. StaticReflector.prototype.guards = function (type) {
  25710. var e_1, _a;
  25711. if (!(type instanceof StaticSymbol)) {
  25712. this.reportError(new Error("guards received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
  25713. return {};
  25714. }
  25715. var staticMembers = this._staticMembers(type);
  25716. var result = {};
  25717. try {
  25718. for (var staticMembers_1 = __values(staticMembers), staticMembers_1_1 = staticMembers_1.next(); !staticMembers_1_1.done; staticMembers_1_1 = staticMembers_1.next()) {
  25719. var name_1 = staticMembers_1_1.value;
  25720. if (name_1.endsWith(TYPEGUARD_POSTFIX)) {
  25721. var property = name_1.substr(0, name_1.length - TYPEGUARD_POSTFIX.length);
  25722. var value = void 0;
  25723. if (property.endsWith(USE_IF)) {
  25724. property = name_1.substr(0, property.length - USE_IF.length);
  25725. value = USE_IF;
  25726. }
  25727. else {
  25728. value = this.getStaticSymbol(type.filePath, type.name, [name_1]);
  25729. }
  25730. result[property] = value;
  25731. }
  25732. }
  25733. }
  25734. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  25735. finally {
  25736. try {
  25737. if (staticMembers_1_1 && !staticMembers_1_1.done && (_a = staticMembers_1.return)) _a.call(staticMembers_1);
  25738. }
  25739. finally { if (e_1) throw e_1.error; }
  25740. }
  25741. return result;
  25742. };
  25743. StaticReflector.prototype._registerDecoratorOrConstructor = function (type, ctor) {
  25744. this.conversionMap.set(type, function (context, args) { return new (ctor.bind.apply(ctor, __spread([void 0], args)))(); });
  25745. };
  25746. StaticReflector.prototype._registerFunction = function (type, fn) {
  25747. this.conversionMap.set(type, function (context, args) { return fn.apply(undefined, args); });
  25748. };
  25749. StaticReflector.prototype.initializeConversionMap = function () {
  25750. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Injectable'), createInjectable);
  25751. this.injectionToken = this.findDeclaration(ANGULAR_CORE, 'InjectionToken');
  25752. this.opaqueToken = this.findDeclaration(ANGULAR_CORE, 'OpaqueToken');
  25753. this.ROUTES = this.tryFindDeclaration(ANGULAR_ROUTER, 'ROUTES');
  25754. this.ANALYZE_FOR_ENTRY_COMPONENTS =
  25755. this.findDeclaration(ANGULAR_CORE, 'ANALYZE_FOR_ENTRY_COMPONENTS');
  25756. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), createHost);
  25757. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), createSelf);
  25758. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), createSkipSelf);
  25759. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Inject'), createInject);
  25760. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Optional'), createOptional);
  25761. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Attribute'), createAttribute);
  25762. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ContentChild'), createContentChild);
  25763. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ContentChildren'), createContentChildren);
  25764. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ViewChild'), createViewChild);
  25765. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ViewChildren'), createViewChildren);
  25766. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Input'), createInput);
  25767. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Output'), createOutput);
  25768. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Pipe'), createPipe);
  25769. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'HostBinding'), createHostBinding);
  25770. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'HostListener'), createHostListener);
  25771. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Directive'), createDirective);
  25772. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Component'), createComponent);
  25773. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'NgModule'), createNgModule);
  25774. // Note: Some metadata classes can be used directly with Provider.deps.
  25775. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), createHost);
  25776. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), createSelf);
  25777. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), createSkipSelf);
  25778. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Optional'), createOptional);
  25779. };
  25780. /**
  25781. * getStaticSymbol produces a Type whose metadata is known but whose implementation is not loaded.
  25782. * All types passed to the StaticResolver should be pseudo-types returned by this method.
  25783. *
  25784. * @param declarationFile the absolute path of the file where the symbol is declared
  25785. * @param name the name of the type.
  25786. */
  25787. StaticReflector.prototype.getStaticSymbol = function (declarationFile, name, members) {
  25788. return this.symbolResolver.getStaticSymbol(declarationFile, name, members);
  25789. };
  25790. /**
  25791. * Simplify but discard any errors
  25792. */
  25793. StaticReflector.prototype.trySimplify = function (context, value) {
  25794. var originalRecorder = this.errorRecorder;
  25795. this.errorRecorder = function (error, fileName) { };
  25796. var result = this.simplify(context, value);
  25797. this.errorRecorder = originalRecorder;
  25798. return result;
  25799. };
  25800. /** @internal */
  25801. StaticReflector.prototype.simplify = function (context, value, lazy) {
  25802. if (lazy === void 0) { lazy = false; }
  25803. var self = this;
  25804. var scope = BindingScope$1.empty;
  25805. var calling = new Map();
  25806. function simplifyInContext(context, value, depth, references) {
  25807. function resolveReferenceValue(staticSymbol) {
  25808. var resolvedSymbol = self.symbolResolver.resolveSymbol(staticSymbol);
  25809. return resolvedSymbol ? resolvedSymbol.metadata : null;
  25810. }
  25811. function simplifyEagerly(value) {
  25812. return simplifyInContext(context, value, depth, 0);
  25813. }
  25814. function simplifyLazily(value) {
  25815. return simplifyInContext(context, value, depth, references + 1);
  25816. }
  25817. function simplifyNested(nestedContext, value) {
  25818. if (nestedContext === context) {
  25819. // If the context hasn't changed let the exception propagate unmodified.
  25820. return simplifyInContext(nestedContext, value, depth + 1, references);
  25821. }
  25822. try {
  25823. return simplifyInContext(nestedContext, value, depth + 1, references);
  25824. }
  25825. catch (e) {
  25826. if (isMetadataError(e)) {
  25827. // Propagate the message text up but add a message to the chain that explains how we got
  25828. // here.
  25829. // e.chain implies e.symbol
  25830. var summaryMsg = e.chain ? 'references \'' + e.symbol.name + '\'' : errorSummary(e);
  25831. var summary = "'" + nestedContext.name + "' " + summaryMsg;
  25832. var chain = { message: summary, position: e.position, next: e.chain };
  25833. // TODO(chuckj): retrieve the position information indirectly from the collectors node
  25834. // map if the metadata is from a .ts file.
  25835. self.error({
  25836. message: e.message,
  25837. advise: e.advise,
  25838. context: e.context, chain: chain,
  25839. symbol: nestedContext
  25840. }, context);
  25841. }
  25842. else {
  25843. // It is probably an internal error.
  25844. throw e;
  25845. }
  25846. }
  25847. }
  25848. function simplifyCall(functionSymbol, targetFunction, args, targetExpression) {
  25849. if (targetFunction && targetFunction['__symbolic'] == 'function') {
  25850. if (calling.get(functionSymbol)) {
  25851. self.error({
  25852. message: 'Recursion is not supported',
  25853. summary: "called '" + functionSymbol.name + "' recursively",
  25854. value: targetFunction
  25855. }, functionSymbol);
  25856. }
  25857. try {
  25858. var value_1 = targetFunction['value'];
  25859. if (value_1 && (depth != 0 || value_1.__symbolic != 'error')) {
  25860. var parameters = targetFunction['parameters'];
  25861. var defaults = targetFunction.defaults;
  25862. args = args.map(function (arg) { return simplifyNested(context, arg); })
  25863. .map(function (arg) { return shouldIgnore(arg) ? undefined : arg; });
  25864. if (defaults && defaults.length > args.length) {
  25865. args.push.apply(args, __spread(defaults.slice(args.length).map(function (value) { return simplify(value); })));
  25866. }
  25867. calling.set(functionSymbol, true);
  25868. var functionScope = BindingScope$1.build();
  25869. for (var i = 0; i < parameters.length; i++) {
  25870. functionScope.define(parameters[i], args[i]);
  25871. }
  25872. var oldScope = scope;
  25873. var result_1;
  25874. try {
  25875. scope = functionScope.done();
  25876. result_1 = simplifyNested(functionSymbol, value_1);
  25877. }
  25878. finally {
  25879. scope = oldScope;
  25880. }
  25881. return result_1;
  25882. }
  25883. }
  25884. finally {
  25885. calling.delete(functionSymbol);
  25886. }
  25887. }
  25888. if (depth === 0) {
  25889. // If depth is 0 we are evaluating the top level expression that is describing element
  25890. // decorator. In this case, it is a decorator we don't understand, such as a custom
  25891. // non-angular decorator, and we should just ignore it.
  25892. return IGNORE;
  25893. }
  25894. var position = undefined;
  25895. if (targetExpression && targetExpression.__symbolic == 'resolved') {
  25896. var line = targetExpression.line;
  25897. var character = targetExpression.character;
  25898. var fileName = targetExpression.fileName;
  25899. if (fileName != null && line != null && character != null) {
  25900. position = { fileName: fileName, line: line, column: character };
  25901. }
  25902. }
  25903. self.error({
  25904. message: FUNCTION_CALL_NOT_SUPPORTED,
  25905. context: functionSymbol,
  25906. value: targetFunction, position: position
  25907. }, context);
  25908. }
  25909. function simplify(expression) {
  25910. var e_2, _a, e_3, _b;
  25911. if (isPrimitive(expression)) {
  25912. return expression;
  25913. }
  25914. if (expression instanceof Array) {
  25915. var result_2 = [];
  25916. try {
  25917. for (var _c = __values(expression), _d = _c.next(); !_d.done; _d = _c.next()) {
  25918. var item = _d.value;
  25919. // Check for a spread expression
  25920. if (item && item.__symbolic === 'spread') {
  25921. // We call with references as 0 because we require the actual value and cannot
  25922. // tolerate a reference here.
  25923. var spreadArray = simplifyEagerly(item.expression);
  25924. if (Array.isArray(spreadArray)) {
  25925. try {
  25926. for (var spreadArray_1 = __values(spreadArray), spreadArray_1_1 = spreadArray_1.next(); !spreadArray_1_1.done; spreadArray_1_1 = spreadArray_1.next()) {
  25927. var spreadItem = spreadArray_1_1.value;
  25928. result_2.push(spreadItem);
  25929. }
  25930. }
  25931. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  25932. finally {
  25933. try {
  25934. if (spreadArray_1_1 && !spreadArray_1_1.done && (_b = spreadArray_1.return)) _b.call(spreadArray_1);
  25935. }
  25936. finally { if (e_3) throw e_3.error; }
  25937. }
  25938. continue;
  25939. }
  25940. }
  25941. var value_2 = simplify(item);
  25942. if (shouldIgnore(value_2)) {
  25943. continue;
  25944. }
  25945. result_2.push(value_2);
  25946. }
  25947. }
  25948. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  25949. finally {
  25950. try {
  25951. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  25952. }
  25953. finally { if (e_2) throw e_2.error; }
  25954. }
  25955. return result_2;
  25956. }
  25957. if (expression instanceof StaticSymbol) {
  25958. // Stop simplification at builtin symbols or if we are in a reference context and
  25959. // the symbol doesn't have members.
  25960. if (expression === self.injectionToken || self.conversionMap.has(expression) ||
  25961. (references > 0 && !expression.members.length)) {
  25962. return expression;
  25963. }
  25964. else {
  25965. var staticSymbol = expression;
  25966. var declarationValue = resolveReferenceValue(staticSymbol);
  25967. if (declarationValue != null) {
  25968. return simplifyNested(staticSymbol, declarationValue);
  25969. }
  25970. else {
  25971. return staticSymbol;
  25972. }
  25973. }
  25974. }
  25975. if (expression) {
  25976. if (expression['__symbolic']) {
  25977. var staticSymbol = void 0;
  25978. switch (expression['__symbolic']) {
  25979. case 'binop':
  25980. var left = simplify(expression['left']);
  25981. if (shouldIgnore(left))
  25982. return left;
  25983. var right = simplify(expression['right']);
  25984. if (shouldIgnore(right))
  25985. return right;
  25986. switch (expression['operator']) {
  25987. case '&&':
  25988. return left && right;
  25989. case '||':
  25990. return left || right;
  25991. case '|':
  25992. return left | right;
  25993. case '^':
  25994. return left ^ right;
  25995. case '&':
  25996. return left & right;
  25997. case '==':
  25998. return left == right;
  25999. case '!=':
  26000. return left != right;
  26001. case '===':
  26002. return left === right;
  26003. case '!==':
  26004. return left !== right;
  26005. case '<':
  26006. return left < right;
  26007. case '>':
  26008. return left > right;
  26009. case '<=':
  26010. return left <= right;
  26011. case '>=':
  26012. return left >= right;
  26013. case '<<':
  26014. return left << right;
  26015. case '>>':
  26016. return left >> right;
  26017. case '+':
  26018. return left + right;
  26019. case '-':
  26020. return left - right;
  26021. case '*':
  26022. return left * right;
  26023. case '/':
  26024. return left / right;
  26025. case '%':
  26026. return left % right;
  26027. }
  26028. return null;
  26029. case 'if':
  26030. var condition = simplify(expression['condition']);
  26031. return condition ? simplify(expression['thenExpression']) :
  26032. simplify(expression['elseExpression']);
  26033. case 'pre':
  26034. var operand = simplify(expression['operand']);
  26035. if (shouldIgnore(operand))
  26036. return operand;
  26037. switch (expression['operator']) {
  26038. case '+':
  26039. return operand;
  26040. case '-':
  26041. return -operand;
  26042. case '!':
  26043. return !operand;
  26044. case '~':
  26045. return ~operand;
  26046. }
  26047. return null;
  26048. case 'index':
  26049. var indexTarget = simplifyEagerly(expression['expression']);
  26050. var index = simplifyEagerly(expression['index']);
  26051. if (indexTarget && isPrimitive(index))
  26052. return indexTarget[index];
  26053. return null;
  26054. case 'select':
  26055. var member = expression['member'];
  26056. var selectContext = context;
  26057. var selectTarget = simplify(expression['expression']);
  26058. if (selectTarget instanceof StaticSymbol) {
  26059. var members = selectTarget.members.concat(member);
  26060. selectContext =
  26061. self.getStaticSymbol(selectTarget.filePath, selectTarget.name, members);
  26062. var declarationValue = resolveReferenceValue(selectContext);
  26063. if (declarationValue != null) {
  26064. return simplifyNested(selectContext, declarationValue);
  26065. }
  26066. else {
  26067. return selectContext;
  26068. }
  26069. }
  26070. if (selectTarget && isPrimitive(member))
  26071. return simplifyNested(selectContext, selectTarget[member]);
  26072. return null;
  26073. case 'reference':
  26074. // Note: This only has to deal with variable references, as symbol references have
  26075. // been converted into 'resolved'
  26076. // in the StaticSymbolResolver.
  26077. var name_2 = expression['name'];
  26078. var localValue = scope.resolve(name_2);
  26079. if (localValue != BindingScope$1.missing) {
  26080. return localValue;
  26081. }
  26082. break;
  26083. case 'resolved':
  26084. try {
  26085. return simplify(expression.symbol);
  26086. }
  26087. catch (e) {
  26088. // If an error is reported evaluating the symbol record the position of the
  26089. // reference in the error so it can
  26090. // be reported in the error message generated from the exception.
  26091. if (isMetadataError(e) && expression.fileName != null &&
  26092. expression.line != null && expression.character != null) {
  26093. e.position = {
  26094. fileName: expression.fileName,
  26095. line: expression.line,
  26096. column: expression.character
  26097. };
  26098. }
  26099. throw e;
  26100. }
  26101. case 'class':
  26102. return context;
  26103. case 'function':
  26104. return context;
  26105. case 'new':
  26106. case 'call':
  26107. // Determine if the function is a built-in conversion
  26108. staticSymbol = simplifyInContext(context, expression['expression'], depth + 1, /* references */ 0);
  26109. if (staticSymbol instanceof StaticSymbol) {
  26110. if (staticSymbol === self.injectionToken || staticSymbol === self.opaqueToken) {
  26111. // if somebody calls new InjectionToken, don't create an InjectionToken,
  26112. // but rather return the symbol to which the InjectionToken is assigned to.
  26113. // OpaqueToken is supported too as it is required by the language service to
  26114. // support v4 and prior versions of Angular.
  26115. return context;
  26116. }
  26117. var argExpressions = expression['arguments'] || [];
  26118. var converter = self.conversionMap.get(staticSymbol);
  26119. if (converter) {
  26120. var args = argExpressions.map(function (arg) { return simplifyNested(context, arg); })
  26121. .map(function (arg) { return shouldIgnore(arg) ? undefined : arg; });
  26122. return converter(context, args);
  26123. }
  26124. else {
  26125. // Determine if the function is one we can simplify.
  26126. var targetFunction = resolveReferenceValue(staticSymbol);
  26127. return simplifyCall(staticSymbol, targetFunction, argExpressions, expression['expression']);
  26128. }
  26129. }
  26130. return IGNORE;
  26131. case 'error':
  26132. var message = expression.message;
  26133. if (expression['line'] != null) {
  26134. self.error({
  26135. message: message,
  26136. context: expression.context,
  26137. value: expression,
  26138. position: {
  26139. fileName: expression['fileName'],
  26140. line: expression['line'],
  26141. column: expression['character']
  26142. }
  26143. }, context);
  26144. }
  26145. else {
  26146. self.error({ message: message, context: expression.context }, context);
  26147. }
  26148. return IGNORE;
  26149. case 'ignore':
  26150. return expression;
  26151. }
  26152. return null;
  26153. }
  26154. return mapStringMap(expression, function (value, name) {
  26155. if (REFERENCE_SET.has(name)) {
  26156. if (name === USE_VALUE$1 && PROVIDE in expression) {
  26157. // If this is a provider expression, check for special tokens that need the value
  26158. // during analysis.
  26159. var provide = simplify(expression.provide);
  26160. if (provide === self.ROUTES || provide == self.ANALYZE_FOR_ENTRY_COMPONENTS) {
  26161. return simplify(value);
  26162. }
  26163. }
  26164. return simplifyLazily(value);
  26165. }
  26166. return simplify(value);
  26167. });
  26168. }
  26169. return IGNORE;
  26170. }
  26171. return simplify(value);
  26172. }
  26173. var result;
  26174. try {
  26175. result = simplifyInContext(context, value, 0, lazy ? 1 : 0);
  26176. }
  26177. catch (e) {
  26178. if (this.errorRecorder) {
  26179. this.reportError(e, context);
  26180. }
  26181. else {
  26182. throw formatMetadataError(e, context);
  26183. }
  26184. }
  26185. if (shouldIgnore(result)) {
  26186. return undefined;
  26187. }
  26188. return result;
  26189. };
  26190. StaticReflector.prototype.getTypeMetadata = function (type) {
  26191. var resolvedSymbol = this.symbolResolver.resolveSymbol(type);
  26192. return resolvedSymbol && resolvedSymbol.metadata ? resolvedSymbol.metadata :
  26193. { __symbolic: 'class' };
  26194. };
  26195. StaticReflector.prototype.reportError = function (error, context, path) {
  26196. if (this.errorRecorder) {
  26197. this.errorRecorder(formatMetadataError(error, context), (context && context.filePath) || path);
  26198. }
  26199. else {
  26200. throw error;
  26201. }
  26202. };
  26203. StaticReflector.prototype.error = function (_a, reportingContext) {
  26204. 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;
  26205. this.reportError(metadataError(message, summary, advise, position, symbol, context, chain), reportingContext);
  26206. };
  26207. return StaticReflector;
  26208. }());
  26209. var METADATA_ERROR = 'ngMetadataError';
  26210. function metadataError(message, summary, advise, position, symbol, context, chain) {
  26211. var error = syntaxError(message);
  26212. error[METADATA_ERROR] = true;
  26213. if (advise)
  26214. error.advise = advise;
  26215. if (position)
  26216. error.position = position;
  26217. if (summary)
  26218. error.summary = summary;
  26219. if (context)
  26220. error.context = context;
  26221. if (chain)
  26222. error.chain = chain;
  26223. if (symbol)
  26224. error.symbol = symbol;
  26225. return error;
  26226. }
  26227. function isMetadataError(error) {
  26228. return !!error[METADATA_ERROR];
  26229. }
  26230. var REFERENCE_TO_NONEXPORTED_CLASS = 'Reference to non-exported class';
  26231. var VARIABLE_NOT_INITIALIZED = 'Variable not initialized';
  26232. var DESTRUCTURE_NOT_SUPPORTED = 'Destructuring not supported';
  26233. var COULD_NOT_RESOLVE_TYPE = 'Could not resolve type';
  26234. var FUNCTION_CALL_NOT_SUPPORTED = 'Function call not supported';
  26235. var REFERENCE_TO_LOCAL_SYMBOL = 'Reference to a local symbol';
  26236. var LAMBDA_NOT_SUPPORTED = 'Lambda not supported';
  26237. function expandedMessage(message, context) {
  26238. switch (message) {
  26239. case REFERENCE_TO_NONEXPORTED_CLASS:
  26240. if (context && context.className) {
  26241. return "References to a non-exported class are not supported in decorators but " + context.className + " was referenced.";
  26242. }
  26243. break;
  26244. case VARIABLE_NOT_INITIALIZED:
  26245. return 'Only initialized variables and constants can be referenced in decorators because the value of this variable is needed by the template compiler';
  26246. case DESTRUCTURE_NOT_SUPPORTED:
  26247. return 'Referencing an exported destructured variable or constant is not supported in decorators and this value is needed by the template compiler';
  26248. case COULD_NOT_RESOLVE_TYPE:
  26249. if (context && context.typeName) {
  26250. return "Could not resolve type " + context.typeName;
  26251. }
  26252. break;
  26253. case FUNCTION_CALL_NOT_SUPPORTED:
  26254. if (context && context.name) {
  26255. return "Function calls are not supported in decorators but '" + context.name + "' was called";
  26256. }
  26257. return 'Function calls are not supported in decorators';
  26258. case REFERENCE_TO_LOCAL_SYMBOL:
  26259. if (context && context.name) {
  26260. return "Reference to a local (non-exported) symbols are not supported in decorators but '" + context.name + "' was referenced";
  26261. }
  26262. break;
  26263. case LAMBDA_NOT_SUPPORTED:
  26264. return "Function expressions are not supported in decorators";
  26265. }
  26266. return message;
  26267. }
  26268. function messageAdvise(message, context) {
  26269. switch (message) {
  26270. case REFERENCE_TO_NONEXPORTED_CLASS:
  26271. if (context && context.className) {
  26272. return "Consider exporting '" + context.className + "'";
  26273. }
  26274. break;
  26275. case DESTRUCTURE_NOT_SUPPORTED:
  26276. return 'Consider simplifying to avoid destructuring';
  26277. case REFERENCE_TO_LOCAL_SYMBOL:
  26278. if (context && context.name) {
  26279. return "Consider exporting '" + context.name + "'";
  26280. }
  26281. break;
  26282. case LAMBDA_NOT_SUPPORTED:
  26283. return "Consider changing the function expression into an exported function";
  26284. }
  26285. return undefined;
  26286. }
  26287. function errorSummary(error) {
  26288. if (error.summary) {
  26289. return error.summary;
  26290. }
  26291. switch (error.message) {
  26292. case REFERENCE_TO_NONEXPORTED_CLASS:
  26293. if (error.context && error.context.className) {
  26294. return "references non-exported class " + error.context.className;
  26295. }
  26296. break;
  26297. case VARIABLE_NOT_INITIALIZED:
  26298. return 'is not initialized';
  26299. case DESTRUCTURE_NOT_SUPPORTED:
  26300. return 'is a destructured variable';
  26301. case COULD_NOT_RESOLVE_TYPE:
  26302. return 'could not be resolved';
  26303. case FUNCTION_CALL_NOT_SUPPORTED:
  26304. if (error.context && error.context.name) {
  26305. return "calls '" + error.context.name + "'";
  26306. }
  26307. return "calls a function";
  26308. case REFERENCE_TO_LOCAL_SYMBOL:
  26309. if (error.context && error.context.name) {
  26310. return "references local variable " + error.context.name;
  26311. }
  26312. return "references a local variable";
  26313. }
  26314. return 'contains the error';
  26315. }
  26316. function mapStringMap(input, transform) {
  26317. if (!input)
  26318. return {};
  26319. var result = {};
  26320. Object.keys(input).forEach(function (key) {
  26321. var value = transform(input[key], key);
  26322. if (!shouldIgnore(value)) {
  26323. if (HIDDEN_KEY.test(key)) {
  26324. Object.defineProperty(result, key, { enumerable: false, configurable: true, value: value });
  26325. }
  26326. else {
  26327. result[key] = value;
  26328. }
  26329. }
  26330. });
  26331. return result;
  26332. }
  26333. function isPrimitive(o) {
  26334. return o === null || (typeof o !== 'function' && typeof o !== 'object');
  26335. }
  26336. var BindingScope$1 = /** @class */ (function () {
  26337. function BindingScope() {
  26338. }
  26339. BindingScope.build = function () {
  26340. var current = new Map();
  26341. return {
  26342. define: function (name, value) {
  26343. current.set(name, value);
  26344. return this;
  26345. },
  26346. done: function () {
  26347. return current.size > 0 ? new PopulatedScope(current) : BindingScope.empty;
  26348. }
  26349. };
  26350. };
  26351. BindingScope.missing = {};
  26352. BindingScope.empty = { resolve: function (name) { return BindingScope.missing; } };
  26353. return BindingScope;
  26354. }());
  26355. var PopulatedScope = /** @class */ (function (_super) {
  26356. __extends(PopulatedScope, _super);
  26357. function PopulatedScope(bindings) {
  26358. var _this = _super.call(this) || this;
  26359. _this.bindings = bindings;
  26360. return _this;
  26361. }
  26362. PopulatedScope.prototype.resolve = function (name) {
  26363. return this.bindings.has(name) ? this.bindings.get(name) : BindingScope$1.missing;
  26364. };
  26365. return PopulatedScope;
  26366. }(BindingScope$1));
  26367. function formatMetadataMessageChain(chain, advise) {
  26368. var expanded = expandedMessage(chain.message, chain.context);
  26369. var nesting = chain.symbol ? " in '" + chain.symbol.name + "'" : '';
  26370. var message = "" + expanded + nesting;
  26371. var position = chain.position;
  26372. var next = chain.next ?
  26373. formatMetadataMessageChain(chain.next, advise) :
  26374. advise ? { message: advise } : undefined;
  26375. return { message: message, position: position, next: next };
  26376. }
  26377. function formatMetadataError(e, context) {
  26378. if (isMetadataError(e)) {
  26379. // Produce a formatted version of the and leaving enough information in the original error
  26380. // to recover the formatting information to eventually produce a diagnostic error message.
  26381. var position = e.position;
  26382. var chain = {
  26383. message: "Error during template compile of '" + context.name + "'",
  26384. position: position,
  26385. next: { message: e.message, next: e.chain, context: e.context, symbol: e.symbol }
  26386. };
  26387. var advise = e.advise || messageAdvise(e.message, e.context);
  26388. return formattedError(formatMetadataMessageChain(chain, advise));
  26389. }
  26390. return e;
  26391. }
  26392. /**
  26393. * @license
  26394. * Copyright Google Inc. All Rights Reserved.
  26395. *
  26396. * Use of this source code is governed by an MIT-style license that can be
  26397. * found in the LICENSE file at https://angular.io/license
  26398. */
  26399. var AotSummaryResolver = /** @class */ (function () {
  26400. function AotSummaryResolver(host, staticSymbolCache) {
  26401. this.host = host;
  26402. this.staticSymbolCache = staticSymbolCache;
  26403. // Note: this will only contain StaticSymbols without members!
  26404. this.summaryCache = new Map();
  26405. this.loadedFilePaths = new Map();
  26406. // Note: this will only contain StaticSymbols without members!
  26407. this.importAs = new Map();
  26408. this.knownFileNameToModuleNames = new Map();
  26409. }
  26410. AotSummaryResolver.prototype.isLibraryFile = function (filePath) {
  26411. // Note: We need to strip the .ngfactory. file path,
  26412. // so this method also works for generated files
  26413. // (for which host.isSourceFile will always return false).
  26414. return !this.host.isSourceFile(stripGeneratedFileSuffix(filePath));
  26415. };
  26416. AotSummaryResolver.prototype.toSummaryFileName = function (filePath, referringSrcFileName) {
  26417. return this.host.toSummaryFileName(filePath, referringSrcFileName);
  26418. };
  26419. AotSummaryResolver.prototype.fromSummaryFileName = function (fileName, referringLibFileName) {
  26420. return this.host.fromSummaryFileName(fileName, referringLibFileName);
  26421. };
  26422. AotSummaryResolver.prototype.resolveSummary = function (staticSymbol) {
  26423. var rootSymbol = staticSymbol.members.length ?
  26424. this.staticSymbolCache.get(staticSymbol.filePath, staticSymbol.name) :
  26425. staticSymbol;
  26426. var summary = this.summaryCache.get(rootSymbol);
  26427. if (!summary) {
  26428. this._loadSummaryFile(staticSymbol.filePath);
  26429. summary = this.summaryCache.get(staticSymbol);
  26430. }
  26431. return (rootSymbol === staticSymbol && summary) || null;
  26432. };
  26433. AotSummaryResolver.prototype.getSymbolsOf = function (filePath) {
  26434. if (this._loadSummaryFile(filePath)) {
  26435. return Array.from(this.summaryCache.keys()).filter(function (symbol) { return symbol.filePath === filePath; });
  26436. }
  26437. return null;
  26438. };
  26439. AotSummaryResolver.prototype.getImportAs = function (staticSymbol) {
  26440. staticSymbol.assertNoMembers();
  26441. return this.importAs.get(staticSymbol);
  26442. };
  26443. /**
  26444. * Converts a file path to a module name that can be used as an `import`.
  26445. */
  26446. AotSummaryResolver.prototype.getKnownModuleName = function (importedFilePath) {
  26447. return this.knownFileNameToModuleNames.get(importedFilePath) || null;
  26448. };
  26449. AotSummaryResolver.prototype.addSummary = function (summary) { this.summaryCache.set(summary.symbol, summary); };
  26450. AotSummaryResolver.prototype._loadSummaryFile = function (filePath) {
  26451. var _this = this;
  26452. var hasSummary = this.loadedFilePaths.get(filePath);
  26453. if (hasSummary != null) {
  26454. return hasSummary;
  26455. }
  26456. var json = null;
  26457. if (this.isLibraryFile(filePath)) {
  26458. var summaryFilePath = summaryFileName(filePath);
  26459. try {
  26460. json = this.host.loadSummary(summaryFilePath);
  26461. }
  26462. catch (e) {
  26463. console.error("Error loading summary file " + summaryFilePath);
  26464. throw e;
  26465. }
  26466. }
  26467. hasSummary = json != null;
  26468. this.loadedFilePaths.set(filePath, hasSummary);
  26469. if (json) {
  26470. var _a = deserializeSummaries(this.staticSymbolCache, this, filePath, json), moduleName = _a.moduleName, summaries = _a.summaries, importAs = _a.importAs;
  26471. summaries.forEach(function (summary) { return _this.summaryCache.set(summary.symbol, summary); });
  26472. if (moduleName) {
  26473. this.knownFileNameToModuleNames.set(filePath, moduleName);
  26474. }
  26475. importAs.forEach(function (importAs) { _this.importAs.set(importAs.symbol, importAs.importAs); });
  26476. }
  26477. return hasSummary;
  26478. };
  26479. return AotSummaryResolver;
  26480. }());
  26481. /**
  26482. * @license
  26483. * Copyright Google Inc. All Rights Reserved.
  26484. *
  26485. * Use of this source code is governed by an MIT-style license that can be
  26486. * found in the LICENSE file at https://angular.io/license
  26487. */
  26488. function createAotUrlResolver(host) {
  26489. return {
  26490. resolve: function (basePath, url) {
  26491. var filePath = host.resourceNameToFileName(url, basePath);
  26492. if (!filePath) {
  26493. throw syntaxError("Couldn't resolve resource " + url + " from " + basePath);
  26494. }
  26495. return filePath;
  26496. }
  26497. };
  26498. }
  26499. /**
  26500. * Creates a new AotCompiler based on options and a host.
  26501. */
  26502. function createAotCompiler(compilerHost, options, errorCollector) {
  26503. var translations = options.translations || '';
  26504. var urlResolver = createAotUrlResolver(compilerHost);
  26505. var symbolCache = new StaticSymbolCache();
  26506. var summaryResolver = new AotSummaryResolver(compilerHost, symbolCache);
  26507. var symbolResolver = new StaticSymbolResolver(compilerHost, symbolCache, summaryResolver);
  26508. var staticReflector = new StaticReflector(summaryResolver, symbolResolver, [], [], errorCollector);
  26509. var htmlParser;
  26510. if (!!options.enableIvy) {
  26511. // Ivy handles i18n at the compiler level so we must use a regular parser
  26512. htmlParser = new HtmlParser();
  26513. }
  26514. else {
  26515. htmlParser = new I18NHtmlParser(new HtmlParser(), translations, options.i18nFormat, options.missingTranslation, console);
  26516. }
  26517. var config = new CompilerConfig({
  26518. defaultEncapsulation: ViewEncapsulation.Emulated,
  26519. useJit: false,
  26520. missingTranslation: options.missingTranslation,
  26521. preserveWhitespaces: options.preserveWhitespaces,
  26522. strictInjectionParameters: options.strictInjectionParameters,
  26523. });
  26524. var normalizer = new DirectiveNormalizer({ get: function (url) { return compilerHost.loadResource(url); } }, urlResolver, htmlParser, config);
  26525. var expressionParser = new Parser$1(new Lexer());
  26526. var elementSchemaRegistry = new DomElementSchemaRegistry();
  26527. var tmplParser = new TemplateParser(config, staticReflector, expressionParser, elementSchemaRegistry, htmlParser, console, []);
  26528. var resolver = new CompileMetadataResolver(config, htmlParser, new NgModuleResolver(staticReflector), new DirectiveResolver(staticReflector), new PipeResolver(staticReflector), summaryResolver, elementSchemaRegistry, normalizer, console, symbolCache, staticReflector, errorCollector);
  26529. // TODO(vicb): do not pass options.i18nFormat here
  26530. var viewCompiler = new ViewCompiler(staticReflector);
  26531. var typeCheckCompiler = new TypeCheckCompiler(options, staticReflector);
  26532. 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);
  26533. return { compiler: compiler, reflector: staticReflector };
  26534. }
  26535. var SummaryResolver = /** @class */ (function () {
  26536. function SummaryResolver() {
  26537. }
  26538. return SummaryResolver;
  26539. }());
  26540. var JitSummaryResolver = /** @class */ (function () {
  26541. function JitSummaryResolver() {
  26542. this._summaries = new Map();
  26543. }
  26544. JitSummaryResolver.prototype.isLibraryFile = function () { return false; };
  26545. JitSummaryResolver.prototype.toSummaryFileName = function (fileName) { return fileName; };
  26546. JitSummaryResolver.prototype.fromSummaryFileName = function (fileName) { return fileName; };
  26547. JitSummaryResolver.prototype.resolveSummary = function (reference) {
  26548. return this._summaries.get(reference) || null;
  26549. };
  26550. JitSummaryResolver.prototype.getSymbolsOf = function () { return []; };
  26551. JitSummaryResolver.prototype.getImportAs = function (reference) { return reference; };
  26552. JitSummaryResolver.prototype.getKnownModuleName = function (fileName) { return null; };
  26553. JitSummaryResolver.prototype.addSummary = function (summary) { this._summaries.set(summary.symbol, summary); };
  26554. return JitSummaryResolver;
  26555. }());
  26556. /**
  26557. * @license
  26558. * Copyright Google Inc. All Rights Reserved.
  26559. *
  26560. * Use of this source code is governed by an MIT-style license that can be
  26561. * found in the LICENSE file at https://angular.io/license
  26562. */
  26563. function interpretStatements(statements, reflector) {
  26564. var ctx = new _ExecutionContext(null, null, null, new Map());
  26565. var visitor = new StatementInterpreter(reflector);
  26566. visitor.visitAllStatements(statements, ctx);
  26567. var result = {};
  26568. ctx.exports.forEach(function (exportName) { result[exportName] = ctx.vars.get(exportName); });
  26569. return result;
  26570. }
  26571. function _executeFunctionStatements(varNames, varValues, statements, ctx, visitor) {
  26572. var childCtx = ctx.createChildWihtLocalVars();
  26573. for (var i = 0; i < varNames.length; i++) {
  26574. childCtx.vars.set(varNames[i], varValues[i]);
  26575. }
  26576. var result = visitor.visitAllStatements(statements, childCtx);
  26577. return result ? result.value : null;
  26578. }
  26579. var _ExecutionContext = /** @class */ (function () {
  26580. function _ExecutionContext(parent, instance, className, vars) {
  26581. this.parent = parent;
  26582. this.instance = instance;
  26583. this.className = className;
  26584. this.vars = vars;
  26585. this.exports = [];
  26586. }
  26587. _ExecutionContext.prototype.createChildWihtLocalVars = function () {
  26588. return new _ExecutionContext(this, this.instance, this.className, new Map());
  26589. };
  26590. return _ExecutionContext;
  26591. }());
  26592. var ReturnValue = /** @class */ (function () {
  26593. function ReturnValue(value) {
  26594. this.value = value;
  26595. }
  26596. return ReturnValue;
  26597. }());
  26598. function createDynamicClass(_classStmt, _ctx, _visitor) {
  26599. var propertyDescriptors = {};
  26600. _classStmt.getters.forEach(function (getter) {
  26601. // Note: use `function` instead of arrow function to capture `this`
  26602. propertyDescriptors[getter.name] = {
  26603. configurable: false,
  26604. get: function () {
  26605. var instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
  26606. return _executeFunctionStatements([], [], getter.body, instanceCtx, _visitor);
  26607. }
  26608. };
  26609. });
  26610. _classStmt.methods.forEach(function (method) {
  26611. var paramNames = method.params.map(function (param) { return param.name; });
  26612. // Note: use `function` instead of arrow function to capture `this`
  26613. propertyDescriptors[method.name] = {
  26614. writable: false,
  26615. configurable: false,
  26616. value: function () {
  26617. var args = [];
  26618. for (var _i = 0; _i < arguments.length; _i++) {
  26619. args[_i] = arguments[_i];
  26620. }
  26621. var instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
  26622. return _executeFunctionStatements(paramNames, args, method.body, instanceCtx, _visitor);
  26623. }
  26624. };
  26625. });
  26626. var ctorParamNames = _classStmt.constructorMethod.params.map(function (param) { return param.name; });
  26627. // Note: use `function` instead of arrow function to capture `this`
  26628. var ctor = function () {
  26629. var _this = this;
  26630. var args = [];
  26631. for (var _i = 0; _i < arguments.length; _i++) {
  26632. args[_i] = arguments[_i];
  26633. }
  26634. var instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
  26635. _classStmt.fields.forEach(function (field) { _this[field.name] = undefined; });
  26636. _executeFunctionStatements(ctorParamNames, args, _classStmt.constructorMethod.body, instanceCtx, _visitor);
  26637. };
  26638. var superClass = _classStmt.parent ? _classStmt.parent.visitExpression(_visitor, _ctx) : Object;
  26639. ctor.prototype = Object.create(superClass.prototype, propertyDescriptors);
  26640. return ctor;
  26641. }
  26642. var StatementInterpreter = /** @class */ (function () {
  26643. function StatementInterpreter(reflector) {
  26644. this.reflector = reflector;
  26645. }
  26646. StatementInterpreter.prototype.debugAst = function (ast) { return debugOutputAstAsTypeScript(ast); };
  26647. StatementInterpreter.prototype.visitDeclareVarStmt = function (stmt, ctx) {
  26648. var initialValue = stmt.value ? stmt.value.visitExpression(this, ctx) : undefined;
  26649. ctx.vars.set(stmt.name, initialValue);
  26650. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  26651. ctx.exports.push(stmt.name);
  26652. }
  26653. return null;
  26654. };
  26655. StatementInterpreter.prototype.visitWriteVarExpr = function (expr, ctx) {
  26656. var value = expr.value.visitExpression(this, ctx);
  26657. var currCtx = ctx;
  26658. while (currCtx != null) {
  26659. if (currCtx.vars.has(expr.name)) {
  26660. currCtx.vars.set(expr.name, value);
  26661. return value;
  26662. }
  26663. currCtx = currCtx.parent;
  26664. }
  26665. throw new Error("Not declared variable " + expr.name);
  26666. };
  26667. StatementInterpreter.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  26668. throw new Error('Cannot interpret a WrappedNodeExpr.');
  26669. };
  26670. StatementInterpreter.prototype.visitTypeofExpr = function (ast, ctx) {
  26671. throw new Error('Cannot interpret a TypeofExpr');
  26672. };
  26673. StatementInterpreter.prototype.visitReadVarExpr = function (ast, ctx) {
  26674. var varName = ast.name;
  26675. if (ast.builtin != null) {
  26676. switch (ast.builtin) {
  26677. case exports.BuiltinVar.Super:
  26678. return ctx.instance.__proto__;
  26679. case exports.BuiltinVar.This:
  26680. return ctx.instance;
  26681. case exports.BuiltinVar.CatchError:
  26682. varName = CATCH_ERROR_VAR$2;
  26683. break;
  26684. case exports.BuiltinVar.CatchStack:
  26685. varName = CATCH_STACK_VAR$2;
  26686. break;
  26687. default:
  26688. throw new Error("Unknown builtin variable " + ast.builtin);
  26689. }
  26690. }
  26691. var currCtx = ctx;
  26692. while (currCtx != null) {
  26693. if (currCtx.vars.has(varName)) {
  26694. return currCtx.vars.get(varName);
  26695. }
  26696. currCtx = currCtx.parent;
  26697. }
  26698. throw new Error("Not declared variable " + varName);
  26699. };
  26700. StatementInterpreter.prototype.visitWriteKeyExpr = function (expr, ctx) {
  26701. var receiver = expr.receiver.visitExpression(this, ctx);
  26702. var index = expr.index.visitExpression(this, ctx);
  26703. var value = expr.value.visitExpression(this, ctx);
  26704. receiver[index] = value;
  26705. return value;
  26706. };
  26707. StatementInterpreter.prototype.visitWritePropExpr = function (expr, ctx) {
  26708. var receiver = expr.receiver.visitExpression(this, ctx);
  26709. var value = expr.value.visitExpression(this, ctx);
  26710. receiver[expr.name] = value;
  26711. return value;
  26712. };
  26713. StatementInterpreter.prototype.visitInvokeMethodExpr = function (expr, ctx) {
  26714. var receiver = expr.receiver.visitExpression(this, ctx);
  26715. var args = this.visitAllExpressions(expr.args, ctx);
  26716. var result;
  26717. if (expr.builtin != null) {
  26718. switch (expr.builtin) {
  26719. case exports.BuiltinMethod.ConcatArray:
  26720. result = receiver.concat.apply(receiver, __spread(args));
  26721. break;
  26722. case exports.BuiltinMethod.SubscribeObservable:
  26723. result = receiver.subscribe({ next: args[0] });
  26724. break;
  26725. case exports.BuiltinMethod.Bind:
  26726. result = receiver.bind.apply(receiver, __spread(args));
  26727. break;
  26728. default:
  26729. throw new Error("Unknown builtin method " + expr.builtin);
  26730. }
  26731. }
  26732. else {
  26733. result = receiver[expr.name].apply(receiver, args);
  26734. }
  26735. return result;
  26736. };
  26737. StatementInterpreter.prototype.visitInvokeFunctionExpr = function (stmt, ctx) {
  26738. var args = this.visitAllExpressions(stmt.args, ctx);
  26739. var fnExpr = stmt.fn;
  26740. if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === exports.BuiltinVar.Super) {
  26741. ctx.instance.constructor.prototype.constructor.apply(ctx.instance, args);
  26742. return null;
  26743. }
  26744. else {
  26745. var fn = stmt.fn.visitExpression(this, ctx);
  26746. return fn.apply(null, args);
  26747. }
  26748. };
  26749. StatementInterpreter.prototype.visitReturnStmt = function (stmt, ctx) {
  26750. return new ReturnValue(stmt.value.visitExpression(this, ctx));
  26751. };
  26752. StatementInterpreter.prototype.visitDeclareClassStmt = function (stmt, ctx) {
  26753. var clazz = createDynamicClass(stmt, ctx, this);
  26754. ctx.vars.set(stmt.name, clazz);
  26755. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  26756. ctx.exports.push(stmt.name);
  26757. }
  26758. return null;
  26759. };
  26760. StatementInterpreter.prototype.visitExpressionStmt = function (stmt, ctx) {
  26761. return stmt.expr.visitExpression(this, ctx);
  26762. };
  26763. StatementInterpreter.prototype.visitIfStmt = function (stmt, ctx) {
  26764. var condition = stmt.condition.visitExpression(this, ctx);
  26765. if (condition) {
  26766. return this.visitAllStatements(stmt.trueCase, ctx);
  26767. }
  26768. else if (stmt.falseCase != null) {
  26769. return this.visitAllStatements(stmt.falseCase, ctx);
  26770. }
  26771. return null;
  26772. };
  26773. StatementInterpreter.prototype.visitTryCatchStmt = function (stmt, ctx) {
  26774. try {
  26775. return this.visitAllStatements(stmt.bodyStmts, ctx);
  26776. }
  26777. catch (e) {
  26778. var childCtx = ctx.createChildWihtLocalVars();
  26779. childCtx.vars.set(CATCH_ERROR_VAR$2, e);
  26780. childCtx.vars.set(CATCH_STACK_VAR$2, e.stack);
  26781. return this.visitAllStatements(stmt.catchStmts, childCtx);
  26782. }
  26783. };
  26784. StatementInterpreter.prototype.visitThrowStmt = function (stmt, ctx) {
  26785. throw stmt.error.visitExpression(this, ctx);
  26786. };
  26787. StatementInterpreter.prototype.visitCommentStmt = function (stmt, context) { return null; };
  26788. StatementInterpreter.prototype.visitJSDocCommentStmt = function (stmt, context) { return null; };
  26789. StatementInterpreter.prototype.visitInstantiateExpr = function (ast, ctx) {
  26790. var args = this.visitAllExpressions(ast.args, ctx);
  26791. var clazz = ast.classExpr.visitExpression(this, ctx);
  26792. return new (clazz.bind.apply(clazz, __spread([void 0], args)))();
  26793. };
  26794. StatementInterpreter.prototype.visitLiteralExpr = function (ast, ctx) { return ast.value; };
  26795. StatementInterpreter.prototype.visitExternalExpr = function (ast, ctx) {
  26796. return this.reflector.resolveExternalReference(ast.value);
  26797. };
  26798. StatementInterpreter.prototype.visitConditionalExpr = function (ast, ctx) {
  26799. if (ast.condition.visitExpression(this, ctx)) {
  26800. return ast.trueCase.visitExpression(this, ctx);
  26801. }
  26802. else if (ast.falseCase != null) {
  26803. return ast.falseCase.visitExpression(this, ctx);
  26804. }
  26805. return null;
  26806. };
  26807. StatementInterpreter.prototype.visitNotExpr = function (ast, ctx) {
  26808. return !ast.condition.visitExpression(this, ctx);
  26809. };
  26810. StatementInterpreter.prototype.visitAssertNotNullExpr = function (ast, ctx) {
  26811. return ast.condition.visitExpression(this, ctx);
  26812. };
  26813. StatementInterpreter.prototype.visitCastExpr = function (ast, ctx) {
  26814. return ast.value.visitExpression(this, ctx);
  26815. };
  26816. StatementInterpreter.prototype.visitFunctionExpr = function (ast, ctx) {
  26817. var paramNames = ast.params.map(function (param) { return param.name; });
  26818. return _declareFn(paramNames, ast.statements, ctx, this);
  26819. };
  26820. StatementInterpreter.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
  26821. var paramNames = stmt.params.map(function (param) { return param.name; });
  26822. ctx.vars.set(stmt.name, _declareFn(paramNames, stmt.statements, ctx, this));
  26823. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  26824. ctx.exports.push(stmt.name);
  26825. }
  26826. return null;
  26827. };
  26828. StatementInterpreter.prototype.visitBinaryOperatorExpr = function (ast, ctx) {
  26829. var _this = this;
  26830. var lhs = function () { return ast.lhs.visitExpression(_this, ctx); };
  26831. var rhs = function () { return ast.rhs.visitExpression(_this, ctx); };
  26832. switch (ast.operator) {
  26833. case exports.BinaryOperator.Equals:
  26834. return lhs() == rhs();
  26835. case exports.BinaryOperator.Identical:
  26836. return lhs() === rhs();
  26837. case exports.BinaryOperator.NotEquals:
  26838. return lhs() != rhs();
  26839. case exports.BinaryOperator.NotIdentical:
  26840. return lhs() !== rhs();
  26841. case exports.BinaryOperator.And:
  26842. return lhs() && rhs();
  26843. case exports.BinaryOperator.Or:
  26844. return lhs() || rhs();
  26845. case exports.BinaryOperator.Plus:
  26846. return lhs() + rhs();
  26847. case exports.BinaryOperator.Minus:
  26848. return lhs() - rhs();
  26849. case exports.BinaryOperator.Divide:
  26850. return lhs() / rhs();
  26851. case exports.BinaryOperator.Multiply:
  26852. return lhs() * rhs();
  26853. case exports.BinaryOperator.Modulo:
  26854. return lhs() % rhs();
  26855. case exports.BinaryOperator.Lower:
  26856. return lhs() < rhs();
  26857. case exports.BinaryOperator.LowerEquals:
  26858. return lhs() <= rhs();
  26859. case exports.BinaryOperator.Bigger:
  26860. return lhs() > rhs();
  26861. case exports.BinaryOperator.BiggerEquals:
  26862. return lhs() >= rhs();
  26863. default:
  26864. throw new Error("Unknown operator " + ast.operator);
  26865. }
  26866. };
  26867. StatementInterpreter.prototype.visitReadPropExpr = function (ast, ctx) {
  26868. var result;
  26869. var receiver = ast.receiver.visitExpression(this, ctx);
  26870. result = receiver[ast.name];
  26871. return result;
  26872. };
  26873. StatementInterpreter.prototype.visitReadKeyExpr = function (ast, ctx) {
  26874. var receiver = ast.receiver.visitExpression(this, ctx);
  26875. var prop = ast.index.visitExpression(this, ctx);
  26876. return receiver[prop];
  26877. };
  26878. StatementInterpreter.prototype.visitLiteralArrayExpr = function (ast, ctx) {
  26879. return this.visitAllExpressions(ast.entries, ctx);
  26880. };
  26881. StatementInterpreter.prototype.visitLiteralMapExpr = function (ast, ctx) {
  26882. var _this = this;
  26883. var result = {};
  26884. ast.entries.forEach(function (entry) { return result[entry.key] = entry.value.visitExpression(_this, ctx); });
  26885. return result;
  26886. };
  26887. StatementInterpreter.prototype.visitCommaExpr = function (ast, context) {
  26888. var values = this.visitAllExpressions(ast.parts, context);
  26889. return values[values.length - 1];
  26890. };
  26891. StatementInterpreter.prototype.visitAllExpressions = function (expressions, ctx) {
  26892. var _this = this;
  26893. return expressions.map(function (expr) { return expr.visitExpression(_this, ctx); });
  26894. };
  26895. StatementInterpreter.prototype.visitAllStatements = function (statements, ctx) {
  26896. for (var i = 0; i < statements.length; i++) {
  26897. var stmt = statements[i];
  26898. var val = stmt.visitStatement(this, ctx);
  26899. if (val instanceof ReturnValue) {
  26900. return val;
  26901. }
  26902. }
  26903. return null;
  26904. };
  26905. return StatementInterpreter;
  26906. }());
  26907. function _declareFn(varNames, statements, ctx, visitor) {
  26908. return function () {
  26909. var args = [];
  26910. for (var _i = 0; _i < arguments.length; _i++) {
  26911. args[_i] = arguments[_i];
  26912. }
  26913. return _executeFunctionStatements(varNames, args, statements, ctx, visitor);
  26914. };
  26915. }
  26916. var CATCH_ERROR_VAR$2 = 'error';
  26917. var CATCH_STACK_VAR$2 = 'stack';
  26918. /**
  26919. * @license
  26920. * Copyright Google Inc. All Rights Reserved.
  26921. *
  26922. * Use of this source code is governed by an MIT-style license that can be
  26923. * found in the LICENSE file at https://angular.io/license
  26924. */
  26925. /**
  26926. * An internal module of the Angular compiler that begins with component types,
  26927. * extracts templates, and eventually produces a compiled version of the component
  26928. * ready for linking into an application.
  26929. *
  26930. * @security When compiling templates at runtime, you must ensure that the entire template comes
  26931. * from a trusted source. Attacker-controlled data introduced by a template could expose your
  26932. * application to XSS risks. For more detail, see the [Security Guide](http://g.co/ng/security).
  26933. */
  26934. var JitCompiler = /** @class */ (function () {
  26935. function JitCompiler(_metadataResolver, _templateParser, _styleCompiler, _viewCompiler, _ngModuleCompiler, _summaryResolver, _reflector, _jitEvaluator, _compilerConfig, _console, getExtraNgModuleProviders) {
  26936. this._metadataResolver = _metadataResolver;
  26937. this._templateParser = _templateParser;
  26938. this._styleCompiler = _styleCompiler;
  26939. this._viewCompiler = _viewCompiler;
  26940. this._ngModuleCompiler = _ngModuleCompiler;
  26941. this._summaryResolver = _summaryResolver;
  26942. this._reflector = _reflector;
  26943. this._jitEvaluator = _jitEvaluator;
  26944. this._compilerConfig = _compilerConfig;
  26945. this._console = _console;
  26946. this.getExtraNgModuleProviders = getExtraNgModuleProviders;
  26947. this._compiledTemplateCache = new Map();
  26948. this._compiledHostTemplateCache = new Map();
  26949. this._compiledDirectiveWrapperCache = new Map();
  26950. this._compiledNgModuleCache = new Map();
  26951. this._sharedStylesheetCount = 0;
  26952. this._addedAotSummaries = new Set();
  26953. }
  26954. JitCompiler.prototype.compileModuleSync = function (moduleType) {
  26955. return SyncAsync.assertSync(this._compileModuleAndComponents(moduleType, true));
  26956. };
  26957. JitCompiler.prototype.compileModuleAsync = function (moduleType) {
  26958. return Promise.resolve(this._compileModuleAndComponents(moduleType, false));
  26959. };
  26960. JitCompiler.prototype.compileModuleAndAllComponentsSync = function (moduleType) {
  26961. return SyncAsync.assertSync(this._compileModuleAndAllComponents(moduleType, true));
  26962. };
  26963. JitCompiler.prototype.compileModuleAndAllComponentsAsync = function (moduleType) {
  26964. return Promise.resolve(this._compileModuleAndAllComponents(moduleType, false));
  26965. };
  26966. JitCompiler.prototype.getComponentFactory = function (component) {
  26967. var summary = this._metadataResolver.getDirectiveSummary(component);
  26968. return summary.componentFactory;
  26969. };
  26970. JitCompiler.prototype.loadAotSummaries = function (summaries) {
  26971. this.clearCache();
  26972. this._addAotSummaries(summaries);
  26973. };
  26974. JitCompiler.prototype._addAotSummaries = function (fn) {
  26975. if (this._addedAotSummaries.has(fn)) {
  26976. return;
  26977. }
  26978. this._addedAotSummaries.add(fn);
  26979. var summaries = fn();
  26980. for (var i = 0; i < summaries.length; i++) {
  26981. var entry = summaries[i];
  26982. if (typeof entry === 'function') {
  26983. this._addAotSummaries(entry);
  26984. }
  26985. else {
  26986. var summary = entry;
  26987. this._summaryResolver.addSummary({ symbol: summary.type.reference, metadata: null, type: summary });
  26988. }
  26989. }
  26990. };
  26991. JitCompiler.prototype.hasAotSummary = function (ref) { return !!this._summaryResolver.resolveSummary(ref); };
  26992. JitCompiler.prototype._filterJitIdentifiers = function (ids) {
  26993. var _this = this;
  26994. return ids.map(function (mod) { return mod.reference; }).filter(function (ref) { return !_this.hasAotSummary(ref); });
  26995. };
  26996. JitCompiler.prototype._compileModuleAndComponents = function (moduleType, isSync) {
  26997. var _this = this;
  26998. return SyncAsync.then(this._loadModules(moduleType, isSync), function () {
  26999. _this._compileComponents(moduleType, null);
  27000. return _this._compileModule(moduleType);
  27001. });
  27002. };
  27003. JitCompiler.prototype._compileModuleAndAllComponents = function (moduleType, isSync) {
  27004. var _this = this;
  27005. return SyncAsync.then(this._loadModules(moduleType, isSync), function () {
  27006. var componentFactories = [];
  27007. _this._compileComponents(moduleType, componentFactories);
  27008. return {
  27009. ngModuleFactory: _this._compileModule(moduleType),
  27010. componentFactories: componentFactories
  27011. };
  27012. });
  27013. };
  27014. JitCompiler.prototype._loadModules = function (mainModule, isSync) {
  27015. var _this = this;
  27016. var loading = [];
  27017. var mainNgModule = this._metadataResolver.getNgModuleMetadata(mainModule);
  27018. // Note: for runtime compilation, we want to transitively compile all modules,
  27019. // so we also need to load the declared directives / pipes for all nested modules.
  27020. this._filterJitIdentifiers(mainNgModule.transitiveModule.modules).forEach(function (nestedNgModule) {
  27021. // getNgModuleMetadata only returns null if the value passed in is not an NgModule
  27022. var moduleMeta = _this._metadataResolver.getNgModuleMetadata(nestedNgModule);
  27023. _this._filterJitIdentifiers(moduleMeta.declaredDirectives).forEach(function (ref) {
  27024. var promise = _this._metadataResolver.loadDirectiveMetadata(moduleMeta.type.reference, ref, isSync);
  27025. if (promise) {
  27026. loading.push(promise);
  27027. }
  27028. });
  27029. _this._filterJitIdentifiers(moduleMeta.declaredPipes)
  27030. .forEach(function (ref) { return _this._metadataResolver.getOrLoadPipeMetadata(ref); });
  27031. });
  27032. return SyncAsync.all(loading);
  27033. };
  27034. JitCompiler.prototype._compileModule = function (moduleType) {
  27035. var ngModuleFactory = this._compiledNgModuleCache.get(moduleType);
  27036. if (!ngModuleFactory) {
  27037. var moduleMeta = this._metadataResolver.getNgModuleMetadata(moduleType);
  27038. // Always provide a bound Compiler
  27039. var extraProviders = this.getExtraNgModuleProviders(moduleMeta.type.reference);
  27040. var outputCtx = createOutputContext();
  27041. var compileResult = this._ngModuleCompiler.compile(outputCtx, moduleMeta, extraProviders);
  27042. ngModuleFactory = this._interpretOrJit(ngModuleJitUrl(moduleMeta), outputCtx.statements)[compileResult.ngModuleFactoryVar];
  27043. this._compiledNgModuleCache.set(moduleMeta.type.reference, ngModuleFactory);
  27044. }
  27045. return ngModuleFactory;
  27046. };
  27047. /**
  27048. * @internal
  27049. */
  27050. JitCompiler.prototype._compileComponents = function (mainModule, allComponentFactories) {
  27051. var _this = this;
  27052. var ngModule = this._metadataResolver.getNgModuleMetadata(mainModule);
  27053. var moduleByJitDirective = new Map();
  27054. var templates = new Set();
  27055. var transJitModules = this._filterJitIdentifiers(ngModule.transitiveModule.modules);
  27056. transJitModules.forEach(function (localMod) {
  27057. var localModuleMeta = _this._metadataResolver.getNgModuleMetadata(localMod);
  27058. _this._filterJitIdentifiers(localModuleMeta.declaredDirectives).forEach(function (dirRef) {
  27059. moduleByJitDirective.set(dirRef, localModuleMeta);
  27060. var dirMeta = _this._metadataResolver.getDirectiveMetadata(dirRef);
  27061. if (dirMeta.isComponent) {
  27062. templates.add(_this._createCompiledTemplate(dirMeta, localModuleMeta));
  27063. if (allComponentFactories) {
  27064. var template = _this._createCompiledHostTemplate(dirMeta.type.reference, localModuleMeta);
  27065. templates.add(template);
  27066. allComponentFactories.push(dirMeta.componentFactory);
  27067. }
  27068. }
  27069. });
  27070. });
  27071. transJitModules.forEach(function (localMod) {
  27072. var localModuleMeta = _this._metadataResolver.getNgModuleMetadata(localMod);
  27073. _this._filterJitIdentifiers(localModuleMeta.declaredDirectives).forEach(function (dirRef) {
  27074. var dirMeta = _this._metadataResolver.getDirectiveMetadata(dirRef);
  27075. if (dirMeta.isComponent) {
  27076. dirMeta.entryComponents.forEach(function (entryComponentType) {
  27077. var moduleMeta = moduleByJitDirective.get(entryComponentType.componentType);
  27078. templates.add(_this._createCompiledHostTemplate(entryComponentType.componentType, moduleMeta));
  27079. });
  27080. }
  27081. });
  27082. localModuleMeta.entryComponents.forEach(function (entryComponentType) {
  27083. if (!_this.hasAotSummary(entryComponentType.componentType)) {
  27084. var moduleMeta = moduleByJitDirective.get(entryComponentType.componentType);
  27085. templates.add(_this._createCompiledHostTemplate(entryComponentType.componentType, moduleMeta));
  27086. }
  27087. });
  27088. });
  27089. templates.forEach(function (template) { return _this._compileTemplate(template); });
  27090. };
  27091. JitCompiler.prototype.clearCacheFor = function (type) {
  27092. this._compiledNgModuleCache.delete(type);
  27093. this._metadataResolver.clearCacheFor(type);
  27094. this._compiledHostTemplateCache.delete(type);
  27095. var compiledTemplate = this._compiledTemplateCache.get(type);
  27096. if (compiledTemplate) {
  27097. this._compiledTemplateCache.delete(type);
  27098. }
  27099. };
  27100. JitCompiler.prototype.clearCache = function () {
  27101. // Note: don't clear the _addedAotSummaries, as they don't change!
  27102. this._metadataResolver.clearCache();
  27103. this._compiledTemplateCache.clear();
  27104. this._compiledHostTemplateCache.clear();
  27105. this._compiledNgModuleCache.clear();
  27106. };
  27107. JitCompiler.prototype._createCompiledHostTemplate = function (compType, ngModule) {
  27108. if (!ngModule) {
  27109. throw new Error("Component " + stringify(compType) + " is not part of any NgModule or the module has not been imported into your module.");
  27110. }
  27111. var compiledTemplate = this._compiledHostTemplateCache.get(compType);
  27112. if (!compiledTemplate) {
  27113. var compMeta = this._metadataResolver.getDirectiveMetadata(compType);
  27114. assertComponent(compMeta);
  27115. var hostMeta = this._metadataResolver.getHostComponentMetadata(compMeta, compMeta.componentFactory.viewDefFactory);
  27116. compiledTemplate =
  27117. new CompiledTemplate(true, compMeta.type, hostMeta, ngModule, [compMeta.type]);
  27118. this._compiledHostTemplateCache.set(compType, compiledTemplate);
  27119. }
  27120. return compiledTemplate;
  27121. };
  27122. JitCompiler.prototype._createCompiledTemplate = function (compMeta, ngModule) {
  27123. var compiledTemplate = this._compiledTemplateCache.get(compMeta.type.reference);
  27124. if (!compiledTemplate) {
  27125. assertComponent(compMeta);
  27126. compiledTemplate = new CompiledTemplate(false, compMeta.type, compMeta, ngModule, ngModule.transitiveModule.directives);
  27127. this._compiledTemplateCache.set(compMeta.type.reference, compiledTemplate);
  27128. }
  27129. return compiledTemplate;
  27130. };
  27131. JitCompiler.prototype._compileTemplate = function (template) {
  27132. var _this = this;
  27133. if (template.isCompiled) {
  27134. return;
  27135. }
  27136. var compMeta = template.compMeta;
  27137. var externalStylesheetsByModuleUrl = new Map();
  27138. var outputContext = createOutputContext();
  27139. var componentStylesheet = this._styleCompiler.compileComponent(outputContext, compMeta);
  27140. compMeta.template.externalStylesheets.forEach(function (stylesheetMeta) {
  27141. var compiledStylesheet = _this._styleCompiler.compileStyles(createOutputContext(), compMeta, stylesheetMeta);
  27142. externalStylesheetsByModuleUrl.set(stylesheetMeta.moduleUrl, compiledStylesheet);
  27143. });
  27144. this._resolveStylesCompileResult(componentStylesheet, externalStylesheetsByModuleUrl);
  27145. var pipes = template.ngModule.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
  27146. var _a = this._parseTemplate(compMeta, template.ngModule, template.directives), parsedTemplate = _a.template, usedPipes = _a.pipes;
  27147. var compileResult = this._viewCompiler.compileComponent(outputContext, compMeta, parsedTemplate, variable(componentStylesheet.stylesVar), usedPipes);
  27148. var evalResult = this._interpretOrJit(templateJitUrl(template.ngModule.type, template.compMeta), outputContext.statements);
  27149. var viewClass = evalResult[compileResult.viewClassVar];
  27150. var rendererType = evalResult[compileResult.rendererTypeVar];
  27151. template.compiled(viewClass, rendererType);
  27152. };
  27153. JitCompiler.prototype._parseTemplate = function (compMeta, ngModule, directiveIdentifiers) {
  27154. var _this = this;
  27155. // Note: ! is ok here as components always have a template.
  27156. var preserveWhitespaces = compMeta.template.preserveWhitespaces;
  27157. var directives = directiveIdentifiers.map(function (dir) { return _this._metadataResolver.getDirectiveSummary(dir.reference); });
  27158. var pipes = ngModule.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
  27159. return this._templateParser.parse(compMeta, compMeta.template.htmlAst, directives, pipes, ngModule.schemas, templateSourceUrl(ngModule.type, compMeta, compMeta.template), preserveWhitespaces);
  27160. };
  27161. JitCompiler.prototype._resolveStylesCompileResult = function (result, externalStylesheetsByModuleUrl) {
  27162. var _this = this;
  27163. result.dependencies.forEach(function (dep, i) {
  27164. var nestedCompileResult = externalStylesheetsByModuleUrl.get(dep.moduleUrl);
  27165. var nestedStylesArr = _this._resolveAndEvalStylesCompileResult(nestedCompileResult, externalStylesheetsByModuleUrl);
  27166. dep.setValue(nestedStylesArr);
  27167. });
  27168. };
  27169. JitCompiler.prototype._resolveAndEvalStylesCompileResult = function (result, externalStylesheetsByModuleUrl) {
  27170. this._resolveStylesCompileResult(result, externalStylesheetsByModuleUrl);
  27171. return this._interpretOrJit(sharedStylesheetJitUrl(result.meta, this._sharedStylesheetCount++), result.outputCtx.statements)[result.stylesVar];
  27172. };
  27173. JitCompiler.prototype._interpretOrJit = function (sourceUrl, statements) {
  27174. if (!this._compilerConfig.useJit) {
  27175. return interpretStatements(statements, this._reflector);
  27176. }
  27177. else {
  27178. return this._jitEvaluator.evaluateStatements(sourceUrl, statements, this._reflector, this._compilerConfig.jitDevMode);
  27179. }
  27180. };
  27181. return JitCompiler;
  27182. }());
  27183. var CompiledTemplate = /** @class */ (function () {
  27184. function CompiledTemplate(isHost, compType, compMeta, ngModule, directives) {
  27185. this.isHost = isHost;
  27186. this.compType = compType;
  27187. this.compMeta = compMeta;
  27188. this.ngModule = ngModule;
  27189. this.directives = directives;
  27190. this._viewClass = null;
  27191. this.isCompiled = false;
  27192. }
  27193. CompiledTemplate.prototype.compiled = function (viewClass, rendererType) {
  27194. this._viewClass = viewClass;
  27195. this.compMeta.componentViewType.setDelegate(viewClass);
  27196. for (var prop in rendererType) {
  27197. this.compMeta.rendererType[prop] = rendererType[prop];
  27198. }
  27199. this.isCompiled = true;
  27200. };
  27201. return CompiledTemplate;
  27202. }());
  27203. function assertComponent(meta) {
  27204. if (!meta.isComponent) {
  27205. throw new Error("Could not compile '" + identifierName(meta.type) + "' because it is not a component.");
  27206. }
  27207. }
  27208. function createOutputContext() {
  27209. var importExpr$1 = function (symbol) {
  27210. return importExpr({ name: identifierName(symbol), moduleName: null, runtime: symbol });
  27211. };
  27212. return { statements: [], genFilePath: '', importExpr: importExpr$1, constantPool: new ConstantPool() };
  27213. }
  27214. /**
  27215. * @license
  27216. * Copyright Google Inc. All Rights Reserved.
  27217. *
  27218. * Use of this source code is governed by an MIT-style license that can be
  27219. * found in the LICENSE file at https://angular.io/license
  27220. */
  27221. /**
  27222. * Provides access to reflection data about symbols that the compiler needs.
  27223. */
  27224. var CompileReflector = /** @class */ (function () {
  27225. function CompileReflector() {
  27226. }
  27227. return CompileReflector;
  27228. }());
  27229. /**
  27230. * @license
  27231. * Copyright Google Inc. All Rights Reserved.
  27232. *
  27233. * Use of this source code is governed by an MIT-style license that can be
  27234. * found in the LICENSE file at https://angular.io/license
  27235. */
  27236. /**
  27237. * Create a {@link UrlResolver} with no package prefix.
  27238. */
  27239. function createUrlResolverWithoutPackagePrefix() {
  27240. return new UrlResolver();
  27241. }
  27242. function createOfflineCompileUrlResolver() {
  27243. return new UrlResolver('.');
  27244. }
  27245. var UrlResolver = /** @class */ (function () {
  27246. function UrlResolverImpl(_packagePrefix) {
  27247. if (_packagePrefix === void 0) { _packagePrefix = null; }
  27248. this._packagePrefix = _packagePrefix;
  27249. }
  27250. /**
  27251. * Resolves the `url` given the `baseUrl`:
  27252. * - when the `url` is null, the `baseUrl` is returned,
  27253. * - if `url` is relative ('path/to/here', './path/to/here'), the resolved url is a combination of
  27254. * `baseUrl` and `url`,
  27255. * - if `url` is absolute (it has a scheme: 'http://', 'https://' or start with '/'), the `url` is
  27256. * returned as is (ignoring the `baseUrl`)
  27257. */
  27258. UrlResolverImpl.prototype.resolve = function (baseUrl, url) {
  27259. var resolvedUrl = url;
  27260. if (baseUrl != null && baseUrl.length > 0) {
  27261. resolvedUrl = _resolveUrl(baseUrl, resolvedUrl);
  27262. }
  27263. var resolvedParts = _split(resolvedUrl);
  27264. var prefix = this._packagePrefix;
  27265. if (prefix != null && resolvedParts != null &&
  27266. resolvedParts[_ComponentIndex.Scheme] == 'package') {
  27267. var path = resolvedParts[_ComponentIndex.Path];
  27268. prefix = prefix.replace(/\/+$/, '');
  27269. path = path.replace(/^\/+/, '');
  27270. return prefix + "/" + path;
  27271. }
  27272. return resolvedUrl;
  27273. };
  27274. return UrlResolverImpl;
  27275. }());
  27276. /**
  27277. * Extract the scheme of a URL.
  27278. */
  27279. function getUrlScheme(url) {
  27280. var match = _split(url);
  27281. return (match && match[_ComponentIndex.Scheme]) || '';
  27282. }
  27283. // The code below is adapted from Traceur:
  27284. // https://github.com/google/traceur-compiler/blob/9511c1dafa972bf0de1202a8a863bad02f0f95a8/src/runtime/url.js
  27285. /**
  27286. * Builds a URI string from already-encoded parts.
  27287. *
  27288. * No encoding is performed. Any component may be omitted as either null or
  27289. * undefined.
  27290. *
  27291. * @param opt_scheme The scheme such as 'http'.
  27292. * @param opt_userInfo The user name before the '@'.
  27293. * @param opt_domain The domain such as 'www.google.com', already
  27294. * URI-encoded.
  27295. * @param opt_port The port number.
  27296. * @param opt_path The path, already URI-encoded. If it is not
  27297. * empty, it must begin with a slash.
  27298. * @param opt_queryData The URI-encoded query data.
  27299. * @param opt_fragment The URI-encoded fragment identifier.
  27300. * @return The fully combined URI.
  27301. */
  27302. function _buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
  27303. var out = [];
  27304. if (opt_scheme != null) {
  27305. out.push(opt_scheme + ':');
  27306. }
  27307. if (opt_domain != null) {
  27308. out.push('//');
  27309. if (opt_userInfo != null) {
  27310. out.push(opt_userInfo + '@');
  27311. }
  27312. out.push(opt_domain);
  27313. if (opt_port != null) {
  27314. out.push(':' + opt_port);
  27315. }
  27316. }
  27317. if (opt_path != null) {
  27318. out.push(opt_path);
  27319. }
  27320. if (opt_queryData != null) {
  27321. out.push('?' + opt_queryData);
  27322. }
  27323. if (opt_fragment != null) {
  27324. out.push('#' + opt_fragment);
  27325. }
  27326. return out.join('');
  27327. }
  27328. /**
  27329. * A regular expression for breaking a URI into its component parts.
  27330. *
  27331. * {@link http://www.gbiv.com/protocols/uri/rfc/rfc3986.html#RFC2234} says
  27332. * As the "first-match-wins" algorithm is identical to the "greedy"
  27333. * disambiguation method used by POSIX regular expressions, it is natural and
  27334. * commonplace to use a regular expression for parsing the potential five
  27335. * components of a URI reference.
  27336. *
  27337. * The following line is the regular expression for breaking-down a
  27338. * well-formed URI reference into its components.
  27339. *
  27340. * <pre>
  27341. * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
  27342. * 12 3 4 5 6 7 8 9
  27343. * </pre>
  27344. *
  27345. * The numbers in the second line above are only to assist readability; they
  27346. * indicate the reference points for each subexpression (i.e., each paired
  27347. * parenthesis). We refer to the value matched for subexpression <n> as $<n>.
  27348. * For example, matching the above expression to
  27349. * <pre>
  27350. * http://www.ics.uci.edu/pub/ietf/uri/#Related
  27351. * </pre>
  27352. * results in the following subexpression matches:
  27353. * <pre>
  27354. * $1 = http:
  27355. * $2 = http
  27356. * $3 = //www.ics.uci.edu
  27357. * $4 = www.ics.uci.edu
  27358. * $5 = /pub/ietf/uri/
  27359. * $6 = <undefined>
  27360. * $7 = <undefined>
  27361. * $8 = #Related
  27362. * $9 = Related
  27363. * </pre>
  27364. * where <undefined> indicates that the component is not present, as is the
  27365. * case for the query component in the above example. Therefore, we can
  27366. * determine the value of the five components as
  27367. * <pre>
  27368. * scheme = $2
  27369. * authority = $4
  27370. * path = $5
  27371. * query = $7
  27372. * fragment = $9
  27373. * </pre>
  27374. *
  27375. * The regular expression has been modified slightly to expose the
  27376. * userInfo, domain, and port separately from the authority.
  27377. * The modified version yields
  27378. * <pre>
  27379. * $1 = http scheme
  27380. * $2 = <undefined> userInfo -\
  27381. * $3 = www.ics.uci.edu domain | authority
  27382. * $4 = <undefined> port -/
  27383. * $5 = /pub/ietf/uri/ path
  27384. * $6 = <undefined> query without ?
  27385. * $7 = Related fragment without #
  27386. * </pre>
  27387. * @internal
  27388. */
  27389. var _splitRe = new RegExp('^' +
  27390. '(?:' +
  27391. '([^:/?#.]+)' + // scheme - ignore special characters
  27392. // used by other URL parts such as :,
  27393. // ?, /, #, and .
  27394. ':)?' +
  27395. '(?://' +
  27396. '(?:([^/?#]*)@)?' + // userInfo
  27397. '([\\w\\d\\-\\u0100-\\uffff.%]*)' + // domain - restrict to letters,
  27398. // digits, dashes, dots, percent
  27399. // escapes, and unicode characters.
  27400. '(?::([0-9]+))?' + // port
  27401. ')?' +
  27402. '([^?#]+)?' + // path
  27403. '(?:\\?([^#]*))?' + // query
  27404. '(?:#(.*))?' + // fragment
  27405. '$');
  27406. /**
  27407. * The index of each URI component in the return value of goog.uri.utils.split.
  27408. * @enum {number}
  27409. */
  27410. var _ComponentIndex;
  27411. (function (_ComponentIndex) {
  27412. _ComponentIndex[_ComponentIndex["Scheme"] = 1] = "Scheme";
  27413. _ComponentIndex[_ComponentIndex["UserInfo"] = 2] = "UserInfo";
  27414. _ComponentIndex[_ComponentIndex["Domain"] = 3] = "Domain";
  27415. _ComponentIndex[_ComponentIndex["Port"] = 4] = "Port";
  27416. _ComponentIndex[_ComponentIndex["Path"] = 5] = "Path";
  27417. _ComponentIndex[_ComponentIndex["QueryData"] = 6] = "QueryData";
  27418. _ComponentIndex[_ComponentIndex["Fragment"] = 7] = "Fragment";
  27419. })(_ComponentIndex || (_ComponentIndex = {}));
  27420. /**
  27421. * Splits a URI into its component parts.
  27422. *
  27423. * Each component can be accessed via the component indices; for example:
  27424. * <pre>
  27425. * goog.uri.utils.split(someStr)[goog.uri.utils.CompontentIndex.QUERY_DATA];
  27426. * </pre>
  27427. *
  27428. * @param uri The URI string to examine.
  27429. * @return Each component still URI-encoded.
  27430. * Each component that is present will contain the encoded value, whereas
  27431. * components that are not present will be undefined or empty, depending
  27432. * on the browser's regular expression implementation. Never null, since
  27433. * arbitrary strings may still look like path names.
  27434. */
  27435. function _split(uri) {
  27436. return uri.match(_splitRe);
  27437. }
  27438. /**
  27439. * Removes dot segments in given path component, as described in
  27440. * RFC 3986, section 5.2.4.
  27441. *
  27442. * @param path A non-empty path component.
  27443. * @return Path component with removed dot segments.
  27444. */
  27445. function _removeDotSegments(path) {
  27446. if (path == '/')
  27447. return '/';
  27448. var leadingSlash = path[0] == '/' ? '/' : '';
  27449. var trailingSlash = path[path.length - 1] === '/' ? '/' : '';
  27450. var segments = path.split('/');
  27451. var out = [];
  27452. var up = 0;
  27453. for (var pos = 0; pos < segments.length; pos++) {
  27454. var segment = segments[pos];
  27455. switch (segment) {
  27456. case '':
  27457. case '.':
  27458. break;
  27459. case '..':
  27460. if (out.length > 0) {
  27461. out.pop();
  27462. }
  27463. else {
  27464. up++;
  27465. }
  27466. break;
  27467. default:
  27468. out.push(segment);
  27469. }
  27470. }
  27471. if (leadingSlash == '') {
  27472. while (up-- > 0) {
  27473. out.unshift('..');
  27474. }
  27475. if (out.length === 0)
  27476. out.push('.');
  27477. }
  27478. return leadingSlash + out.join('/') + trailingSlash;
  27479. }
  27480. /**
  27481. * Takes an array of the parts from split and canonicalizes the path part
  27482. * and then joins all the parts.
  27483. */
  27484. function _joinAndCanonicalizePath(parts) {
  27485. var path = parts[_ComponentIndex.Path];
  27486. path = path == null ? '' : _removeDotSegments(path);
  27487. parts[_ComponentIndex.Path] = path;
  27488. return _buildFromEncodedParts(parts[_ComponentIndex.Scheme], parts[_ComponentIndex.UserInfo], parts[_ComponentIndex.Domain], parts[_ComponentIndex.Port], path, parts[_ComponentIndex.QueryData], parts[_ComponentIndex.Fragment]);
  27489. }
  27490. /**
  27491. * Resolves a URL.
  27492. * @param base The URL acting as the base URL.
  27493. * @param to The URL to resolve.
  27494. */
  27495. function _resolveUrl(base, url) {
  27496. var parts = _split(encodeURI(url));
  27497. var baseParts = _split(base);
  27498. if (parts[_ComponentIndex.Scheme] != null) {
  27499. return _joinAndCanonicalizePath(parts);
  27500. }
  27501. else {
  27502. parts[_ComponentIndex.Scheme] = baseParts[_ComponentIndex.Scheme];
  27503. }
  27504. for (var i = _ComponentIndex.Scheme; i <= _ComponentIndex.Port; i++) {
  27505. if (parts[i] == null) {
  27506. parts[i] = baseParts[i];
  27507. }
  27508. }
  27509. if (parts[_ComponentIndex.Path][0] == '/') {
  27510. return _joinAndCanonicalizePath(parts);
  27511. }
  27512. var path = baseParts[_ComponentIndex.Path];
  27513. if (path == null)
  27514. path = '/';
  27515. var index = path.lastIndexOf('/');
  27516. path = path.substring(0, index + 1) + parts[_ComponentIndex.Path];
  27517. parts[_ComponentIndex.Path] = path;
  27518. return _joinAndCanonicalizePath(parts);
  27519. }
  27520. /**
  27521. * @license
  27522. * Copyright Google Inc. All Rights Reserved.
  27523. *
  27524. * Use of this source code is governed by an MIT-style license that can be
  27525. * found in the LICENSE file at https://angular.io/license
  27526. */
  27527. var Extractor = /** @class */ (function () {
  27528. function Extractor(host, staticSymbolResolver, messageBundle, metadataResolver) {
  27529. this.host = host;
  27530. this.staticSymbolResolver = staticSymbolResolver;
  27531. this.messageBundle = messageBundle;
  27532. this.metadataResolver = metadataResolver;
  27533. }
  27534. Extractor.prototype.extract = function (rootFiles) {
  27535. var _this = this;
  27536. var _a = analyzeAndValidateNgModules(rootFiles, this.host, this.staticSymbolResolver, this.metadataResolver), files = _a.files, ngModules = _a.ngModules;
  27537. return Promise
  27538. .all(ngModules.map(function (ngModule) { return _this.metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false); }))
  27539. .then(function () {
  27540. var errors = [];
  27541. files.forEach(function (file) {
  27542. var compMetas = [];
  27543. file.directives.forEach(function (directiveType) {
  27544. var dirMeta = _this.metadataResolver.getDirectiveMetadata(directiveType);
  27545. if (dirMeta && dirMeta.isComponent) {
  27546. compMetas.push(dirMeta);
  27547. }
  27548. });
  27549. compMetas.forEach(function (compMeta) {
  27550. var html = compMeta.template.template;
  27551. // Template URL points to either an HTML or TS file depending on
  27552. // whether the file is used with `templateUrl:` or `template:`,
  27553. // respectively.
  27554. var templateUrl = compMeta.template.templateUrl;
  27555. var interpolationConfig = InterpolationConfig.fromArray(compMeta.template.interpolation);
  27556. errors.push.apply(errors, __spread(_this.messageBundle.updateFromTemplate(html, templateUrl, interpolationConfig)));
  27557. });
  27558. });
  27559. if (errors.length) {
  27560. throw new Error(errors.map(function (e) { return e.toString(); }).join('\n'));
  27561. }
  27562. return _this.messageBundle;
  27563. });
  27564. };
  27565. Extractor.create = function (host, locale) {
  27566. var htmlParser = new HtmlParser();
  27567. var urlResolver = createAotUrlResolver(host);
  27568. var symbolCache = new StaticSymbolCache();
  27569. var summaryResolver = new AotSummaryResolver(host, symbolCache);
  27570. var staticSymbolResolver = new StaticSymbolResolver(host, symbolCache, summaryResolver);
  27571. var staticReflector = new StaticReflector(summaryResolver, staticSymbolResolver);
  27572. var config = new CompilerConfig({ defaultEncapsulation: ViewEncapsulation.Emulated, useJit: false });
  27573. var normalizer = new DirectiveNormalizer({ get: function (url) { return host.loadResource(url); } }, urlResolver, htmlParser, config);
  27574. var elementSchemaRegistry = new DomElementSchemaRegistry();
  27575. var resolver = new CompileMetadataResolver(config, htmlParser, new NgModuleResolver(staticReflector), new DirectiveResolver(staticReflector), new PipeResolver(staticReflector), summaryResolver, elementSchemaRegistry, normalizer, console, symbolCache, staticReflector);
  27576. // TODO(vicb): implicit tags & attributes
  27577. var messageBundle = new MessageBundle(htmlParser, [], {}, locale);
  27578. var extractor = new Extractor(host, staticSymbolResolver, messageBundle, resolver);
  27579. return { extractor: extractor, staticReflector: staticReflector };
  27580. };
  27581. return Extractor;
  27582. }());
  27583. /**
  27584. * @license
  27585. * Copyright Google Inc. All Rights Reserved.
  27586. *
  27587. * Use of this source code is governed by an MIT-style license that can be
  27588. * found in the LICENSE file at https://angular.io/license
  27589. */
  27590. /**
  27591. * @license
  27592. * Copyright Google Inc. All Rights Reserved.
  27593. *
  27594. * Use of this source code is governed by an MIT-style license that can be
  27595. * found in the LICENSE file at https://angular.io/license
  27596. */
  27597. /**
  27598. * Processes `Target`s with a given set of directives and performs a binding operation, which
  27599. * returns an object similar to TypeScript's `ts.TypeChecker` that contains knowledge about the
  27600. * target.
  27601. */
  27602. var R3TargetBinder = /** @class */ (function () {
  27603. function R3TargetBinder(directiveMatcher) {
  27604. this.directiveMatcher = directiveMatcher;
  27605. }
  27606. /**
  27607. * Perform a binding operation on the given `Target` and return a `BoundTarget` which contains
  27608. * metadata about the types referenced in the template.
  27609. */
  27610. R3TargetBinder.prototype.bind = function (target) {
  27611. if (!target.template) {
  27612. // TODO(alxhub): handle targets which contain things like HostBindings, etc.
  27613. throw new Error('Binding without a template not yet supported');
  27614. }
  27615. // First, parse the template into a `Scope` structure. This operation captures the syntactic
  27616. // scopes in the template and makes them available for later use.
  27617. var scope = Scope.apply(target.template);
  27618. // Next, perform directive matching on the template using the `DirectiveBinder`. This returns:
  27619. // - directives: Map of nodes (elements & ng-templates) to the directives on them.
  27620. // - bindings: Map of inputs, outputs, and attributes to the directive/element that claims
  27621. // them. TODO(alxhub): handle multiple directives claiming an input/output/etc.
  27622. // - references: Map of #references to their targets.
  27623. var _a = DirectiveBinder.apply(target.template, this.directiveMatcher), directives = _a.directives, bindings = _a.bindings, references = _a.references;
  27624. // Finally, run the TemplateBinder to bind references, variables, and other entities within the
  27625. // template. This extracts all the metadata that doesn't depend on directive matching.
  27626. var _b = TemplateBinder.apply(target.template, scope), expressions = _b.expressions, symbols = _b.symbols, nestingLevel = _b.nestingLevel, usedPipes = _b.usedPipes;
  27627. return new R3BoundTarget(target, directives, bindings, references, expressions, symbols, nestingLevel, usedPipes);
  27628. };
  27629. return R3TargetBinder;
  27630. }());
  27631. /**
  27632. * Represents a binding scope within a template.
  27633. *
  27634. * Any variables, references, or other named entities declared within the template will
  27635. * be captured and available by name in `namedEntities`. Additionally, child templates will
  27636. * be analyzed and have their child `Scope`s available in `childScopes`.
  27637. */
  27638. var Scope = /** @class */ (function () {
  27639. function Scope(parentScope) {
  27640. this.parentScope = parentScope;
  27641. /**
  27642. * Named members of the `Scope`, such as `Reference`s or `Variable`s.
  27643. */
  27644. this.namedEntities = new Map();
  27645. /**
  27646. * Child `Scope`s for immediately nested `Template`s.
  27647. */
  27648. this.childScopes = new Map();
  27649. }
  27650. /**
  27651. * Process a template (either as a `Template` sub-template with variables, or a plain array of
  27652. * template `Node`s) and construct its `Scope`.
  27653. */
  27654. Scope.apply = function (template) {
  27655. var scope = new Scope();
  27656. scope.ingest(template);
  27657. return scope;
  27658. };
  27659. /**
  27660. * Internal method to process the template and populate the `Scope`.
  27661. */
  27662. Scope.prototype.ingest = function (template) {
  27663. var _this = this;
  27664. if (template instanceof Template) {
  27665. // Variables on an <ng-template> are defined in the inner scope.
  27666. template.variables.forEach(function (node) { return _this.visitVariable(node); });
  27667. // Process the nodes of the template.
  27668. template.children.forEach(function (node) { return node.visit(_this); });
  27669. }
  27670. else {
  27671. // No overarching `Template` instance, so process the nodes directly.
  27672. template.forEach(function (node) { return node.visit(_this); });
  27673. }
  27674. };
  27675. Scope.prototype.visitElement = function (element) {
  27676. var _this = this;
  27677. // `Element`s in the template may have `Reference`s which are captured in the scope.
  27678. element.references.forEach(function (node) { return _this.visitReference(node); });
  27679. // Recurse into the `Element`'s children.
  27680. element.children.forEach(function (node) { return node.visit(_this); });
  27681. };
  27682. Scope.prototype.visitTemplate = function (template) {
  27683. var _this = this;
  27684. // References on a <ng-template> are defined in the outer scope, so capture them before
  27685. // processing the template's child scope.
  27686. template.references.forEach(function (node) { return _this.visitReference(node); });
  27687. // Next, create an inner scope and process the template within it.
  27688. var scope = new Scope(this);
  27689. scope.ingest(template);
  27690. this.childScopes.set(template, scope);
  27691. };
  27692. Scope.prototype.visitVariable = function (variable) {
  27693. // Declare the variable if it's not already.
  27694. this.maybeDeclare(variable);
  27695. };
  27696. Scope.prototype.visitReference = function (reference) {
  27697. // Declare the variable if it's not already.
  27698. this.maybeDeclare(reference);
  27699. };
  27700. // Unused visitors.
  27701. Scope.prototype.visitContent = function (content) { };
  27702. Scope.prototype.visitBoundAttribute = function (attr) { };
  27703. Scope.prototype.visitBoundEvent = function (event) { };
  27704. Scope.prototype.visitBoundText = function (text) { };
  27705. Scope.prototype.visitText = function (text) { };
  27706. Scope.prototype.visitTextAttribute = function (attr) { };
  27707. Scope.prototype.visitIcu = function (icu) { };
  27708. Scope.prototype.maybeDeclare = function (thing) {
  27709. // Declare something with a name, as long as that name isn't taken.
  27710. if (!this.namedEntities.has(thing.name)) {
  27711. this.namedEntities.set(thing.name, thing);
  27712. }
  27713. };
  27714. /**
  27715. * Look up a variable within this `Scope`.
  27716. *
  27717. * This can recurse into a parent `Scope` if it's available.
  27718. */
  27719. Scope.prototype.lookup = function (name) {
  27720. if (this.namedEntities.has(name)) {
  27721. // Found in the local scope.
  27722. return this.namedEntities.get(name);
  27723. }
  27724. else if (this.parentScope !== undefined) {
  27725. // Not in the local scope, but there's a parent scope so check there.
  27726. return this.parentScope.lookup(name);
  27727. }
  27728. else {
  27729. // At the top level and it wasn't found.
  27730. return null;
  27731. }
  27732. };
  27733. /**
  27734. * Get the child scope for a `Template`.
  27735. *
  27736. * This should always be defined.
  27737. */
  27738. Scope.prototype.getChildScope = function (template) {
  27739. var res = this.childScopes.get(template);
  27740. if (res === undefined) {
  27741. throw new Error("Assertion error: child scope for " + template + " not found");
  27742. }
  27743. return res;
  27744. };
  27745. return Scope;
  27746. }());
  27747. /**
  27748. * Processes a template and matches directives on nodes (elements and templates).
  27749. *
  27750. * Usually used via the static `apply()` method.
  27751. */
  27752. var DirectiveBinder = /** @class */ (function () {
  27753. function DirectiveBinder(matcher, directives, bindings, references) {
  27754. this.matcher = matcher;
  27755. this.directives = directives;
  27756. this.bindings = bindings;
  27757. this.references = references;
  27758. }
  27759. /**
  27760. * Process a template (list of `Node`s) and perform directive matching against each node.
  27761. *
  27762. * @param template the list of template `Node`s to match (recursively).
  27763. * @param selectorMatcher a `SelectorMatcher` containing the directives that are in scope for
  27764. * this template.
  27765. * @returns three maps which contain information about directives in the template: the
  27766. * `directives` map which lists directives matched on each node, the `bindings` map which
  27767. * indicates which directives claimed which bindings (inputs, outputs, etc), and the `references`
  27768. * map which resolves #references (`Reference`s) within the template to the named directive or
  27769. * template node.
  27770. */
  27771. DirectiveBinder.apply = function (template, selectorMatcher) {
  27772. var directives = new Map();
  27773. var bindings = new Map();
  27774. var references = new Map();
  27775. var matcher = new DirectiveBinder(selectorMatcher, directives, bindings, references);
  27776. matcher.ingest(template);
  27777. return { directives: directives, bindings: bindings, references: references };
  27778. };
  27779. DirectiveBinder.prototype.ingest = function (template) {
  27780. var _this = this;
  27781. template.forEach(function (node) { return node.visit(_this); });
  27782. };
  27783. DirectiveBinder.prototype.visitElement = function (element) { this.visitElementOrTemplate(element.name, element); };
  27784. DirectiveBinder.prototype.visitTemplate = function (template) { this.visitElementOrTemplate('ng-template', template); };
  27785. DirectiveBinder.prototype.visitElementOrTemplate = function (tag, node) {
  27786. var _this = this;
  27787. // First, determine the HTML shape of the node for the purpose of directive matching.
  27788. // Do this by building up a `CssSelector` for the node.
  27789. var cssSelector = new CssSelector();
  27790. cssSelector.setElement(tag);
  27791. // Add attributes to the CSS selector.
  27792. var attrs = getAttrsForDirectiveMatching(node);
  27793. Object.getOwnPropertyNames(attrs).forEach(function (name) {
  27794. var value = attrs[name];
  27795. cssSelector.addAttribute(name, value);
  27796. // Treat the 'class' attribute specially.
  27797. if (name.toLowerCase() === 'class') {
  27798. var classes = value.trim().split(/\s+/g);
  27799. classes.forEach(function (className) { return cssSelector.addClassName(className); });
  27800. }
  27801. });
  27802. // Next, use the `SelectorMatcher` to get the list of directives on the node.
  27803. var directives = [];
  27804. this.matcher.match(cssSelector, function (_, directive) { return directives.push(directive); });
  27805. if (directives.length > 0) {
  27806. this.directives.set(node, directives);
  27807. }
  27808. // Resolve any references that are created on this node.
  27809. node.references.forEach(function (ref) {
  27810. var dirTarget = null;
  27811. // If the reference expression is empty, then it matches the "primary" directive on the node
  27812. // (if there is one). Otherwise it matches the host node itself (either an element or
  27813. // <ng-template> node).
  27814. if (ref.value.trim() === '') {
  27815. // This could be a reference to a component if there is one.
  27816. dirTarget = directives.find(function (dir) { return dir.isComponent; }) || null;
  27817. }
  27818. else {
  27819. // This is a reference to a directive exported via exportAs. One should exist.
  27820. dirTarget =
  27821. directives.find(function (dir) { return dir.exportAs !== null && dir.exportAs.some(function (value) { return value === ref.value; }); }) ||
  27822. null;
  27823. // Check if a matching directive was found, and error if it wasn't.
  27824. if (dirTarget === null) {
  27825. // TODO(alxhub): Return an error value here that can be used for template validation.
  27826. throw new Error("Assertion error: failed to find directive with exportAs: " + ref.value);
  27827. }
  27828. }
  27829. if (dirTarget !== null) {
  27830. // This reference points to a directive.
  27831. _this.references.set(ref, { directive: dirTarget, node: node });
  27832. }
  27833. else {
  27834. // This reference points to the node itself.
  27835. _this.references.set(ref, node);
  27836. }
  27837. });
  27838. // Associate attributes/bindings on the node with directives or with the node itself.
  27839. var processAttribute = function (attribute) {
  27840. var dir = directives.find(function (dir) { return dir.inputs.hasOwnProperty(attribute.name); });
  27841. if (dir !== undefined) {
  27842. _this.bindings.set(attribute, dir);
  27843. }
  27844. else {
  27845. _this.bindings.set(attribute, node);
  27846. }
  27847. };
  27848. node.attributes.forEach(processAttribute);
  27849. node.inputs.forEach(processAttribute);
  27850. node.outputs.forEach(processAttribute);
  27851. if (node instanceof Template) {
  27852. node.templateAttrs.forEach(processAttribute);
  27853. }
  27854. // Recurse into the node's children.
  27855. node.children.forEach(function (child) { return child.visit(_this); });
  27856. };
  27857. // Unused visitors.
  27858. DirectiveBinder.prototype.visitContent = function (content) { };
  27859. DirectiveBinder.prototype.visitVariable = function (variable) { };
  27860. DirectiveBinder.prototype.visitReference = function (reference) { };
  27861. DirectiveBinder.prototype.visitTextAttribute = function (attribute) { };
  27862. DirectiveBinder.prototype.visitBoundAttribute = function (attribute) { };
  27863. DirectiveBinder.prototype.visitBoundEvent = function (attribute) { };
  27864. DirectiveBinder.prototype.visitBoundAttributeOrEvent = function (node) { };
  27865. DirectiveBinder.prototype.visitText = function (text) { };
  27866. DirectiveBinder.prototype.visitBoundText = function (text) { };
  27867. DirectiveBinder.prototype.visitIcu = function (icu) { };
  27868. return DirectiveBinder;
  27869. }());
  27870. /**
  27871. * Processes a template and extract metadata about expressions and symbols within.
  27872. *
  27873. * This is a companion to the `DirectiveBinder` that doesn't require knowledge of directives matched
  27874. * within the template in order to operate.
  27875. *
  27876. * Expressions are visited by the superclass `RecursiveAstVisitor`, with custom logic provided
  27877. * by overridden methods from that visitor.
  27878. */
  27879. var TemplateBinder = /** @class */ (function (_super) {
  27880. __extends(TemplateBinder, _super);
  27881. function TemplateBinder(bindings, symbols, usedPipes, nestingLevel, scope, template, level) {
  27882. var _this = _super.call(this) || this;
  27883. _this.bindings = bindings;
  27884. _this.symbols = symbols;
  27885. _this.usedPipes = usedPipes;
  27886. _this.nestingLevel = nestingLevel;
  27887. _this.scope = scope;
  27888. _this.template = template;
  27889. _this.level = level;
  27890. _this.pipesUsed = [];
  27891. // Save a bit of processing time by constructing this closure in advance.
  27892. _this.visitNode = function (node) { return node.visit(_this); };
  27893. return _this;
  27894. }
  27895. /**
  27896. * Process a template and extract metadata about expressions and symbols within.
  27897. *
  27898. * @param template the nodes of the template to process
  27899. * @param scope the `Scope` of the template being processed.
  27900. * @returns three maps which contain metadata about the template: `expressions` which interprets
  27901. * special `AST` nodes in expressions as pointing to references or variables declared within the
  27902. * template, `symbols` which maps those variables and references to the nested `Template` which
  27903. * declares them, if any, and `nestingLevel` which associates each `Template` with a integer
  27904. * nesting level (how many levels deep within the template structure the `Template` is), starting
  27905. * at 1.
  27906. */
  27907. TemplateBinder.apply = function (template, scope) {
  27908. var expressions = new Map();
  27909. var symbols = new Map();
  27910. var nestingLevel = new Map();
  27911. var usedPipes = new Set();
  27912. // The top-level template has nesting level 0.
  27913. var binder = new TemplateBinder(expressions, symbols, usedPipes, nestingLevel, scope, template instanceof Template ? template : null, 0);
  27914. binder.ingest(template);
  27915. return { expressions: expressions, symbols: symbols, nestingLevel: nestingLevel, usedPipes: usedPipes };
  27916. };
  27917. TemplateBinder.prototype.ingest = function (template) {
  27918. if (template instanceof Template) {
  27919. // For <ng-template>s, process only variables and child nodes. Inputs, outputs, templateAttrs,
  27920. // and references were all processed in the scope of the containing template.
  27921. template.variables.forEach(this.visitNode);
  27922. template.children.forEach(this.visitNode);
  27923. // Set the nesting level.
  27924. this.nestingLevel.set(template, this.level);
  27925. }
  27926. else {
  27927. // Visit each node from the top-level template.
  27928. template.forEach(this.visitNode);
  27929. }
  27930. };
  27931. TemplateBinder.prototype.visitElement = function (element) {
  27932. // Visit the inputs, outputs, and children of the element.
  27933. element.inputs.forEach(this.visitNode);
  27934. element.outputs.forEach(this.visitNode);
  27935. element.children.forEach(this.visitNode);
  27936. };
  27937. TemplateBinder.prototype.visitTemplate = function (template) {
  27938. // First, visit inputs, outputs and template attributes of the template node.
  27939. template.inputs.forEach(this.visitNode);
  27940. template.outputs.forEach(this.visitNode);
  27941. template.templateAttrs.forEach(this.visitNode);
  27942. // References are also evaluated in the outer context.
  27943. template.references.forEach(this.visitNode);
  27944. // Next, recurse into the template using its scope, and bumping the nesting level up by one.
  27945. var childScope = this.scope.getChildScope(template);
  27946. var binder = new TemplateBinder(this.bindings, this.symbols, this.usedPipes, this.nestingLevel, childScope, template, this.level + 1);
  27947. binder.ingest(template);
  27948. };
  27949. TemplateBinder.prototype.visitVariable = function (variable) {
  27950. // Register the `Variable` as a symbol in the current `Template`.
  27951. if (this.template !== null) {
  27952. this.symbols.set(variable, this.template);
  27953. }
  27954. };
  27955. TemplateBinder.prototype.visitReference = function (reference) {
  27956. // Register the `Reference` as a symbol in the current `Template`.
  27957. if (this.template !== null) {
  27958. this.symbols.set(reference, this.template);
  27959. }
  27960. };
  27961. // Unused template visitors
  27962. TemplateBinder.prototype.visitText = function (text) { };
  27963. TemplateBinder.prototype.visitContent = function (content) { };
  27964. TemplateBinder.prototype.visitTextAttribute = function (attribute) { };
  27965. TemplateBinder.prototype.visitIcu = function (icu) { };
  27966. // The remaining visitors are concerned with processing AST expressions within template bindings
  27967. TemplateBinder.prototype.visitBoundAttribute = function (attribute) { attribute.value.visit(this); };
  27968. TemplateBinder.prototype.visitBoundEvent = function (event) { event.handler.visit(this); };
  27969. TemplateBinder.prototype.visitBoundText = function (text) { text.value.visit(this); };
  27970. TemplateBinder.prototype.visitPipe = function (ast, context) {
  27971. this.usedPipes.add(ast.name);
  27972. return _super.prototype.visitPipe.call(this, ast, context);
  27973. };
  27974. // These five types of AST expressions can refer to expression roots, which could be variables
  27975. // or references in the current scope.
  27976. TemplateBinder.prototype.visitPropertyRead = function (ast, context) {
  27977. this.maybeMap(context, ast, ast.name);
  27978. return _super.prototype.visitPropertyRead.call(this, ast, context);
  27979. };
  27980. TemplateBinder.prototype.visitSafePropertyRead = function (ast, context) {
  27981. this.maybeMap(context, ast, ast.name);
  27982. return _super.prototype.visitSafePropertyRead.call(this, ast, context);
  27983. };
  27984. TemplateBinder.prototype.visitPropertyWrite = function (ast, context) {
  27985. this.maybeMap(context, ast, ast.name);
  27986. return _super.prototype.visitPropertyWrite.call(this, ast, context);
  27987. };
  27988. TemplateBinder.prototype.visitMethodCall = function (ast, context) {
  27989. this.maybeMap(context, ast, ast.name);
  27990. return _super.prototype.visitMethodCall.call(this, ast, context);
  27991. };
  27992. TemplateBinder.prototype.visitSafeMethodCall = function (ast, context) {
  27993. this.maybeMap(context, ast, ast.name);
  27994. return _super.prototype.visitSafeMethodCall.call(this, ast, context);
  27995. };
  27996. TemplateBinder.prototype.maybeMap = function (scope, ast, name) {
  27997. // If the receiver of the expression isn't the `ImplicitReceiver`, this isn't the root of an
  27998. // `AST` expression that maps to a `Variable` or `Reference`.
  27999. if (!(ast.receiver instanceof ImplicitReceiver)) {
  28000. return;
  28001. }
  28002. // Check whether the name exists in the current scope. If so, map it. Otherwise, the name is
  28003. // probably a property on the top-level component context.
  28004. var target = this.scope.lookup(name);
  28005. if (target !== null) {
  28006. this.bindings.set(ast, target);
  28007. }
  28008. };
  28009. return TemplateBinder;
  28010. }(RecursiveAstVisitor$1));
  28011. /**
  28012. * Metadata container for a `Target` that allows queries for specific bits of metadata.
  28013. *
  28014. * See `BoundTarget` for documentation on the individual methods.
  28015. */
  28016. var R3BoundTarget = /** @class */ (function () {
  28017. function R3BoundTarget(target, directives, bindings, references, exprTargets, symbols, nestingLevel, usedPipes) {
  28018. this.target = target;
  28019. this.directives = directives;
  28020. this.bindings = bindings;
  28021. this.references = references;
  28022. this.exprTargets = exprTargets;
  28023. this.symbols = symbols;
  28024. this.nestingLevel = nestingLevel;
  28025. this.usedPipes = usedPipes;
  28026. }
  28027. R3BoundTarget.prototype.getDirectivesOfNode = function (node) {
  28028. return this.directives.get(node) || null;
  28029. };
  28030. R3BoundTarget.prototype.getReferenceTarget = function (ref) {
  28031. return this.references.get(ref) || null;
  28032. };
  28033. R3BoundTarget.prototype.getConsumerOfBinding = function (binding) {
  28034. return this.bindings.get(binding) || null;
  28035. };
  28036. R3BoundTarget.prototype.getExpressionTarget = function (expr) {
  28037. return this.exprTargets.get(expr) || null;
  28038. };
  28039. R3BoundTarget.prototype.getTemplateOfSymbol = function (symbol) {
  28040. return this.symbols.get(symbol) || null;
  28041. };
  28042. R3BoundTarget.prototype.getNestingLevel = function (template) { return this.nestingLevel.get(template) || 0; };
  28043. R3BoundTarget.prototype.getUsedDirectives = function () {
  28044. var set = new Set();
  28045. this.directives.forEach(function (dirs) { return dirs.forEach(function (dir) { return set.add(dir); }); });
  28046. return Array.from(set.values());
  28047. };
  28048. R3BoundTarget.prototype.getUsedPipes = function () { return Array.from(this.usedPipes); };
  28049. return R3BoundTarget;
  28050. }());
  28051. /**
  28052. * @license
  28053. * Copyright Google Inc. All Rights Reserved.
  28054. *
  28055. * Use of this source code is governed by an MIT-style license that can be
  28056. * found in the LICENSE file at https://angular.io/license
  28057. */
  28058. // This file only reexports content of the `src` folder. Keep it that way.
  28059. // This function call has a global side effects and publishes the compiler into global namespace for
  28060. // the late binding of the Compiler to the @angular/core for jit compilation.
  28061. publishFacade(_global);
  28062. /**
  28063. * @license
  28064. * Copyright Google Inc. All Rights Reserved.
  28065. *
  28066. * Use of this source code is governed by an MIT-style license that can be
  28067. * found in the LICENSE file at https://angular.io/license
  28068. */
  28069. // This file only reexports content of the `src` folder. Keep it that way.
  28070. /**
  28071. * @license
  28072. * Copyright Google Inc. All Rights Reserved.
  28073. *
  28074. * Use of this source code is governed by an MIT-style license that can be
  28075. * found in the LICENSE file at https://angular.io/license
  28076. */
  28077. /**
  28078. * @license
  28079. * Copyright Google Inc. All Rights Reserved.
  28080. *
  28081. * Use of this source code is governed by an MIT-style license that can be
  28082. * found in the LICENSE file at https://angular.io/license
  28083. */
  28084. exports.core = core;
  28085. exports.CompilerConfig = CompilerConfig;
  28086. exports.preserveWhitespacesDefault = preserveWhitespacesDefault;
  28087. exports.isLoweredSymbol = isLoweredSymbol;
  28088. exports.createLoweredSymbol = createLoweredSymbol;
  28089. exports.Identifiers = Identifiers;
  28090. exports.JitCompiler = JitCompiler;
  28091. exports.ConstantPool = ConstantPool;
  28092. exports.DirectiveResolver = DirectiveResolver;
  28093. exports.PipeResolver = PipeResolver;
  28094. exports.NgModuleResolver = NgModuleResolver;
  28095. exports.DEFAULT_INTERPOLATION_CONFIG = DEFAULT_INTERPOLATION_CONFIG;
  28096. exports.InterpolationConfig = InterpolationConfig;
  28097. exports.NgModuleCompiler = NgModuleCompiler;
  28098. exports.ArrayType = ArrayType;
  28099. exports.AssertNotNull = AssertNotNull;
  28100. exports.DYNAMIC_TYPE = DYNAMIC_TYPE;
  28101. exports.BinaryOperatorExpr = BinaryOperatorExpr;
  28102. exports.BuiltinType = BuiltinType;
  28103. exports.CastExpr = CastExpr;
  28104. exports.ClassField = ClassField;
  28105. exports.ClassMethod = ClassMethod;
  28106. exports.ClassStmt = ClassStmt;
  28107. exports.CommaExpr = CommaExpr;
  28108. exports.CommentStmt = CommentStmt;
  28109. exports.ConditionalExpr = ConditionalExpr;
  28110. exports.DeclareFunctionStmt = DeclareFunctionStmt;
  28111. exports.DeclareVarStmt = DeclareVarStmt;
  28112. exports.Expression = Expression;
  28113. exports.ExpressionStatement = ExpressionStatement;
  28114. exports.ExpressionType = ExpressionType;
  28115. exports.ExternalExpr = ExternalExpr;
  28116. exports.ExternalReference = ExternalReference;
  28117. exports.literalMap = literalMap;
  28118. exports.FunctionExpr = FunctionExpr;
  28119. exports.IfStmt = IfStmt;
  28120. exports.InstantiateExpr = InstantiateExpr;
  28121. exports.InvokeFunctionExpr = InvokeFunctionExpr;
  28122. exports.InvokeMethodExpr = InvokeMethodExpr;
  28123. exports.JSDocCommentStmt = JSDocCommentStmt;
  28124. exports.LiteralArrayExpr = LiteralArrayExpr;
  28125. exports.LiteralExpr = LiteralExpr;
  28126. exports.LiteralMapExpr = LiteralMapExpr;
  28127. exports.MapType = MapType;
  28128. exports.NotExpr = NotExpr;
  28129. exports.ReadKeyExpr = ReadKeyExpr;
  28130. exports.ReadPropExpr = ReadPropExpr;
  28131. exports.ReadVarExpr = ReadVarExpr;
  28132. exports.ReturnStatement = ReturnStatement;
  28133. exports.ThrowStmt = ThrowStmt;
  28134. exports.TryCatchStmt = TryCatchStmt;
  28135. exports.Type = Type$1;
  28136. exports.WrappedNodeExpr = WrappedNodeExpr;
  28137. exports.WriteKeyExpr = WriteKeyExpr;
  28138. exports.WritePropExpr = WritePropExpr;
  28139. exports.WriteVarExpr = WriteVarExpr;
  28140. exports.Statement = Statement;
  28141. exports.TypeofExpr = TypeofExpr;
  28142. exports.collectExternalReferences = collectExternalReferences;
  28143. exports.EmitterVisitorContext = EmitterVisitorContext;
  28144. exports.JitEvaluator = JitEvaluator;
  28145. exports.ViewCompiler = ViewCompiler;
  28146. exports.findStaticQueryIds = findStaticQueryIds;
  28147. exports.staticViewQueryIds = staticViewQueryIds;
  28148. exports.getParseErrors = getParseErrors;
  28149. exports.isSyntaxError = isSyntaxError;
  28150. exports.syntaxError = syntaxError;
  28151. exports.Version = Version;
  28152. exports.TmplAstBoundAttribute = BoundAttribute;
  28153. exports.TmplAstBoundEvent = BoundEvent;
  28154. exports.TmplAstBoundText = BoundText;
  28155. exports.TmplAstContent = Content;
  28156. exports.TmplAstElement = Element;
  28157. exports.TmplAstReference = Reference;
  28158. exports.TmplAstTemplate = Template;
  28159. exports.TmplAstText = Text;
  28160. exports.TmplAstTextAttribute = TextAttribute;
  28161. exports.TmplAstVariable = Variable;
  28162. exports.R3Identifiers = Identifiers$1;
  28163. exports.compileInjector = compileInjector;
  28164. exports.compileNgModule = compileNgModule;
  28165. exports.compilePipeFromMetadata = compilePipeFromMetadata;
  28166. exports.makeBindingParser = makeBindingParser;
  28167. exports.parseTemplate = parseTemplate;
  28168. exports.compileBaseDefFromMetadata = compileBaseDefFromMetadata;
  28169. exports.compileComponentFromMetadata = compileComponentFromMetadata;
  28170. exports.compileDirectiveFromMetadata = compileDirectiveFromMetadata;
  28171. exports.parseHostBindings = parseHostBindings;
  28172. exports.verifyHostBindings = verifyHostBindings;
  28173. exports.publishFacade = publishFacade;
  28174. exports.VERSION = VERSION$1;
  28175. exports.TextAst = TextAst;
  28176. exports.BoundTextAst = BoundTextAst;
  28177. exports.AttrAst = AttrAst;
  28178. exports.BoundElementPropertyAst = BoundElementPropertyAst;
  28179. exports.BoundEventAst = BoundEventAst;
  28180. exports.ReferenceAst = ReferenceAst;
  28181. exports.VariableAst = VariableAst;
  28182. exports.ElementAst = ElementAst;
  28183. exports.EmbeddedTemplateAst = EmbeddedTemplateAst;
  28184. exports.BoundDirectivePropertyAst = BoundDirectivePropertyAst;
  28185. exports.DirectiveAst = DirectiveAst;
  28186. exports.ProviderAst = ProviderAst;
  28187. exports.NgContentAst = NgContentAst;
  28188. exports.NullTemplateVisitor = NullTemplateVisitor;
  28189. exports.RecursiveTemplateAstVisitor = RecursiveTemplateAstVisitor;
  28190. exports.templateVisitAll = templateVisitAll;
  28191. exports.sanitizeIdentifier = sanitizeIdentifier;
  28192. exports.identifierName = identifierName;
  28193. exports.identifierModuleUrl = identifierModuleUrl;
  28194. exports.viewClassName = viewClassName;
  28195. exports.rendererTypeName = rendererTypeName;
  28196. exports.hostViewClassName = hostViewClassName;
  28197. exports.componentFactoryName = componentFactoryName;
  28198. exports.tokenName = tokenName;
  28199. exports.tokenReference = tokenReference;
  28200. exports.CompileStylesheetMetadata = CompileStylesheetMetadata;
  28201. exports.CompileTemplateMetadata = CompileTemplateMetadata;
  28202. exports.CompileDirectiveMetadata = CompileDirectiveMetadata;
  28203. exports.CompilePipeMetadata = CompilePipeMetadata;
  28204. exports.CompileShallowModuleMetadata = CompileShallowModuleMetadata;
  28205. exports.CompileNgModuleMetadata = CompileNgModuleMetadata;
  28206. exports.TransitiveCompileNgModuleMetadata = TransitiveCompileNgModuleMetadata;
  28207. exports.ProviderMeta = ProviderMeta;
  28208. exports.flatten = flatten;
  28209. exports.templateSourceUrl = templateSourceUrl;
  28210. exports.sharedStylesheetJitUrl = sharedStylesheetJitUrl;
  28211. exports.ngModuleJitUrl = ngModuleJitUrl;
  28212. exports.templateJitUrl = templateJitUrl;
  28213. exports.createAotUrlResolver = createAotUrlResolver;
  28214. exports.createAotCompiler = createAotCompiler;
  28215. exports.AotCompiler = AotCompiler;
  28216. exports.analyzeNgModules = analyzeNgModules;
  28217. exports.analyzeAndValidateNgModules = analyzeAndValidateNgModules;
  28218. exports.analyzeFile = analyzeFile;
  28219. exports.analyzeFileForInjectables = analyzeFileForInjectables;
  28220. exports.mergeAnalyzedFiles = mergeAnalyzedFiles;
  28221. exports.GeneratedFile = GeneratedFile;
  28222. exports.toTypeScript = toTypeScript;
  28223. exports.formattedError = formattedError;
  28224. exports.isFormattedError = isFormattedError;
  28225. exports.StaticReflector = StaticReflector;
  28226. exports.StaticSymbol = StaticSymbol;
  28227. exports.StaticSymbolCache = StaticSymbolCache;
  28228. exports.ResolvedStaticSymbol = ResolvedStaticSymbol;
  28229. exports.StaticSymbolResolver = StaticSymbolResolver;
  28230. exports.unescapeIdentifier = unescapeIdentifier;
  28231. exports.unwrapResolvedMetadata = unwrapResolvedMetadata;
  28232. exports.AotSummaryResolver = AotSummaryResolver;
  28233. exports.AstPath = AstPath;
  28234. exports.SummaryResolver = SummaryResolver;
  28235. exports.JitSummaryResolver = JitSummaryResolver;
  28236. exports.CompileReflector = CompileReflector;
  28237. exports.createUrlResolverWithoutPackagePrefix = createUrlResolverWithoutPackagePrefix;
  28238. exports.createOfflineCompileUrlResolver = createOfflineCompileUrlResolver;
  28239. exports.UrlResolver = UrlResolver;
  28240. exports.getUrlScheme = getUrlScheme;
  28241. exports.ResourceLoader = ResourceLoader;
  28242. exports.ElementSchemaRegistry = ElementSchemaRegistry;
  28243. exports.Extractor = Extractor;
  28244. exports.I18NHtmlParser = I18NHtmlParser;
  28245. exports.MessageBundle = MessageBundle;
  28246. exports.Serializer = Serializer;
  28247. exports.Xliff = Xliff;
  28248. exports.Xliff2 = Xliff2;
  28249. exports.Xmb = Xmb;
  28250. exports.Xtb = Xtb;
  28251. exports.DirectiveNormalizer = DirectiveNormalizer;
  28252. exports.ParserError = ParserError;
  28253. exports.ParseSpan = ParseSpan;
  28254. exports.AST = AST;
  28255. exports.Quote = Quote;
  28256. exports.EmptyExpr = EmptyExpr;
  28257. exports.ImplicitReceiver = ImplicitReceiver;
  28258. exports.Chain = Chain;
  28259. exports.Conditional = Conditional;
  28260. exports.PropertyRead = PropertyRead;
  28261. exports.PropertyWrite = PropertyWrite;
  28262. exports.SafePropertyRead = SafePropertyRead;
  28263. exports.KeyedRead = KeyedRead;
  28264. exports.KeyedWrite = KeyedWrite;
  28265. exports.BindingPipe = BindingPipe;
  28266. exports.LiteralPrimitive = LiteralPrimitive;
  28267. exports.LiteralArray = LiteralArray;
  28268. exports.LiteralMap = LiteralMap;
  28269. exports.Interpolation = Interpolation;
  28270. exports.Binary = Binary;
  28271. exports.PrefixNot = PrefixNot;
  28272. exports.NonNullAssert = NonNullAssert;
  28273. exports.MethodCall = MethodCall;
  28274. exports.SafeMethodCall = SafeMethodCall;
  28275. exports.FunctionCall = FunctionCall;
  28276. exports.ASTWithSource = ASTWithSource;
  28277. exports.TemplateBinding = TemplateBinding;
  28278. exports.NullAstVisitor = NullAstVisitor;
  28279. exports.RecursiveAstVisitor = RecursiveAstVisitor$1;
  28280. exports.AstTransformer = AstTransformer$1;
  28281. exports.AstMemoryEfficientTransformer = AstMemoryEfficientTransformer;
  28282. exports.visitAstChildren = visitAstChildren;
  28283. exports.ParsedProperty = ParsedProperty;
  28284. exports.ParsedEvent = ParsedEvent;
  28285. exports.ParsedVariable = ParsedVariable;
  28286. exports.BoundElementProperty = BoundElementProperty;
  28287. exports.Lexer = Lexer;
  28288. exports.Token = Token$1;
  28289. exports.EOF = EOF;
  28290. exports.isIdentifier = isIdentifier;
  28291. exports.isQuote = isQuote;
  28292. exports.SplitInterpolation = SplitInterpolation;
  28293. exports.TemplateBindingParseResult = TemplateBindingParseResult;
  28294. exports.Parser = Parser$1;
  28295. exports._ParseAST = _ParseAST;
  28296. exports.ERROR_COMPONENT_TYPE = ERROR_COMPONENT_TYPE;
  28297. exports.CompileMetadataResolver = CompileMetadataResolver;
  28298. exports.Text = Text$3;
  28299. exports.Expansion = Expansion;
  28300. exports.ExpansionCase = ExpansionCase;
  28301. exports.Attribute = Attribute;
  28302. exports.Element = Element$1;
  28303. exports.Comment = Comment;
  28304. exports.visitAll = visitAll$1;
  28305. exports.RecursiveVisitor = RecursiveVisitor;
  28306. exports.findNode = findNode;
  28307. exports.HtmlParser = HtmlParser;
  28308. exports.ParseTreeResult = ParseTreeResult;
  28309. exports.TreeError = TreeError;
  28310. exports.HtmlTagDefinition = HtmlTagDefinition;
  28311. exports.getHtmlTagDefinition = getHtmlTagDefinition;
  28312. exports.splitNsName = splitNsName;
  28313. exports.isNgContainer = isNgContainer;
  28314. exports.isNgContent = isNgContent;
  28315. exports.isNgTemplate = isNgTemplate;
  28316. exports.getNsPrefix = getNsPrefix;
  28317. exports.mergeNsAndName = mergeNsAndName;
  28318. exports.NAMED_ENTITIES = NAMED_ENTITIES;
  28319. exports.NGSP_UNICODE = NGSP_UNICODE;
  28320. exports.debugOutputAstAsTypeScript = debugOutputAstAsTypeScript;
  28321. exports.TypeScriptEmitter = TypeScriptEmitter;
  28322. exports.ParseLocation = ParseLocation;
  28323. exports.ParseSourceFile = ParseSourceFile;
  28324. exports.ParseSourceSpan = ParseSourceSpan;
  28325. exports.ParseError = ParseError;
  28326. exports.typeSourceSpan = typeSourceSpan;
  28327. exports.r3JitTypeSourceSpan = r3JitTypeSourceSpan;
  28328. exports.DomElementSchemaRegistry = DomElementSchemaRegistry;
  28329. exports.CssSelector = CssSelector;
  28330. exports.SelectorMatcher = SelectorMatcher;
  28331. exports.SelectorListContext = SelectorListContext;
  28332. exports.SelectorContext = SelectorContext;
  28333. exports.HOST_ATTR = HOST_ATTR;
  28334. exports.CONTENT_ATTR = CONTENT_ATTR;
  28335. exports.StylesCompileDependency = StylesCompileDependency;
  28336. exports.CompiledStylesheet = CompiledStylesheet;
  28337. exports.StyleCompiler = StyleCompiler;
  28338. exports.TemplateParseError = TemplateParseError;
  28339. exports.TemplateParseResult = TemplateParseResult;
  28340. exports.TemplateParser = TemplateParser;
  28341. exports.splitClasses = splitClasses;
  28342. exports.createElementCssSelector = createElementCssSelector;
  28343. exports.removeSummaryDuplicates = removeSummaryDuplicates;
  28344. exports.isEmptyExpression = isEmptyExpression;
  28345. exports.compileInjectable = compileInjectable;
  28346. exports.R3TargetBinder = R3TargetBinder;
  28347. exports.R3BoundTarget = R3BoundTarget;
  28348. Object.defineProperty(exports, '__esModule', { value: true });
  28349. }));
  28350. //# sourceMappingURL=compiler.umd.js.map