compiler-dom.global.js 231 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703
  1. var VueCompilerDOM = (function (exports) {
  2. 'use strict';
  3. /**
  4. * Make a map and return a function for checking if a key
  5. * is in that map.
  6. * IMPORTANT: all calls of this function must be prefixed with
  7. * \/\*#\_\_PURE\_\_\*\/
  8. * So that rollup can tree-shake them if necessary.
  9. */
  10. function makeMap(str, expectsLowerCase) {
  11. const map = Object.create(null);
  12. const list = str.split(',');
  13. for (let i = 0; i < list.length; i++) {
  14. map[list[i]] = true;
  15. }
  16. return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
  17. }
  18. /**
  19. * dev only flag -> name mapping
  20. */
  21. const PatchFlagNames = {
  22. [1 /* PatchFlags.TEXT */]: `TEXT`,
  23. [2 /* PatchFlags.CLASS */]: `CLASS`,
  24. [4 /* PatchFlags.STYLE */]: `STYLE`,
  25. [8 /* PatchFlags.PROPS */]: `PROPS`,
  26. [16 /* PatchFlags.FULL_PROPS */]: `FULL_PROPS`,
  27. [32 /* PatchFlags.HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
  28. [64 /* PatchFlags.STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
  29. [128 /* PatchFlags.KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
  30. [256 /* PatchFlags.UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
  31. [512 /* PatchFlags.NEED_PATCH */]: `NEED_PATCH`,
  32. [1024 /* PatchFlags.DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
  33. [2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
  34. [-1 /* PatchFlags.HOISTED */]: `HOISTED`,
  35. [-2 /* PatchFlags.BAIL */]: `BAIL`
  36. };
  37. /**
  38. * Dev only
  39. */
  40. const slotFlagsText = {
  41. [1 /* SlotFlags.STABLE */]: 'STABLE',
  42. [2 /* SlotFlags.DYNAMIC */]: 'DYNAMIC',
  43. [3 /* SlotFlags.FORWARDED */]: 'FORWARDED'
  44. };
  45. const range = 2;
  46. function generateCodeFrame(source, start = 0, end = source.length) {
  47. // Split the content into individual lines but capture the newline sequence
  48. // that separated each line. This is important because the actual sequence is
  49. // needed to properly take into account the full line length for offset
  50. // comparison
  51. let lines = source.split(/(\r?\n)/);
  52. // Separate the lines and newline sequences into separate arrays for easier referencing
  53. const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);
  54. lines = lines.filter((_, idx) => idx % 2 === 0);
  55. let count = 0;
  56. const res = [];
  57. for (let i = 0; i < lines.length; i++) {
  58. count +=
  59. lines[i].length +
  60. ((newlineSequences[i] && newlineSequences[i].length) || 0);
  61. if (count >= start) {
  62. for (let j = i - range; j <= i + range || end > count; j++) {
  63. if (j < 0 || j >= lines.length)
  64. continue;
  65. const line = j + 1;
  66. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  67. const lineLength = lines[j].length;
  68. const newLineSeqLength = (newlineSequences[j] && newlineSequences[j].length) || 0;
  69. if (j === i) {
  70. // push underline
  71. const pad = start - (count - (lineLength + newLineSeqLength));
  72. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  73. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  74. }
  75. else if (j > i) {
  76. if (end > count) {
  77. const length = Math.max(Math.min(end - count, lineLength), 1);
  78. res.push(` | ` + '^'.repeat(length));
  79. }
  80. count += lineLength + newLineSeqLength;
  81. }
  82. }
  83. break;
  84. }
  85. }
  86. return res.join('\n');
  87. }
  88. const listDelimiterRE = /;(?![^(]*\))/g;
  89. const propertyDelimiterRE = /:([^]+)/;
  90. const styleCommentRE = /\/\*.*?\*\//gs;
  91. function parseStringStyle(cssText) {
  92. const ret = {};
  93. cssText
  94. .replace(styleCommentRE, '')
  95. .split(listDelimiterRE)
  96. .forEach(item => {
  97. if (item) {
  98. const tmp = item.split(propertyDelimiterRE);
  99. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  100. }
  101. });
  102. return ret;
  103. }
  104. // These tag configs are shared between compiler-dom and runtime-dom, so they
  105. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  106. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  107. 'header,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,' +
  108. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  109. 'data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,' +
  110. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  111. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  112. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  113. 'option,output,progress,select,textarea,details,dialog,menu,' +
  114. 'summary,template,blockquote,iframe,tfoot';
  115. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  116. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  117. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  118. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  119. 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  120. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  121. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  122. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  123. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  124. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  125. 'text,textPath,title,tspan,unknown,use,view';
  126. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  127. /**
  128. * Compiler only.
  129. * Do NOT use in runtime code paths unless behind `true` flag.
  130. */
  131. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  132. /**
  133. * Compiler only.
  134. * Do NOT use in runtime code paths unless behind `true` flag.
  135. */
  136. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  137. /**
  138. * Compiler only.
  139. * Do NOT use in runtime code paths unless behind `true` flag.
  140. */
  141. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  142. const EMPTY_OBJ = Object.freeze({})
  143. ;
  144. Object.freeze([]) ;
  145. const NOOP = () => { };
  146. /**
  147. * Always return false.
  148. */
  149. const NO = () => false;
  150. const onRE = /^on[^a-z]/;
  151. const isOn = (key) => onRE.test(key);
  152. const extend = Object.assign;
  153. const isArray = Array.isArray;
  154. const isString = (val) => typeof val === 'string';
  155. const isSymbol = (val) => typeof val === 'symbol';
  156. const isObject = (val) => val !== null && typeof val === 'object';
  157. const isReservedProp = /*#__PURE__*/ makeMap(
  158. // the leading comma is intentional so empty string "" is also included
  159. ',key,ref,ref_for,ref_key,' +
  160. 'onVnodeBeforeMount,onVnodeMounted,' +
  161. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  162. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  163. const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo');
  164. const cacheStringFunction = (fn) => {
  165. const cache = Object.create(null);
  166. return ((str) => {
  167. const hit = cache[str];
  168. return hit || (cache[str] = fn(str));
  169. });
  170. };
  171. const camelizeRE = /-(\w)/g;
  172. /**
  173. * @private
  174. */
  175. const camelize = cacheStringFunction((str) => {
  176. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  177. });
  178. const hyphenateRE = /\B([A-Z])/g;
  179. /**
  180. * @private
  181. */
  182. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  183. /**
  184. * @private
  185. */
  186. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  187. /**
  188. * @private
  189. */
  190. const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
  191. function defaultOnError(error) {
  192. throw error;
  193. }
  194. function defaultOnWarn(msg) {
  195. console.warn(`[Vue warn] ${msg.message}`);
  196. }
  197. function createCompilerError(code, loc, messages, additionalMessage) {
  198. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  199. ;
  200. const error = new SyntaxError(String(msg));
  201. error.code = code;
  202. error.loc = loc;
  203. return error;
  204. }
  205. const errorMessages = {
  206. // parse errors
  207. [0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  208. [1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  209. [2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  210. [3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  211. [4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  212. [5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  213. [6 /* ErrorCodes.EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  214. [7 /* ErrorCodes.EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  215. [8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  216. [9 /* ErrorCodes.EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  217. [10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  218. [11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  219. [12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  220. [13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  221. [14 /* ErrorCodes.MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  222. [15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  223. [16 /* ErrorCodes.NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  224. [17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  225. [18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  226. [19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  227. [21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  228. [20 /* ErrorCodes.UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
  229. [22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  230. // Vue-specific parse errors
  231. [23 /* ErrorCodes.X_INVALID_END_TAG */]: 'Invalid end tag.',
  232. [24 /* ErrorCodes.X_MISSING_END_TAG */]: 'Element is missing end tag.',
  233. [25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  234. [27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  235. 'Note that dynamic directive argument cannot contain spaces.',
  236. [26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
  237. // transform errors
  238. [28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  239. [29 /* ErrorCodes.X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  240. [30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
  241. [31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  242. [32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  243. [33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  244. [34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  245. [35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  246. [36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  247. [37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
  248. `When there are multiple named slots, all slots should use <template> ` +
  249. `syntax to avoid scope ambiguity.`,
  250. [38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  251. [39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  252. `default slot. These children will be ignored.`,
  253. [40 /* ErrorCodes.X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  254. [41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  255. [42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  256. [43 /* ErrorCodes.X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  257. [44 /* ErrorCodes.X_V_MODEL_ON_PROPS */]: `v-model cannot be used on a prop, because local prop bindings are not writable.\nUse a v-bind binding combined with a v-on listener that emits update:x event instead.`,
  258. [45 /* ErrorCodes.X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  259. [46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  260. // generic errors
  261. [47 /* ErrorCodes.X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  262. [48 /* ErrorCodes.X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  263. [49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  264. [50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
  265. // just to fulfill types
  266. [51 /* ErrorCodes.__EXTEND_POINT__ */]: ``
  267. };
  268. const FRAGMENT = Symbol(`Fragment` );
  269. const TELEPORT = Symbol(`Teleport` );
  270. const SUSPENSE = Symbol(`Suspense` );
  271. const KEEP_ALIVE = Symbol(`KeepAlive` );
  272. const BASE_TRANSITION = Symbol(`BaseTransition` );
  273. const OPEN_BLOCK = Symbol(`openBlock` );
  274. const CREATE_BLOCK = Symbol(`createBlock` );
  275. const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
  276. const CREATE_VNODE = Symbol(`createVNode` );
  277. const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
  278. const CREATE_COMMENT = Symbol(`createCommentVNode` );
  279. const CREATE_TEXT = Symbol(`createTextVNode` );
  280. const CREATE_STATIC = Symbol(`createStaticVNode` );
  281. const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
  282. const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
  283. const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
  284. const RESOLVE_FILTER = Symbol(`resolveFilter` );
  285. const WITH_DIRECTIVES = Symbol(`withDirectives` );
  286. const RENDER_LIST = Symbol(`renderList` );
  287. const RENDER_SLOT = Symbol(`renderSlot` );
  288. const CREATE_SLOTS = Symbol(`createSlots` );
  289. const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
  290. const MERGE_PROPS = Symbol(`mergeProps` );
  291. const NORMALIZE_CLASS = Symbol(`normalizeClass` );
  292. const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
  293. const NORMALIZE_PROPS = Symbol(`normalizeProps` );
  294. const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
  295. const TO_HANDLERS = Symbol(`toHandlers` );
  296. const CAMELIZE = Symbol(`camelize` );
  297. const CAPITALIZE = Symbol(`capitalize` );
  298. const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
  299. const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
  300. const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
  301. const POP_SCOPE_ID = Symbol(`popScopeId` );
  302. const WITH_CTX = Symbol(`withCtx` );
  303. const UNREF = Symbol(`unref` );
  304. const IS_REF = Symbol(`isRef` );
  305. const WITH_MEMO = Symbol(`withMemo` );
  306. const IS_MEMO_SAME = Symbol(`isMemoSame` );
  307. // Name mapping for runtime helpers that need to be imported from 'vue' in
  308. // generated code. Make sure these are correctly exported in the runtime!
  309. const helperNameMap = {
  310. [FRAGMENT]: `Fragment`,
  311. [TELEPORT]: `Teleport`,
  312. [SUSPENSE]: `Suspense`,
  313. [KEEP_ALIVE]: `KeepAlive`,
  314. [BASE_TRANSITION]: `BaseTransition`,
  315. [OPEN_BLOCK]: `openBlock`,
  316. [CREATE_BLOCK]: `createBlock`,
  317. [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
  318. [CREATE_VNODE]: `createVNode`,
  319. [CREATE_ELEMENT_VNODE]: `createElementVNode`,
  320. [CREATE_COMMENT]: `createCommentVNode`,
  321. [CREATE_TEXT]: `createTextVNode`,
  322. [CREATE_STATIC]: `createStaticVNode`,
  323. [RESOLVE_COMPONENT]: `resolveComponent`,
  324. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  325. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  326. [RESOLVE_FILTER]: `resolveFilter`,
  327. [WITH_DIRECTIVES]: `withDirectives`,
  328. [RENDER_LIST]: `renderList`,
  329. [RENDER_SLOT]: `renderSlot`,
  330. [CREATE_SLOTS]: `createSlots`,
  331. [TO_DISPLAY_STRING]: `toDisplayString`,
  332. [MERGE_PROPS]: `mergeProps`,
  333. [NORMALIZE_CLASS]: `normalizeClass`,
  334. [NORMALIZE_STYLE]: `normalizeStyle`,
  335. [NORMALIZE_PROPS]: `normalizeProps`,
  336. [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
  337. [TO_HANDLERS]: `toHandlers`,
  338. [CAMELIZE]: `camelize`,
  339. [CAPITALIZE]: `capitalize`,
  340. [TO_HANDLER_KEY]: `toHandlerKey`,
  341. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  342. [PUSH_SCOPE_ID]: `pushScopeId`,
  343. [POP_SCOPE_ID]: `popScopeId`,
  344. [WITH_CTX]: `withCtx`,
  345. [UNREF]: `unref`,
  346. [IS_REF]: `isRef`,
  347. [WITH_MEMO]: `withMemo`,
  348. [IS_MEMO_SAME]: `isMemoSame`
  349. };
  350. function registerRuntimeHelpers(helpers) {
  351. Object.getOwnPropertySymbols(helpers).forEach(s => {
  352. helperNameMap[s] = helpers[s];
  353. });
  354. }
  355. // AST Utilities ---------------------------------------------------------------
  356. // Some expressions, e.g. sequence and conditional expressions, are never
  357. // associated with template nodes, so their source locations are just a stub.
  358. // Container types like CompoundExpression also don't need a real location.
  359. const locStub = {
  360. source: '',
  361. start: { line: 1, column: 1, offset: 0 },
  362. end: { line: 1, column: 1, offset: 0 }
  363. };
  364. function createRoot(children, loc = locStub) {
  365. return {
  366. type: 0 /* NodeTypes.ROOT */,
  367. children,
  368. helpers: [],
  369. components: [],
  370. directives: [],
  371. hoists: [],
  372. imports: [],
  373. cached: 0,
  374. temps: 0,
  375. codegenNode: undefined,
  376. loc
  377. };
  378. }
  379. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
  380. if (context) {
  381. if (isBlock) {
  382. context.helper(OPEN_BLOCK);
  383. context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
  384. }
  385. else {
  386. context.helper(getVNodeHelper(context.inSSR, isComponent));
  387. }
  388. if (directives) {
  389. context.helper(WITH_DIRECTIVES);
  390. }
  391. }
  392. return {
  393. type: 13 /* NodeTypes.VNODE_CALL */,
  394. tag,
  395. props,
  396. children,
  397. patchFlag,
  398. dynamicProps,
  399. directives,
  400. isBlock,
  401. disableTracking,
  402. isComponent,
  403. loc
  404. };
  405. }
  406. function createArrayExpression(elements, loc = locStub) {
  407. return {
  408. type: 17 /* NodeTypes.JS_ARRAY_EXPRESSION */,
  409. loc,
  410. elements
  411. };
  412. }
  413. function createObjectExpression(properties, loc = locStub) {
  414. return {
  415. type: 15 /* NodeTypes.JS_OBJECT_EXPRESSION */,
  416. loc,
  417. properties
  418. };
  419. }
  420. function createObjectProperty(key, value) {
  421. return {
  422. type: 16 /* NodeTypes.JS_PROPERTY */,
  423. loc: locStub,
  424. key: isString(key) ? createSimpleExpression(key, true) : key,
  425. value
  426. };
  427. }
  428. function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* ConstantTypes.NOT_CONSTANT */) {
  429. return {
  430. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  431. loc,
  432. content,
  433. isStatic,
  434. constType: isStatic ? 3 /* ConstantTypes.CAN_STRINGIFY */ : constType
  435. };
  436. }
  437. function createInterpolation(content, loc) {
  438. return {
  439. type: 5 /* NodeTypes.INTERPOLATION */,
  440. loc,
  441. content: isString(content)
  442. ? createSimpleExpression(content, false, loc)
  443. : content
  444. };
  445. }
  446. function createCompoundExpression(children, loc = locStub) {
  447. return {
  448. type: 8 /* NodeTypes.COMPOUND_EXPRESSION */,
  449. loc,
  450. children
  451. };
  452. }
  453. function createCallExpression(callee, args = [], loc = locStub) {
  454. return {
  455. type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
  456. loc,
  457. callee,
  458. arguments: args
  459. };
  460. }
  461. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  462. return {
  463. type: 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */,
  464. params,
  465. returns,
  466. newline,
  467. isSlot,
  468. loc
  469. };
  470. }
  471. function createConditionalExpression(test, consequent, alternate, newline = true) {
  472. return {
  473. type: 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */,
  474. test,
  475. consequent,
  476. alternate,
  477. newline,
  478. loc: locStub
  479. };
  480. }
  481. function createCacheExpression(index, value, isVNode = false) {
  482. return {
  483. type: 20 /* NodeTypes.JS_CACHE_EXPRESSION */,
  484. index,
  485. value,
  486. isVNode,
  487. loc: locStub
  488. };
  489. }
  490. function createBlockStatement(body) {
  491. return {
  492. type: 21 /* NodeTypes.JS_BLOCK_STATEMENT */,
  493. body,
  494. loc: locStub
  495. };
  496. }
  497. function createTemplateLiteral(elements) {
  498. return {
  499. type: 22 /* NodeTypes.JS_TEMPLATE_LITERAL */,
  500. elements,
  501. loc: locStub
  502. };
  503. }
  504. function createIfStatement(test, consequent, alternate) {
  505. return {
  506. type: 23 /* NodeTypes.JS_IF_STATEMENT */,
  507. test,
  508. consequent,
  509. alternate,
  510. loc: locStub
  511. };
  512. }
  513. function createAssignmentExpression(left, right) {
  514. return {
  515. type: 24 /* NodeTypes.JS_ASSIGNMENT_EXPRESSION */,
  516. left,
  517. right,
  518. loc: locStub
  519. };
  520. }
  521. function createSequenceExpression(expressions) {
  522. return {
  523. type: 25 /* NodeTypes.JS_SEQUENCE_EXPRESSION */,
  524. expressions,
  525. loc: locStub
  526. };
  527. }
  528. function createReturnStatement(returns) {
  529. return {
  530. type: 26 /* NodeTypes.JS_RETURN_STATEMENT */,
  531. returns,
  532. loc: locStub
  533. };
  534. }
  535. const isStaticExp = (p) => p.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && p.isStatic;
  536. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  537. function isCoreComponent(tag) {
  538. if (isBuiltInType(tag, 'Teleport')) {
  539. return TELEPORT;
  540. }
  541. else if (isBuiltInType(tag, 'Suspense')) {
  542. return SUSPENSE;
  543. }
  544. else if (isBuiltInType(tag, 'KeepAlive')) {
  545. return KEEP_ALIVE;
  546. }
  547. else if (isBuiltInType(tag, 'BaseTransition')) {
  548. return BASE_TRANSITION;
  549. }
  550. }
  551. const nonIdentifierRE = /^\d|[^\$\w]/;
  552. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  553. const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
  554. const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
  555. const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
  556. /**
  557. * Simple lexer to check if an expression is a member expression. This is
  558. * lax and only checks validity at the root level (i.e. does not validate exps
  559. * inside square brackets), but it's ok since these are only used on template
  560. * expressions and false positives are invalid expressions in the first place.
  561. */
  562. const isMemberExpressionBrowser = (path) => {
  563. // remove whitespaces around . or [ first
  564. path = path.trim().replace(whitespaceRE, s => s.trim());
  565. let state = 0 /* MemberExpLexState.inMemberExp */;
  566. let stateStack = [];
  567. let currentOpenBracketCount = 0;
  568. let currentOpenParensCount = 0;
  569. let currentStringType = null;
  570. for (let i = 0; i < path.length; i++) {
  571. const char = path.charAt(i);
  572. switch (state) {
  573. case 0 /* MemberExpLexState.inMemberExp */:
  574. if (char === '[') {
  575. stateStack.push(state);
  576. state = 1 /* MemberExpLexState.inBrackets */;
  577. currentOpenBracketCount++;
  578. }
  579. else if (char === '(') {
  580. stateStack.push(state);
  581. state = 2 /* MemberExpLexState.inParens */;
  582. currentOpenParensCount++;
  583. }
  584. else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
  585. return false;
  586. }
  587. break;
  588. case 1 /* MemberExpLexState.inBrackets */:
  589. if (char === `'` || char === `"` || char === '`') {
  590. stateStack.push(state);
  591. state = 3 /* MemberExpLexState.inString */;
  592. currentStringType = char;
  593. }
  594. else if (char === `[`) {
  595. currentOpenBracketCount++;
  596. }
  597. else if (char === `]`) {
  598. if (!--currentOpenBracketCount) {
  599. state = stateStack.pop();
  600. }
  601. }
  602. break;
  603. case 2 /* MemberExpLexState.inParens */:
  604. if (char === `'` || char === `"` || char === '`') {
  605. stateStack.push(state);
  606. state = 3 /* MemberExpLexState.inString */;
  607. currentStringType = char;
  608. }
  609. else if (char === `(`) {
  610. currentOpenParensCount++;
  611. }
  612. else if (char === `)`) {
  613. // if the exp ends as a call then it should not be considered valid
  614. if (i === path.length - 1) {
  615. return false;
  616. }
  617. if (!--currentOpenParensCount) {
  618. state = stateStack.pop();
  619. }
  620. }
  621. break;
  622. case 3 /* MemberExpLexState.inString */:
  623. if (char === currentStringType) {
  624. state = stateStack.pop();
  625. currentStringType = null;
  626. }
  627. break;
  628. }
  629. }
  630. return !currentOpenBracketCount && !currentOpenParensCount;
  631. };
  632. const isMemberExpressionNode = NOOP
  633. ;
  634. const isMemberExpression = isMemberExpressionBrowser
  635. ;
  636. function getInnerRange(loc, offset, length) {
  637. const source = loc.source.slice(offset, offset + length);
  638. const newLoc = {
  639. source,
  640. start: advancePositionWithClone(loc.start, loc.source, offset),
  641. end: loc.end
  642. };
  643. if (length != null) {
  644. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  645. }
  646. return newLoc;
  647. }
  648. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  649. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  650. }
  651. // advance by mutation without cloning (for performance reasons), since this
  652. // gets called a lot in the parser
  653. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  654. let linesCount = 0;
  655. let lastNewLinePos = -1;
  656. for (let i = 0; i < numberOfCharacters; i++) {
  657. if (source.charCodeAt(i) === 10 /* newline char code */) {
  658. linesCount++;
  659. lastNewLinePos = i;
  660. }
  661. }
  662. pos.offset += numberOfCharacters;
  663. pos.line += linesCount;
  664. pos.column =
  665. lastNewLinePos === -1
  666. ? pos.column + numberOfCharacters
  667. : numberOfCharacters - lastNewLinePos;
  668. return pos;
  669. }
  670. function assert(condition, msg) {
  671. /* istanbul ignore if */
  672. if (!condition) {
  673. throw new Error(msg || `unexpected compiler condition`);
  674. }
  675. }
  676. function findDir(node, name, allowEmpty = false) {
  677. for (let i = 0; i < node.props.length; i++) {
  678. const p = node.props[i];
  679. if (p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  680. (allowEmpty || p.exp) &&
  681. (isString(name) ? p.name === name : name.test(p.name))) {
  682. return p;
  683. }
  684. }
  685. }
  686. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  687. for (let i = 0; i < node.props.length; i++) {
  688. const p = node.props[i];
  689. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  690. if (dynamicOnly)
  691. continue;
  692. if (p.name === name && (p.value || allowEmpty)) {
  693. return p;
  694. }
  695. }
  696. else if (p.name === 'bind' &&
  697. (p.exp || allowEmpty) &&
  698. isStaticArgOf(p.arg, name)) {
  699. return p;
  700. }
  701. }
  702. }
  703. function isStaticArgOf(arg, name) {
  704. return !!(arg && isStaticExp(arg) && arg.content === name);
  705. }
  706. function hasDynamicKeyVBind(node) {
  707. return node.props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  708. p.name === 'bind' &&
  709. (!p.arg || // v-bind="obj"
  710. p.arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  711. !p.arg.isStatic) // v-bind:[foo]
  712. );
  713. }
  714. function isText(node) {
  715. return node.type === 5 /* NodeTypes.INTERPOLATION */ || node.type === 2 /* NodeTypes.TEXT */;
  716. }
  717. function isVSlot(p) {
  718. return p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'slot';
  719. }
  720. function isTemplateNode(node) {
  721. return (node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 3 /* ElementTypes.TEMPLATE */);
  722. }
  723. function isSlotOutlet(node) {
  724. return node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 2 /* ElementTypes.SLOT */;
  725. }
  726. function getVNodeHelper(ssr, isComponent) {
  727. return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
  728. }
  729. function getVNodeBlockHelper(ssr, isComponent) {
  730. return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
  731. }
  732. const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
  733. function getUnnormalizedProps(props, callPath = []) {
  734. if (props &&
  735. !isString(props) &&
  736. props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  737. const callee = props.callee;
  738. if (!isString(callee) && propsHelperSet.has(callee)) {
  739. return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
  740. }
  741. }
  742. return [props, callPath];
  743. }
  744. function injectProp(node, prop, context) {
  745. let propsWithInjection;
  746. /**
  747. * 1. mergeProps(...)
  748. * 2. toHandlers(...)
  749. * 3. normalizeProps(...)
  750. * 4. normalizeProps(guardReactiveProps(...))
  751. *
  752. * we need to get the real props before normalization
  753. */
  754. let props = node.type === 13 /* NodeTypes.VNODE_CALL */ ? node.props : node.arguments[2];
  755. let callPath = [];
  756. let parentCall;
  757. if (props &&
  758. !isString(props) &&
  759. props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  760. const ret = getUnnormalizedProps(props);
  761. props = ret[0];
  762. callPath = ret[1];
  763. parentCall = callPath[callPath.length - 1];
  764. }
  765. if (props == null || isString(props)) {
  766. propsWithInjection = createObjectExpression([prop]);
  767. }
  768. else if (props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  769. // merged props... add ours
  770. // only inject key to object literal if it's the first argument so that
  771. // if doesn't override user provided keys
  772. const first = props.arguments[0];
  773. if (!isString(first) && first.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  774. // #6631
  775. if (!hasProp(prop, first)) {
  776. first.properties.unshift(prop);
  777. }
  778. }
  779. else {
  780. if (props.callee === TO_HANDLERS) {
  781. // #2366
  782. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  783. createObjectExpression([prop]),
  784. props
  785. ]);
  786. }
  787. else {
  788. props.arguments.unshift(createObjectExpression([prop]));
  789. }
  790. }
  791. !propsWithInjection && (propsWithInjection = props);
  792. }
  793. else if (props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  794. if (!hasProp(prop, props)) {
  795. props.properties.unshift(prop);
  796. }
  797. propsWithInjection = props;
  798. }
  799. else {
  800. // single v-bind with expression, return a merged replacement
  801. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  802. createObjectExpression([prop]),
  803. props
  804. ]);
  805. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
  806. // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
  807. // the `guardReactiveProps` will no longer be needed
  808. if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
  809. parentCall = callPath[callPath.length - 2];
  810. }
  811. }
  812. if (node.type === 13 /* NodeTypes.VNODE_CALL */) {
  813. if (parentCall) {
  814. parentCall.arguments[0] = propsWithInjection;
  815. }
  816. else {
  817. node.props = propsWithInjection;
  818. }
  819. }
  820. else {
  821. if (parentCall) {
  822. parentCall.arguments[0] = propsWithInjection;
  823. }
  824. else {
  825. node.arguments[2] = propsWithInjection;
  826. }
  827. }
  828. }
  829. // check existing key to avoid overriding user provided keys
  830. function hasProp(prop, props) {
  831. let result = false;
  832. if (prop.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  833. const propKeyName = prop.key.content;
  834. result = props.properties.some(p => p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  835. p.key.content === propKeyName);
  836. }
  837. return result;
  838. }
  839. function toValidAssetId(name, type) {
  840. // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
  841. return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
  842. return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
  843. })}`;
  844. }
  845. // Check if a node contains expressions that reference current context scope ids
  846. function hasScopeRef(node, ids) {
  847. if (!node || Object.keys(ids).length === 0) {
  848. return false;
  849. }
  850. switch (node.type) {
  851. case 1 /* NodeTypes.ELEMENT */:
  852. for (let i = 0; i < node.props.length; i++) {
  853. const p = node.props[i];
  854. if (p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  855. (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {
  856. return true;
  857. }
  858. }
  859. return node.children.some(c => hasScopeRef(c, ids));
  860. case 11 /* NodeTypes.FOR */:
  861. if (hasScopeRef(node.source, ids)) {
  862. return true;
  863. }
  864. return node.children.some(c => hasScopeRef(c, ids));
  865. case 9 /* NodeTypes.IF */:
  866. return node.branches.some(b => hasScopeRef(b, ids));
  867. case 10 /* NodeTypes.IF_BRANCH */:
  868. if (hasScopeRef(node.condition, ids)) {
  869. return true;
  870. }
  871. return node.children.some(c => hasScopeRef(c, ids));
  872. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  873. return (!node.isStatic &&
  874. isSimpleIdentifier(node.content) &&
  875. !!ids[node.content]);
  876. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  877. return node.children.some(c => isObject(c) && hasScopeRef(c, ids));
  878. case 5 /* NodeTypes.INTERPOLATION */:
  879. case 12 /* NodeTypes.TEXT_CALL */:
  880. return hasScopeRef(node.content, ids);
  881. case 2 /* NodeTypes.TEXT */:
  882. case 3 /* NodeTypes.COMMENT */:
  883. return false;
  884. default:
  885. return false;
  886. }
  887. }
  888. function getMemoedVNodeCall(node) {
  889. if (node.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
  890. return node.arguments[1].returns;
  891. }
  892. else {
  893. return node;
  894. }
  895. }
  896. function makeBlock(node, { helper, removeHelper, inSSR }) {
  897. if (!node.isBlock) {
  898. node.isBlock = true;
  899. removeHelper(getVNodeHelper(inSSR, node.isComponent));
  900. helper(OPEN_BLOCK);
  901. helper(getVNodeBlockHelper(inSSR, node.isComponent));
  902. }
  903. }
  904. const deprecationData = {
  905. ["COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */]: {
  906. message: `Platform-native elements with "is" prop will no longer be ` +
  907. `treated as components in Vue 3 unless the "is" value is explicitly ` +
  908. `prefixed with "vue:".`,
  909. link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
  910. },
  911. ["COMPILER_V_BIND_SYNC" /* CompilerDeprecationTypes.COMPILER_V_BIND_SYNC */]: {
  912. message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
  913. `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
  914. `\`v-model:${key}\`.`,
  915. link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
  916. },
  917. ["COMPILER_V_BIND_PROP" /* CompilerDeprecationTypes.COMPILER_V_BIND_PROP */]: {
  918. message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
  919. `Vue 3 will automatically set a binding as DOM property when appropriate.`
  920. },
  921. ["COMPILER_V_BIND_OBJECT_ORDER" /* CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER */]: {
  922. message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
  923. `object spread: it will now overwrite an existing non-mergeable attribute ` +
  924. `that appears before v-bind in the case of conflict. ` +
  925. `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
  926. `You can also suppress this warning if the usage is intended.`,
  927. link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
  928. },
  929. ["COMPILER_V_ON_NATIVE" /* CompilerDeprecationTypes.COMPILER_V_ON_NATIVE */]: {
  930. message: `.native modifier for v-on has been removed as is no longer necessary.`,
  931. link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
  932. },
  933. ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* CompilerDeprecationTypes.COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
  934. message: `v-if / v-for precedence when used on the same element has changed ` +
  935. `in Vue 3: v-if now takes higher precedence and will no longer have ` +
  936. `access to v-for scope variables. It is best to avoid the ambiguity ` +
  937. `with <template> tags or use a computed property that filters v-for ` +
  938. `data source.`,
  939. link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
  940. },
  941. ["COMPILER_NATIVE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_NATIVE_TEMPLATE */]: {
  942. message: `<template> with no special directives will render as a native template ` +
  943. `element instead of its inner content in Vue 3.`
  944. },
  945. ["COMPILER_INLINE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_INLINE_TEMPLATE */]: {
  946. message: `"inline-template" has been removed in Vue 3.`,
  947. link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
  948. },
  949. ["COMPILER_FILTER" /* CompilerDeprecationTypes.COMPILER_FILTERS */]: {
  950. message: `filters have been removed in Vue 3. ` +
  951. `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
  952. `Use method calls or computed properties instead.`,
  953. link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
  954. }
  955. };
  956. function getCompatValue(key, context) {
  957. const config = context.options
  958. ? context.options.compatConfig
  959. : context.compatConfig;
  960. const value = config && config[key];
  961. if (key === 'MODE') {
  962. return value || 3; // compiler defaults to v3 behavior
  963. }
  964. else {
  965. return value;
  966. }
  967. }
  968. function isCompatEnabled(key, context) {
  969. const mode = getCompatValue('MODE', context);
  970. const value = getCompatValue(key, context);
  971. // in v3 mode, only enable if explicitly set to true
  972. // otherwise enable for any non-false value
  973. return mode === 3 ? value === true : value !== false;
  974. }
  975. function checkCompatEnabled(key, context, loc, ...args) {
  976. const enabled = isCompatEnabled(key, context);
  977. if (enabled) {
  978. warnDeprecation(key, context, loc, ...args);
  979. }
  980. return enabled;
  981. }
  982. function warnDeprecation(key, context, loc, ...args) {
  983. const val = getCompatValue(key, context);
  984. if (val === 'suppress-warning') {
  985. return;
  986. }
  987. const { message, link } = deprecationData[key];
  988. const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
  989. const err = new SyntaxError(msg);
  990. err.code = key;
  991. if (loc)
  992. err.loc = loc;
  993. context.onWarn(err);
  994. }
  995. // The default decoder only provides escapes for characters reserved as part of
  996. // the template syntax, and is only used if the custom renderer did not provide
  997. // a platform-specific decoder.
  998. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  999. const decodeMap = {
  1000. gt: '>',
  1001. lt: '<',
  1002. amp: '&',
  1003. apos: "'",
  1004. quot: '"'
  1005. };
  1006. const defaultParserOptions = {
  1007. delimiters: [`{{`, `}}`],
  1008. getNamespace: () => 0 /* Namespaces.HTML */,
  1009. getTextMode: () => 0 /* TextModes.DATA */,
  1010. isVoidTag: NO,
  1011. isPreTag: NO,
  1012. isCustomElement: NO,
  1013. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  1014. onError: defaultOnError,
  1015. onWarn: defaultOnWarn,
  1016. comments: true
  1017. };
  1018. function baseParse(content, options = {}) {
  1019. const context = createParserContext(content, options);
  1020. const start = getCursor(context);
  1021. return createRoot(parseChildren(context, 0 /* TextModes.DATA */, []), getSelection(context, start));
  1022. }
  1023. function createParserContext(content, rawOptions) {
  1024. const options = extend({}, defaultParserOptions);
  1025. let key;
  1026. for (key in rawOptions) {
  1027. // @ts-ignore
  1028. options[key] =
  1029. rawOptions[key] === undefined
  1030. ? defaultParserOptions[key]
  1031. : rawOptions[key];
  1032. }
  1033. return {
  1034. options,
  1035. column: 1,
  1036. line: 1,
  1037. offset: 0,
  1038. originalSource: content,
  1039. source: content,
  1040. inPre: false,
  1041. inVPre: false,
  1042. onWarn: options.onWarn
  1043. };
  1044. }
  1045. function parseChildren(context, mode, ancestors) {
  1046. const parent = last(ancestors);
  1047. const ns = parent ? parent.ns : 0 /* Namespaces.HTML */;
  1048. const nodes = [];
  1049. while (!isEnd(context, mode, ancestors)) {
  1050. const s = context.source;
  1051. let node = undefined;
  1052. if (mode === 0 /* TextModes.DATA */ || mode === 1 /* TextModes.RCDATA */) {
  1053. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  1054. // '{{'
  1055. node = parseInterpolation(context, mode);
  1056. }
  1057. else if (mode === 0 /* TextModes.DATA */ && s[0] === '<') {
  1058. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  1059. if (s.length === 1) {
  1060. emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 1);
  1061. }
  1062. else if (s[1] === '!') {
  1063. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  1064. if (startsWith(s, '<!--')) {
  1065. node = parseComment(context);
  1066. }
  1067. else if (startsWith(s, '<!DOCTYPE')) {
  1068. // Ignore DOCTYPE by a limitation.
  1069. node = parseBogusComment(context);
  1070. }
  1071. else if (startsWith(s, '<![CDATA[')) {
  1072. if (ns !== 0 /* Namespaces.HTML */) {
  1073. node = parseCDATA(context, ancestors);
  1074. }
  1075. else {
  1076. emitError(context, 1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */);
  1077. node = parseBogusComment(context);
  1078. }
  1079. }
  1080. else {
  1081. emitError(context, 11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */);
  1082. node = parseBogusComment(context);
  1083. }
  1084. }
  1085. else if (s[1] === '/') {
  1086. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  1087. if (s.length === 2) {
  1088. emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 2);
  1089. }
  1090. else if (s[2] === '>') {
  1091. emitError(context, 14 /* ErrorCodes.MISSING_END_TAG_NAME */, 2);
  1092. advanceBy(context, 3);
  1093. continue;
  1094. }
  1095. else if (/[a-z]/i.test(s[2])) {
  1096. emitError(context, 23 /* ErrorCodes.X_INVALID_END_TAG */);
  1097. parseTag(context, 1 /* TagType.End */, parent);
  1098. continue;
  1099. }
  1100. else {
  1101. emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  1102. node = parseBogusComment(context);
  1103. }
  1104. }
  1105. else if (/[a-z]/i.test(s[1])) {
  1106. node = parseElement(context, ancestors);
  1107. // 2.x <template> with no directive compat
  1108. if (isCompatEnabled("COMPILER_NATIVE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_NATIVE_TEMPLATE */, context) &&
  1109. node &&
  1110. node.tag === 'template' &&
  1111. !node.props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  1112. isSpecialTemplateDirective(p.name))) {
  1113. warnDeprecation("COMPILER_NATIVE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_NATIVE_TEMPLATE */, context, node.loc);
  1114. node = node.children;
  1115. }
  1116. }
  1117. else if (s[1] === '?') {
  1118. emitError(context, 21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  1119. node = parseBogusComment(context);
  1120. }
  1121. else {
  1122. emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  1123. }
  1124. }
  1125. }
  1126. if (!node) {
  1127. node = parseText(context, mode);
  1128. }
  1129. if (isArray(node)) {
  1130. for (let i = 0; i < node.length; i++) {
  1131. pushNode(nodes, node[i]);
  1132. }
  1133. }
  1134. else {
  1135. pushNode(nodes, node);
  1136. }
  1137. }
  1138. // Whitespace handling strategy like v2
  1139. let removedWhitespace = false;
  1140. if (mode !== 2 /* TextModes.RAWTEXT */ && mode !== 1 /* TextModes.RCDATA */) {
  1141. const shouldCondense = context.options.whitespace !== 'preserve';
  1142. for (let i = 0; i < nodes.length; i++) {
  1143. const node = nodes[i];
  1144. if (node.type === 2 /* NodeTypes.TEXT */) {
  1145. if (!context.inPre) {
  1146. if (!/[^\t\r\n\f ]/.test(node.content)) {
  1147. const prev = nodes[i - 1];
  1148. const next = nodes[i + 1];
  1149. // Remove if:
  1150. // - the whitespace is the first or last node, or:
  1151. // - (condense mode) the whitespace is between twos comments, or:
  1152. // - (condense mode) the whitespace is between comment and element, or:
  1153. // - (condense mode) the whitespace is between two elements AND contains newline
  1154. if (!prev ||
  1155. !next ||
  1156. (shouldCondense &&
  1157. ((prev.type === 3 /* NodeTypes.COMMENT */ &&
  1158. next.type === 3 /* NodeTypes.COMMENT */) ||
  1159. (prev.type === 3 /* NodeTypes.COMMENT */ &&
  1160. next.type === 1 /* NodeTypes.ELEMENT */) ||
  1161. (prev.type === 1 /* NodeTypes.ELEMENT */ &&
  1162. next.type === 3 /* NodeTypes.COMMENT */) ||
  1163. (prev.type === 1 /* NodeTypes.ELEMENT */ &&
  1164. next.type === 1 /* NodeTypes.ELEMENT */ &&
  1165. /[\r\n]/.test(node.content))))) {
  1166. removedWhitespace = true;
  1167. nodes[i] = null;
  1168. }
  1169. else {
  1170. // Otherwise, the whitespace is condensed into a single space
  1171. node.content = ' ';
  1172. }
  1173. }
  1174. else if (shouldCondense) {
  1175. // in condense mode, consecutive whitespaces in text are condensed
  1176. // down to a single space.
  1177. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  1178. }
  1179. }
  1180. else {
  1181. // #6410 normalize windows newlines in <pre>:
  1182. // in SSR, browsers normalize server-rendered \r\n into a single \n
  1183. // in the DOM
  1184. node.content = node.content.replace(/\r\n/g, '\n');
  1185. }
  1186. }
  1187. // Remove comment nodes if desired by configuration.
  1188. else if (node.type === 3 /* NodeTypes.COMMENT */ && !context.options.comments) {
  1189. removedWhitespace = true;
  1190. nodes[i] = null;
  1191. }
  1192. }
  1193. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  1194. // remove leading newline per html spec
  1195. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  1196. const first = nodes[0];
  1197. if (first && first.type === 2 /* NodeTypes.TEXT */) {
  1198. first.content = first.content.replace(/^\r?\n/, '');
  1199. }
  1200. }
  1201. }
  1202. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  1203. }
  1204. function pushNode(nodes, node) {
  1205. if (node.type === 2 /* NodeTypes.TEXT */) {
  1206. const prev = last(nodes);
  1207. // Merge if both this and the previous node are text and those are
  1208. // consecutive. This happens for cases like "a < b".
  1209. if (prev &&
  1210. prev.type === 2 /* NodeTypes.TEXT */ &&
  1211. prev.loc.end.offset === node.loc.start.offset) {
  1212. prev.content += node.content;
  1213. prev.loc.end = node.loc.end;
  1214. prev.loc.source += node.loc.source;
  1215. return;
  1216. }
  1217. }
  1218. nodes.push(node);
  1219. }
  1220. function parseCDATA(context, ancestors) {
  1221. advanceBy(context, 9);
  1222. const nodes = parseChildren(context, 3 /* TextModes.CDATA */, ancestors);
  1223. if (context.source.length === 0) {
  1224. emitError(context, 6 /* ErrorCodes.EOF_IN_CDATA */);
  1225. }
  1226. else {
  1227. advanceBy(context, 3);
  1228. }
  1229. return nodes;
  1230. }
  1231. function parseComment(context) {
  1232. const start = getCursor(context);
  1233. let content;
  1234. // Regular comment.
  1235. const match = /--(\!)?>/.exec(context.source);
  1236. if (!match) {
  1237. content = context.source.slice(4);
  1238. advanceBy(context, context.source.length);
  1239. emitError(context, 7 /* ErrorCodes.EOF_IN_COMMENT */);
  1240. }
  1241. else {
  1242. if (match.index <= 3) {
  1243. emitError(context, 0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  1244. }
  1245. if (match[1]) {
  1246. emitError(context, 10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */);
  1247. }
  1248. content = context.source.slice(4, match.index);
  1249. // Advancing with reporting nested comments.
  1250. const s = context.source.slice(0, match.index);
  1251. let prevIndex = 1, nestedIndex = 0;
  1252. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  1253. advanceBy(context, nestedIndex - prevIndex + 1);
  1254. if (nestedIndex + 4 < s.length) {
  1255. emitError(context, 16 /* ErrorCodes.NESTED_COMMENT */);
  1256. }
  1257. prevIndex = nestedIndex + 1;
  1258. }
  1259. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  1260. }
  1261. return {
  1262. type: 3 /* NodeTypes.COMMENT */,
  1263. content,
  1264. loc: getSelection(context, start)
  1265. };
  1266. }
  1267. function parseBogusComment(context) {
  1268. const start = getCursor(context);
  1269. const contentStart = context.source[1] === '?' ? 1 : 2;
  1270. let content;
  1271. const closeIndex = context.source.indexOf('>');
  1272. if (closeIndex === -1) {
  1273. content = context.source.slice(contentStart);
  1274. advanceBy(context, context.source.length);
  1275. }
  1276. else {
  1277. content = context.source.slice(contentStart, closeIndex);
  1278. advanceBy(context, closeIndex + 1);
  1279. }
  1280. return {
  1281. type: 3 /* NodeTypes.COMMENT */,
  1282. content,
  1283. loc: getSelection(context, start)
  1284. };
  1285. }
  1286. function parseElement(context, ancestors) {
  1287. // Start tag.
  1288. const wasInPre = context.inPre;
  1289. const wasInVPre = context.inVPre;
  1290. const parent = last(ancestors);
  1291. const element = parseTag(context, 0 /* TagType.Start */, parent);
  1292. const isPreBoundary = context.inPre && !wasInPre;
  1293. const isVPreBoundary = context.inVPre && !wasInVPre;
  1294. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  1295. // #4030 self-closing <pre> tag
  1296. if (isPreBoundary) {
  1297. context.inPre = false;
  1298. }
  1299. if (isVPreBoundary) {
  1300. context.inVPre = false;
  1301. }
  1302. return element;
  1303. }
  1304. // Children.
  1305. ancestors.push(element);
  1306. const mode = context.options.getTextMode(element, parent);
  1307. const children = parseChildren(context, mode, ancestors);
  1308. ancestors.pop();
  1309. // 2.x inline-template compat
  1310. {
  1311. const inlineTemplateProp = element.props.find(p => p.type === 6 /* NodeTypes.ATTRIBUTE */ && p.name === 'inline-template');
  1312. if (inlineTemplateProp &&
  1313. checkCompatEnabled("COMPILER_INLINE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_INLINE_TEMPLATE */, context, inlineTemplateProp.loc)) {
  1314. const loc = getSelection(context, element.loc.end);
  1315. inlineTemplateProp.value = {
  1316. type: 2 /* NodeTypes.TEXT */,
  1317. content: loc.source,
  1318. loc
  1319. };
  1320. }
  1321. }
  1322. element.children = children;
  1323. // End tag.
  1324. if (startsWithEndTagOpen(context.source, element.tag)) {
  1325. parseTag(context, 1 /* TagType.End */, parent);
  1326. }
  1327. else {
  1328. emitError(context, 24 /* ErrorCodes.X_MISSING_END_TAG */, 0, element.loc.start);
  1329. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  1330. const first = children[0];
  1331. if (first && startsWith(first.loc.source, '<!--')) {
  1332. emitError(context, 8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  1333. }
  1334. }
  1335. }
  1336. element.loc = getSelection(context, element.loc.start);
  1337. if (isPreBoundary) {
  1338. context.inPre = false;
  1339. }
  1340. if (isVPreBoundary) {
  1341. context.inVPre = false;
  1342. }
  1343. return element;
  1344. }
  1345. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  1346. function parseTag(context, type, parent) {
  1347. // Tag open.
  1348. const start = getCursor(context);
  1349. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  1350. const tag = match[1];
  1351. const ns = context.options.getNamespace(tag, parent);
  1352. advanceBy(context, match[0].length);
  1353. advanceSpaces(context);
  1354. // save current state in case we need to re-parse attributes with v-pre
  1355. const cursor = getCursor(context);
  1356. const currentSource = context.source;
  1357. // check <pre> tag
  1358. if (context.options.isPreTag(tag)) {
  1359. context.inPre = true;
  1360. }
  1361. // Attributes.
  1362. let props = parseAttributes(context, type);
  1363. // check v-pre
  1364. if (type === 0 /* TagType.Start */ &&
  1365. !context.inVPre &&
  1366. props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'pre')) {
  1367. context.inVPre = true;
  1368. // reset context
  1369. extend(context, cursor);
  1370. context.source = currentSource;
  1371. // re-parse attrs and filter out v-pre itself
  1372. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  1373. }
  1374. // Tag close.
  1375. let isSelfClosing = false;
  1376. if (context.source.length === 0) {
  1377. emitError(context, 9 /* ErrorCodes.EOF_IN_TAG */);
  1378. }
  1379. else {
  1380. isSelfClosing = startsWith(context.source, '/>');
  1381. if (type === 1 /* TagType.End */ && isSelfClosing) {
  1382. emitError(context, 4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */);
  1383. }
  1384. advanceBy(context, isSelfClosing ? 2 : 1);
  1385. }
  1386. if (type === 1 /* TagType.End */) {
  1387. return;
  1388. }
  1389. // 2.x deprecation checks
  1390. if (isCompatEnabled("COMPILER_V_IF_V_FOR_PRECEDENCE" /* CompilerDeprecationTypes.COMPILER_V_IF_V_FOR_PRECEDENCE */, context)) {
  1391. let hasIf = false;
  1392. let hasFor = false;
  1393. for (let i = 0; i < props.length; i++) {
  1394. const p = props[i];
  1395. if (p.type === 7 /* NodeTypes.DIRECTIVE */) {
  1396. if (p.name === 'if') {
  1397. hasIf = true;
  1398. }
  1399. else if (p.name === 'for') {
  1400. hasFor = true;
  1401. }
  1402. }
  1403. if (hasIf && hasFor) {
  1404. warnDeprecation("COMPILER_V_IF_V_FOR_PRECEDENCE" /* CompilerDeprecationTypes.COMPILER_V_IF_V_FOR_PRECEDENCE */, context, getSelection(context, start));
  1405. break;
  1406. }
  1407. }
  1408. }
  1409. let tagType = 0 /* ElementTypes.ELEMENT */;
  1410. if (!context.inVPre) {
  1411. if (tag === 'slot') {
  1412. tagType = 2 /* ElementTypes.SLOT */;
  1413. }
  1414. else if (tag === 'template') {
  1415. if (props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
  1416. tagType = 3 /* ElementTypes.TEMPLATE */;
  1417. }
  1418. }
  1419. else if (isComponent(tag, props, context)) {
  1420. tagType = 1 /* ElementTypes.COMPONENT */;
  1421. }
  1422. }
  1423. return {
  1424. type: 1 /* NodeTypes.ELEMENT */,
  1425. ns,
  1426. tag,
  1427. tagType,
  1428. props,
  1429. isSelfClosing,
  1430. children: [],
  1431. loc: getSelection(context, start),
  1432. codegenNode: undefined // to be created during transform phase
  1433. };
  1434. }
  1435. function isComponent(tag, props, context) {
  1436. const options = context.options;
  1437. if (options.isCustomElement(tag)) {
  1438. return false;
  1439. }
  1440. if (tag === 'component' ||
  1441. /^[A-Z]/.test(tag) ||
  1442. isCoreComponent(tag) ||
  1443. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  1444. (options.isNativeTag && !options.isNativeTag(tag))) {
  1445. return true;
  1446. }
  1447. // at this point the tag should be a native tag, but check for potential "is"
  1448. // casting
  1449. for (let i = 0; i < props.length; i++) {
  1450. const p = props[i];
  1451. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  1452. if (p.name === 'is' && p.value) {
  1453. if (p.value.content.startsWith('vue:')) {
  1454. return true;
  1455. }
  1456. else if (checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
  1457. return true;
  1458. }
  1459. }
  1460. }
  1461. else {
  1462. // directive
  1463. // v-is (TODO Deprecate)
  1464. if (p.name === 'is') {
  1465. return true;
  1466. }
  1467. else if (
  1468. // :is on plain element - only treat as component in compat mode
  1469. p.name === 'bind' &&
  1470. isStaticArgOf(p.arg, 'is') &&
  1471. true &&
  1472. checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
  1473. return true;
  1474. }
  1475. }
  1476. }
  1477. }
  1478. function parseAttributes(context, type) {
  1479. const props = [];
  1480. const attributeNames = new Set();
  1481. while (context.source.length > 0 &&
  1482. !startsWith(context.source, '>') &&
  1483. !startsWith(context.source, '/>')) {
  1484. if (startsWith(context.source, '/')) {
  1485. emitError(context, 22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */);
  1486. advanceBy(context, 1);
  1487. advanceSpaces(context);
  1488. continue;
  1489. }
  1490. if (type === 1 /* TagType.End */) {
  1491. emitError(context, 3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */);
  1492. }
  1493. const attr = parseAttribute(context, attributeNames);
  1494. // Trim whitespace between class
  1495. // https://github.com/vuejs/core/issues/4251
  1496. if (attr.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  1497. attr.value &&
  1498. attr.name === 'class') {
  1499. attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
  1500. }
  1501. if (type === 0 /* TagType.Start */) {
  1502. props.push(attr);
  1503. }
  1504. if (/^[^\t\r\n\f />]/.test(context.source)) {
  1505. emitError(context, 15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  1506. }
  1507. advanceSpaces(context);
  1508. }
  1509. return props;
  1510. }
  1511. function parseAttribute(context, nameSet) {
  1512. // Name.
  1513. const start = getCursor(context);
  1514. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  1515. const name = match[0];
  1516. if (nameSet.has(name)) {
  1517. emitError(context, 2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */);
  1518. }
  1519. nameSet.add(name);
  1520. if (name[0] === '=') {
  1521. emitError(context, 19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  1522. }
  1523. {
  1524. const pattern = /["'<]/g;
  1525. let m;
  1526. while ((m = pattern.exec(name))) {
  1527. emitError(context, 17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  1528. }
  1529. }
  1530. advanceBy(context, name.length);
  1531. // Value
  1532. let value = undefined;
  1533. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  1534. advanceSpaces(context);
  1535. advanceBy(context, 1);
  1536. advanceSpaces(context);
  1537. value = parseAttributeValue(context);
  1538. if (!value) {
  1539. emitError(context, 13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */);
  1540. }
  1541. }
  1542. const loc = getSelection(context, start);
  1543. if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
  1544. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  1545. let isPropShorthand = startsWith(name, '.');
  1546. let dirName = match[1] ||
  1547. (isPropShorthand || startsWith(name, ':')
  1548. ? 'bind'
  1549. : startsWith(name, '@')
  1550. ? 'on'
  1551. : 'slot');
  1552. let arg;
  1553. if (match[2]) {
  1554. const isSlot = dirName === 'slot';
  1555. const startOffset = name.lastIndexOf(match[2]);
  1556. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  1557. let content = match[2];
  1558. let isStatic = true;
  1559. if (content.startsWith('[')) {
  1560. isStatic = false;
  1561. if (!content.endsWith(']')) {
  1562. emitError(context, 27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  1563. content = content.slice(1);
  1564. }
  1565. else {
  1566. content = content.slice(1, content.length - 1);
  1567. }
  1568. }
  1569. else if (isSlot) {
  1570. // #1241 special case for v-slot: vuetify relies extensively on slot
  1571. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  1572. // supports such usage so we are keeping it consistent with 2.x.
  1573. content += match[3] || '';
  1574. }
  1575. arg = {
  1576. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  1577. content,
  1578. isStatic,
  1579. constType: isStatic
  1580. ? 3 /* ConstantTypes.CAN_STRINGIFY */
  1581. : 0 /* ConstantTypes.NOT_CONSTANT */,
  1582. loc
  1583. };
  1584. }
  1585. if (value && value.isQuoted) {
  1586. const valueLoc = value.loc;
  1587. valueLoc.start.offset++;
  1588. valueLoc.start.column++;
  1589. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  1590. valueLoc.source = valueLoc.source.slice(1, -1);
  1591. }
  1592. const modifiers = match[3] ? match[3].slice(1).split('.') : [];
  1593. if (isPropShorthand)
  1594. modifiers.push('prop');
  1595. // 2.x compat v-bind:foo.sync -> v-model:foo
  1596. if (dirName === 'bind' && arg) {
  1597. if (modifiers.includes('sync') &&
  1598. checkCompatEnabled("COMPILER_V_BIND_SYNC" /* CompilerDeprecationTypes.COMPILER_V_BIND_SYNC */, context, loc, arg.loc.source)) {
  1599. dirName = 'model';
  1600. modifiers.splice(modifiers.indexOf('sync'), 1);
  1601. }
  1602. if (modifiers.includes('prop')) {
  1603. checkCompatEnabled("COMPILER_V_BIND_PROP" /* CompilerDeprecationTypes.COMPILER_V_BIND_PROP */, context, loc);
  1604. }
  1605. }
  1606. return {
  1607. type: 7 /* NodeTypes.DIRECTIVE */,
  1608. name: dirName,
  1609. exp: value && {
  1610. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  1611. content: value.content,
  1612. isStatic: false,
  1613. // Treat as non-constant by default. This can be potentially set to
  1614. // other values by `transformExpression` to make it eligible for hoisting.
  1615. constType: 0 /* ConstantTypes.NOT_CONSTANT */,
  1616. loc: value.loc
  1617. },
  1618. arg,
  1619. modifiers,
  1620. loc
  1621. };
  1622. }
  1623. // missing directive name or illegal directive name
  1624. if (!context.inVPre && startsWith(name, 'v-')) {
  1625. emitError(context, 26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */);
  1626. }
  1627. return {
  1628. type: 6 /* NodeTypes.ATTRIBUTE */,
  1629. name,
  1630. value: value && {
  1631. type: 2 /* NodeTypes.TEXT */,
  1632. content: value.content,
  1633. loc: value.loc
  1634. },
  1635. loc
  1636. };
  1637. }
  1638. function parseAttributeValue(context) {
  1639. const start = getCursor(context);
  1640. let content;
  1641. const quote = context.source[0];
  1642. const isQuoted = quote === `"` || quote === `'`;
  1643. if (isQuoted) {
  1644. // Quoted value.
  1645. advanceBy(context, 1);
  1646. const endIndex = context.source.indexOf(quote);
  1647. if (endIndex === -1) {
  1648. content = parseTextData(context, context.source.length, 4 /* TextModes.ATTRIBUTE_VALUE */);
  1649. }
  1650. else {
  1651. content = parseTextData(context, endIndex, 4 /* TextModes.ATTRIBUTE_VALUE */);
  1652. advanceBy(context, 1);
  1653. }
  1654. }
  1655. else {
  1656. // Unquoted
  1657. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  1658. if (!match) {
  1659. return undefined;
  1660. }
  1661. const unexpectedChars = /["'<=`]/g;
  1662. let m;
  1663. while ((m = unexpectedChars.exec(match[0]))) {
  1664. emitError(context, 18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  1665. }
  1666. content = parseTextData(context, match[0].length, 4 /* TextModes.ATTRIBUTE_VALUE */);
  1667. }
  1668. return { content, isQuoted, loc: getSelection(context, start) };
  1669. }
  1670. function parseInterpolation(context, mode) {
  1671. const [open, close] = context.options.delimiters;
  1672. const closeIndex = context.source.indexOf(close, open.length);
  1673. if (closeIndex === -1) {
  1674. emitError(context, 25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */);
  1675. return undefined;
  1676. }
  1677. const start = getCursor(context);
  1678. advanceBy(context, open.length);
  1679. const innerStart = getCursor(context);
  1680. const innerEnd = getCursor(context);
  1681. const rawContentLength = closeIndex - open.length;
  1682. const rawContent = context.source.slice(0, rawContentLength);
  1683. const preTrimContent = parseTextData(context, rawContentLength, mode);
  1684. const content = preTrimContent.trim();
  1685. const startOffset = preTrimContent.indexOf(content);
  1686. if (startOffset > 0) {
  1687. advancePositionWithMutation(innerStart, rawContent, startOffset);
  1688. }
  1689. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  1690. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  1691. advanceBy(context, close.length);
  1692. return {
  1693. type: 5 /* NodeTypes.INTERPOLATION */,
  1694. content: {
  1695. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  1696. isStatic: false,
  1697. // Set `isConstant` to false by default and will decide in transformExpression
  1698. constType: 0 /* ConstantTypes.NOT_CONSTANT */,
  1699. content,
  1700. loc: getSelection(context, innerStart, innerEnd)
  1701. },
  1702. loc: getSelection(context, start)
  1703. };
  1704. }
  1705. function parseText(context, mode) {
  1706. const endTokens = mode === 3 /* TextModes.CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
  1707. let endIndex = context.source.length;
  1708. for (let i = 0; i < endTokens.length; i++) {
  1709. const index = context.source.indexOf(endTokens[i], 1);
  1710. if (index !== -1 && endIndex > index) {
  1711. endIndex = index;
  1712. }
  1713. }
  1714. const start = getCursor(context);
  1715. const content = parseTextData(context, endIndex, mode);
  1716. return {
  1717. type: 2 /* NodeTypes.TEXT */,
  1718. content,
  1719. loc: getSelection(context, start)
  1720. };
  1721. }
  1722. /**
  1723. * Get text data with a given length from the current location.
  1724. * This translates HTML entities in the text data.
  1725. */
  1726. function parseTextData(context, length, mode) {
  1727. const rawText = context.source.slice(0, length);
  1728. advanceBy(context, length);
  1729. if (mode === 2 /* TextModes.RAWTEXT */ ||
  1730. mode === 3 /* TextModes.CDATA */ ||
  1731. !rawText.includes('&')) {
  1732. return rawText;
  1733. }
  1734. else {
  1735. // DATA or RCDATA containing "&"". Entity decoding required.
  1736. return context.options.decodeEntities(rawText, mode === 4 /* TextModes.ATTRIBUTE_VALUE */);
  1737. }
  1738. }
  1739. function getCursor(context) {
  1740. const { column, line, offset } = context;
  1741. return { column, line, offset };
  1742. }
  1743. function getSelection(context, start, end) {
  1744. end = end || getCursor(context);
  1745. return {
  1746. start,
  1747. end,
  1748. source: context.originalSource.slice(start.offset, end.offset)
  1749. };
  1750. }
  1751. function last(xs) {
  1752. return xs[xs.length - 1];
  1753. }
  1754. function startsWith(source, searchString) {
  1755. return source.startsWith(searchString);
  1756. }
  1757. function advanceBy(context, numberOfCharacters) {
  1758. const { source } = context;
  1759. advancePositionWithMutation(context, source, numberOfCharacters);
  1760. context.source = source.slice(numberOfCharacters);
  1761. }
  1762. function advanceSpaces(context) {
  1763. const match = /^[\t\r\n\f ]+/.exec(context.source);
  1764. if (match) {
  1765. advanceBy(context, match[0].length);
  1766. }
  1767. }
  1768. function getNewPosition(context, start, numberOfCharacters) {
  1769. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  1770. }
  1771. function emitError(context, code, offset, loc = getCursor(context)) {
  1772. if (offset) {
  1773. loc.offset += offset;
  1774. loc.column += offset;
  1775. }
  1776. context.options.onError(createCompilerError(code, {
  1777. start: loc,
  1778. end: loc,
  1779. source: ''
  1780. }));
  1781. }
  1782. function isEnd(context, mode, ancestors) {
  1783. const s = context.source;
  1784. switch (mode) {
  1785. case 0 /* TextModes.DATA */:
  1786. if (startsWith(s, '</')) {
  1787. // TODO: probably bad performance
  1788. for (let i = ancestors.length - 1; i >= 0; --i) {
  1789. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  1790. return true;
  1791. }
  1792. }
  1793. }
  1794. break;
  1795. case 1 /* TextModes.RCDATA */:
  1796. case 2 /* TextModes.RAWTEXT */: {
  1797. const parent = last(ancestors);
  1798. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  1799. return true;
  1800. }
  1801. break;
  1802. }
  1803. case 3 /* TextModes.CDATA */:
  1804. if (startsWith(s, ']]>')) {
  1805. return true;
  1806. }
  1807. break;
  1808. }
  1809. return !s;
  1810. }
  1811. function startsWithEndTagOpen(source, tag) {
  1812. return (startsWith(source, '</') &&
  1813. source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
  1814. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  1815. }
  1816. function hoistStatic(root, context) {
  1817. walk(root, context,
  1818. // Root node is unfortunately non-hoistable due to potential parent
  1819. // fallthrough attributes.
  1820. isSingleElementRoot(root, root.children[0]));
  1821. }
  1822. function isSingleElementRoot(root, child) {
  1823. const { children } = root;
  1824. return (children.length === 1 &&
  1825. child.type === 1 /* NodeTypes.ELEMENT */ &&
  1826. !isSlotOutlet(child));
  1827. }
  1828. function walk(node, context, doNotHoistNode = false) {
  1829. const { children } = node;
  1830. const originalCount = children.length;
  1831. let hoistedCount = 0;
  1832. for (let i = 0; i < children.length; i++) {
  1833. const child = children[i];
  1834. // only plain elements & text calls are eligible for hoisting.
  1835. if (child.type === 1 /* NodeTypes.ELEMENT */ &&
  1836. child.tagType === 0 /* ElementTypes.ELEMENT */) {
  1837. const constantType = doNotHoistNode
  1838. ? 0 /* ConstantTypes.NOT_CONSTANT */
  1839. : getConstantType(child, context);
  1840. if (constantType > 0 /* ConstantTypes.NOT_CONSTANT */) {
  1841. if (constantType >= 2 /* ConstantTypes.CAN_HOIST */) {
  1842. child.codegenNode.patchFlag =
  1843. -1 /* PatchFlags.HOISTED */ + (` /* HOISTED */` );
  1844. child.codegenNode = context.hoist(child.codegenNode);
  1845. hoistedCount++;
  1846. continue;
  1847. }
  1848. }
  1849. else {
  1850. // node may contain dynamic children, but its props may be eligible for
  1851. // hoisting.
  1852. const codegenNode = child.codegenNode;
  1853. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  1854. const flag = getPatchFlag(codegenNode);
  1855. if ((!flag ||
  1856. flag === 512 /* PatchFlags.NEED_PATCH */ ||
  1857. flag === 1 /* PatchFlags.TEXT */) &&
  1858. getGeneratedPropsConstantType(child, context) >=
  1859. 2 /* ConstantTypes.CAN_HOIST */) {
  1860. const props = getNodeProps(child);
  1861. if (props) {
  1862. codegenNode.props = context.hoist(props);
  1863. }
  1864. }
  1865. if (codegenNode.dynamicProps) {
  1866. codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
  1867. }
  1868. }
  1869. }
  1870. }
  1871. // walk further
  1872. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  1873. const isComponent = child.tagType === 1 /* ElementTypes.COMPONENT */;
  1874. if (isComponent) {
  1875. context.scopes.vSlot++;
  1876. }
  1877. walk(child, context);
  1878. if (isComponent) {
  1879. context.scopes.vSlot--;
  1880. }
  1881. }
  1882. else if (child.type === 11 /* NodeTypes.FOR */) {
  1883. // Do not hoist v-for single child because it has to be a block
  1884. walk(child, context, child.children.length === 1);
  1885. }
  1886. else if (child.type === 9 /* NodeTypes.IF */) {
  1887. for (let i = 0; i < child.branches.length; i++) {
  1888. // Do not hoist v-if single child because it has to be a block
  1889. walk(child.branches[i], context, child.branches[i].children.length === 1);
  1890. }
  1891. }
  1892. }
  1893. if (hoistedCount && context.transformHoist) {
  1894. context.transformHoist(children, context, node);
  1895. }
  1896. // all children were hoisted - the entire children array is hoistable.
  1897. if (hoistedCount &&
  1898. hoistedCount === originalCount &&
  1899. node.type === 1 /* NodeTypes.ELEMENT */ &&
  1900. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  1901. node.codegenNode &&
  1902. node.codegenNode.type === 13 /* NodeTypes.VNODE_CALL */ &&
  1903. isArray(node.codegenNode.children)) {
  1904. node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
  1905. }
  1906. }
  1907. function getConstantType(node, context) {
  1908. const { constantCache } = context;
  1909. switch (node.type) {
  1910. case 1 /* NodeTypes.ELEMENT */:
  1911. if (node.tagType !== 0 /* ElementTypes.ELEMENT */) {
  1912. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1913. }
  1914. const cached = constantCache.get(node);
  1915. if (cached !== undefined) {
  1916. return cached;
  1917. }
  1918. const codegenNode = node.codegenNode;
  1919. if (codegenNode.type !== 13 /* NodeTypes.VNODE_CALL */) {
  1920. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1921. }
  1922. if (codegenNode.isBlock &&
  1923. node.tag !== 'svg' &&
  1924. node.tag !== 'foreignObject') {
  1925. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1926. }
  1927. const flag = getPatchFlag(codegenNode);
  1928. if (!flag) {
  1929. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  1930. // Element itself has no patch flag. However we still need to check:
  1931. // 1. Even for a node with no patch flag, it is possible for it to contain
  1932. // non-hoistable expressions that refers to scope variables, e.g. compiler
  1933. // injected keys or cached event handlers. Therefore we need to always
  1934. // check the codegenNode's props to be sure.
  1935. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  1936. if (generatedPropsType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  1937. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  1938. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1939. }
  1940. if (generatedPropsType < returnType) {
  1941. returnType = generatedPropsType;
  1942. }
  1943. // 2. its children.
  1944. for (let i = 0; i < node.children.length; i++) {
  1945. const childType = getConstantType(node.children[i], context);
  1946. if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  1947. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  1948. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1949. }
  1950. if (childType < returnType) {
  1951. returnType = childType;
  1952. }
  1953. }
  1954. // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
  1955. // type, check if any of the props can cause the type to be lowered
  1956. // we can skip can_patch because it's guaranteed by the absence of a
  1957. // patchFlag.
  1958. if (returnType > 1 /* ConstantTypes.CAN_SKIP_PATCH */) {
  1959. for (let i = 0; i < node.props.length; i++) {
  1960. const p = node.props[i];
  1961. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'bind' && p.exp) {
  1962. const expType = getConstantType(p.exp, context);
  1963. if (expType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  1964. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  1965. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1966. }
  1967. if (expType < returnType) {
  1968. returnType = expType;
  1969. }
  1970. }
  1971. }
  1972. }
  1973. // only svg/foreignObject could be block here, however if they are
  1974. // static then they don't need to be blocks since there will be no
  1975. // nested updates.
  1976. if (codegenNode.isBlock) {
  1977. // except set custom directives.
  1978. for (let i = 0; i < node.props.length; i++) {
  1979. const p = node.props[i];
  1980. if (p.type === 7 /* NodeTypes.DIRECTIVE */) {
  1981. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  1982. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1983. }
  1984. }
  1985. context.removeHelper(OPEN_BLOCK);
  1986. context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
  1987. codegenNode.isBlock = false;
  1988. context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
  1989. }
  1990. constantCache.set(node, returnType);
  1991. return returnType;
  1992. }
  1993. else {
  1994. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  1995. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1996. }
  1997. case 2 /* NodeTypes.TEXT */:
  1998. case 3 /* NodeTypes.COMMENT */:
  1999. return 3 /* ConstantTypes.CAN_STRINGIFY */;
  2000. case 9 /* NodeTypes.IF */:
  2001. case 11 /* NodeTypes.FOR */:
  2002. case 10 /* NodeTypes.IF_BRANCH */:
  2003. return 0 /* ConstantTypes.NOT_CONSTANT */;
  2004. case 5 /* NodeTypes.INTERPOLATION */:
  2005. case 12 /* NodeTypes.TEXT_CALL */:
  2006. return getConstantType(node.content, context);
  2007. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  2008. return node.constType;
  2009. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  2010. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  2011. for (let i = 0; i < node.children.length; i++) {
  2012. const child = node.children[i];
  2013. if (isString(child) || isSymbol(child)) {
  2014. continue;
  2015. }
  2016. const childType = getConstantType(child, context);
  2017. if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  2018. return 0 /* ConstantTypes.NOT_CONSTANT */;
  2019. }
  2020. else if (childType < returnType) {
  2021. returnType = childType;
  2022. }
  2023. }
  2024. return returnType;
  2025. default:
  2026. return 0 /* ConstantTypes.NOT_CONSTANT */;
  2027. }
  2028. }
  2029. const allowHoistedHelperSet = new Set([
  2030. NORMALIZE_CLASS,
  2031. NORMALIZE_STYLE,
  2032. NORMALIZE_PROPS,
  2033. GUARD_REACTIVE_PROPS
  2034. ]);
  2035. function getConstantTypeOfHelperCall(value, context) {
  2036. if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ &&
  2037. !isString(value.callee) &&
  2038. allowHoistedHelperSet.has(value.callee)) {
  2039. const arg = value.arguments[0];
  2040. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  2041. return getConstantType(arg, context);
  2042. }
  2043. else if (arg.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  2044. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
  2045. return getConstantTypeOfHelperCall(arg, context);
  2046. }
  2047. }
  2048. return 0 /* ConstantTypes.NOT_CONSTANT */;
  2049. }
  2050. function getGeneratedPropsConstantType(node, context) {
  2051. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  2052. const props = getNodeProps(node);
  2053. if (props && props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  2054. const { properties } = props;
  2055. for (let i = 0; i < properties.length; i++) {
  2056. const { key, value } = properties[i];
  2057. const keyType = getConstantType(key, context);
  2058. if (keyType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  2059. return keyType;
  2060. }
  2061. if (keyType < returnType) {
  2062. returnType = keyType;
  2063. }
  2064. let valueType;
  2065. if (value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  2066. valueType = getConstantType(value, context);
  2067. }
  2068. else if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  2069. // some helper calls can be hoisted,
  2070. // such as the `normalizeProps` generated by the compiler for pre-normalize class,
  2071. // in this case we need to respect the ConstantType of the helper's arguments
  2072. valueType = getConstantTypeOfHelperCall(value, context);
  2073. }
  2074. else {
  2075. valueType = 0 /* ConstantTypes.NOT_CONSTANT */;
  2076. }
  2077. if (valueType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  2078. return valueType;
  2079. }
  2080. if (valueType < returnType) {
  2081. returnType = valueType;
  2082. }
  2083. }
  2084. }
  2085. return returnType;
  2086. }
  2087. function getNodeProps(node) {
  2088. const codegenNode = node.codegenNode;
  2089. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  2090. return codegenNode.props;
  2091. }
  2092. }
  2093. function getPatchFlag(node) {
  2094. const flag = node.patchFlag;
  2095. return flag ? parseInt(flag, 10) : undefined;
  2096. }
  2097. function createTransformContext(root, { filename = '', prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = NOOP, isCustomElement = NOOP, expressionPlugins = [], scopeId = null, slotted = true, ssr = false, inSSR = false, ssrCssVars = ``, bindingMetadata = EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError, onWarn = defaultOnWarn, compatConfig }) {
  2098. const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
  2099. const context = {
  2100. // options
  2101. selfName: nameMatch && capitalize(camelize(nameMatch[1])),
  2102. prefixIdentifiers,
  2103. hoistStatic,
  2104. cacheHandlers,
  2105. nodeTransforms,
  2106. directiveTransforms,
  2107. transformHoist,
  2108. isBuiltInComponent,
  2109. isCustomElement,
  2110. expressionPlugins,
  2111. scopeId,
  2112. slotted,
  2113. ssr,
  2114. inSSR,
  2115. ssrCssVars,
  2116. bindingMetadata,
  2117. inline,
  2118. isTS,
  2119. onError,
  2120. onWarn,
  2121. compatConfig,
  2122. // state
  2123. root,
  2124. helpers: new Map(),
  2125. components: new Set(),
  2126. directives: new Set(),
  2127. hoists: [],
  2128. imports: [],
  2129. constantCache: new Map(),
  2130. temps: 0,
  2131. cached: 0,
  2132. identifiers: Object.create(null),
  2133. scopes: {
  2134. vFor: 0,
  2135. vSlot: 0,
  2136. vPre: 0,
  2137. vOnce: 0
  2138. },
  2139. parent: null,
  2140. currentNode: root,
  2141. childIndex: 0,
  2142. inVOnce: false,
  2143. // methods
  2144. helper(name) {
  2145. const count = context.helpers.get(name) || 0;
  2146. context.helpers.set(name, count + 1);
  2147. return name;
  2148. },
  2149. removeHelper(name) {
  2150. const count = context.helpers.get(name);
  2151. if (count) {
  2152. const currentCount = count - 1;
  2153. if (!currentCount) {
  2154. context.helpers.delete(name);
  2155. }
  2156. else {
  2157. context.helpers.set(name, currentCount);
  2158. }
  2159. }
  2160. },
  2161. helperString(name) {
  2162. return `_${helperNameMap[context.helper(name)]}`;
  2163. },
  2164. replaceNode(node) {
  2165. /* istanbul ignore if */
  2166. {
  2167. if (!context.currentNode) {
  2168. throw new Error(`Node being replaced is already removed.`);
  2169. }
  2170. if (!context.parent) {
  2171. throw new Error(`Cannot replace root node.`);
  2172. }
  2173. }
  2174. context.parent.children[context.childIndex] = context.currentNode = node;
  2175. },
  2176. removeNode(node) {
  2177. if (!context.parent) {
  2178. throw new Error(`Cannot remove root node.`);
  2179. }
  2180. const list = context.parent.children;
  2181. const removalIndex = node
  2182. ? list.indexOf(node)
  2183. : context.currentNode
  2184. ? context.childIndex
  2185. : -1;
  2186. /* istanbul ignore if */
  2187. if (removalIndex < 0) {
  2188. throw new Error(`node being removed is not a child of current parent`);
  2189. }
  2190. if (!node || node === context.currentNode) {
  2191. // current node removed
  2192. context.currentNode = null;
  2193. context.onNodeRemoved();
  2194. }
  2195. else {
  2196. // sibling node removed
  2197. if (context.childIndex > removalIndex) {
  2198. context.childIndex--;
  2199. context.onNodeRemoved();
  2200. }
  2201. }
  2202. context.parent.children.splice(removalIndex, 1);
  2203. },
  2204. onNodeRemoved: () => { },
  2205. addIdentifiers(exp) {
  2206. },
  2207. removeIdentifiers(exp) {
  2208. },
  2209. hoist(exp) {
  2210. if (isString(exp))
  2211. exp = createSimpleExpression(exp);
  2212. context.hoists.push(exp);
  2213. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* ConstantTypes.CAN_HOIST */);
  2214. identifier.hoisted = exp;
  2215. return identifier;
  2216. },
  2217. cache(exp, isVNode = false) {
  2218. return createCacheExpression(context.cached++, exp, isVNode);
  2219. }
  2220. };
  2221. {
  2222. context.filters = new Set();
  2223. }
  2224. return context;
  2225. }
  2226. function transform(root, options) {
  2227. const context = createTransformContext(root, options);
  2228. traverseNode(root, context);
  2229. if (options.hoistStatic) {
  2230. hoistStatic(root, context);
  2231. }
  2232. if (!options.ssr) {
  2233. createRootCodegen(root, context);
  2234. }
  2235. // finalize meta information
  2236. root.helpers = [...context.helpers.keys()];
  2237. root.components = [...context.components];
  2238. root.directives = [...context.directives];
  2239. root.imports = context.imports;
  2240. root.hoists = context.hoists;
  2241. root.temps = context.temps;
  2242. root.cached = context.cached;
  2243. {
  2244. root.filters = [...context.filters];
  2245. }
  2246. }
  2247. function createRootCodegen(root, context) {
  2248. const { helper } = context;
  2249. const { children } = root;
  2250. if (children.length === 1) {
  2251. const child = children[0];
  2252. // if the single child is an element, turn it into a block.
  2253. if (isSingleElementRoot(root, child) && child.codegenNode) {
  2254. // single element root is never hoisted so codegenNode will never be
  2255. // SimpleExpressionNode
  2256. const codegenNode = child.codegenNode;
  2257. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  2258. makeBlock(codegenNode, context);
  2259. }
  2260. root.codegenNode = codegenNode;
  2261. }
  2262. else {
  2263. // - single <slot/>, IfNode, ForNode: already blocks.
  2264. // - single text node: always patched.
  2265. // root codegen falls through via genNode()
  2266. root.codegenNode = child;
  2267. }
  2268. }
  2269. else if (children.length > 1) {
  2270. // root has multiple nodes - return a fragment block.
  2271. let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
  2272. let patchFlagText = PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
  2273. // check if the fragment actually contains a single valid child with
  2274. // the rest being comments
  2275. if (children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
  2276. patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
  2277. patchFlagText += `, ${PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
  2278. }
  2279. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
  2280. }
  2281. else ;
  2282. }
  2283. function traverseChildren(parent, context) {
  2284. let i = 0;
  2285. const nodeRemoved = () => {
  2286. i--;
  2287. };
  2288. for (; i < parent.children.length; i++) {
  2289. const child = parent.children[i];
  2290. if (isString(child))
  2291. continue;
  2292. context.parent = parent;
  2293. context.childIndex = i;
  2294. context.onNodeRemoved = nodeRemoved;
  2295. traverseNode(child, context);
  2296. }
  2297. }
  2298. function traverseNode(node, context) {
  2299. context.currentNode = node;
  2300. // apply transform plugins
  2301. const { nodeTransforms } = context;
  2302. const exitFns = [];
  2303. for (let i = 0; i < nodeTransforms.length; i++) {
  2304. const onExit = nodeTransforms[i](node, context);
  2305. if (onExit) {
  2306. if (isArray(onExit)) {
  2307. exitFns.push(...onExit);
  2308. }
  2309. else {
  2310. exitFns.push(onExit);
  2311. }
  2312. }
  2313. if (!context.currentNode) {
  2314. // node was removed
  2315. return;
  2316. }
  2317. else {
  2318. // node may have been replaced
  2319. node = context.currentNode;
  2320. }
  2321. }
  2322. switch (node.type) {
  2323. case 3 /* NodeTypes.COMMENT */:
  2324. if (!context.ssr) {
  2325. // inject import for the Comment symbol, which is needed for creating
  2326. // comment nodes with `createVNode`
  2327. context.helper(CREATE_COMMENT);
  2328. }
  2329. break;
  2330. case 5 /* NodeTypes.INTERPOLATION */:
  2331. // no need to traverse, but we need to inject toString helper
  2332. if (!context.ssr) {
  2333. context.helper(TO_DISPLAY_STRING);
  2334. }
  2335. break;
  2336. // for container types, further traverse downwards
  2337. case 9 /* NodeTypes.IF */:
  2338. for (let i = 0; i < node.branches.length; i++) {
  2339. traverseNode(node.branches[i], context);
  2340. }
  2341. break;
  2342. case 10 /* NodeTypes.IF_BRANCH */:
  2343. case 11 /* NodeTypes.FOR */:
  2344. case 1 /* NodeTypes.ELEMENT */:
  2345. case 0 /* NodeTypes.ROOT */:
  2346. traverseChildren(node, context);
  2347. break;
  2348. }
  2349. // exit transforms
  2350. context.currentNode = node;
  2351. let i = exitFns.length;
  2352. while (i--) {
  2353. exitFns[i]();
  2354. }
  2355. }
  2356. function createStructuralDirectiveTransform(name, fn) {
  2357. const matches = isString(name)
  2358. ? (n) => n === name
  2359. : (n) => name.test(n);
  2360. return (node, context) => {
  2361. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  2362. const { props } = node;
  2363. // structural directive transforms are not concerned with slots
  2364. // as they are handled separately in vSlot.ts
  2365. if (node.tagType === 3 /* ElementTypes.TEMPLATE */ && props.some(isVSlot)) {
  2366. return;
  2367. }
  2368. const exitFns = [];
  2369. for (let i = 0; i < props.length; i++) {
  2370. const prop = props[i];
  2371. if (prop.type === 7 /* NodeTypes.DIRECTIVE */ && matches(prop.name)) {
  2372. // structural directives are removed to avoid infinite recursion
  2373. // also we remove them *before* applying so that it can further
  2374. // traverse itself in case it moves the node around
  2375. props.splice(i, 1);
  2376. i--;
  2377. const onExit = fn(node, prop, context);
  2378. if (onExit)
  2379. exitFns.push(onExit);
  2380. }
  2381. }
  2382. return exitFns;
  2383. }
  2384. };
  2385. }
  2386. const PURE_ANNOTATION = `/*#__PURE__*/`;
  2387. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  2388. function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssrRuntimeModuleName = 'vue/server-renderer', ssr = false, isTS = false, inSSR = false }) {
  2389. const context = {
  2390. mode,
  2391. prefixIdentifiers,
  2392. sourceMap,
  2393. filename,
  2394. scopeId,
  2395. optimizeImports,
  2396. runtimeGlobalName,
  2397. runtimeModuleName,
  2398. ssrRuntimeModuleName,
  2399. ssr,
  2400. isTS,
  2401. inSSR,
  2402. source: ast.loc.source,
  2403. code: ``,
  2404. column: 1,
  2405. line: 1,
  2406. offset: 0,
  2407. indentLevel: 0,
  2408. pure: false,
  2409. map: undefined,
  2410. helper(key) {
  2411. return `_${helperNameMap[key]}`;
  2412. },
  2413. push(code, node) {
  2414. context.code += code;
  2415. },
  2416. indent() {
  2417. newline(++context.indentLevel);
  2418. },
  2419. deindent(withoutNewLine = false) {
  2420. if (withoutNewLine) {
  2421. --context.indentLevel;
  2422. }
  2423. else {
  2424. newline(--context.indentLevel);
  2425. }
  2426. },
  2427. newline() {
  2428. newline(context.indentLevel);
  2429. }
  2430. };
  2431. function newline(n) {
  2432. context.push('\n' + ` `.repeat(n));
  2433. }
  2434. return context;
  2435. }
  2436. function generate(ast, options = {}) {
  2437. const context = createCodegenContext(ast, options);
  2438. if (options.onContextCreated)
  2439. options.onContextCreated(context);
  2440. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  2441. const hasHelpers = ast.helpers.length > 0;
  2442. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  2443. // preambles
  2444. // in setup() inline mode, the preamble is generated in a sub context
  2445. // and returned separately.
  2446. const preambleContext = context;
  2447. {
  2448. genFunctionPreamble(ast, preambleContext);
  2449. }
  2450. // enter render function
  2451. const functionName = ssr ? `ssrRender` : `render`;
  2452. const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
  2453. const signature = args.join(', ');
  2454. {
  2455. push(`function ${functionName}(${signature}) {`);
  2456. }
  2457. indent();
  2458. if (useWithBlock) {
  2459. push(`with (_ctx) {`);
  2460. indent();
  2461. // function mode const declarations should be inside with block
  2462. // also they should be renamed to avoid collision with user properties
  2463. if (hasHelpers) {
  2464. push(`const { ${ast.helpers.map(aliasHelper).join(', ')} } = _Vue`);
  2465. push(`\n`);
  2466. newline();
  2467. }
  2468. }
  2469. // generate asset resolution statements
  2470. if (ast.components.length) {
  2471. genAssets(ast.components, 'component', context);
  2472. if (ast.directives.length || ast.temps > 0) {
  2473. newline();
  2474. }
  2475. }
  2476. if (ast.directives.length) {
  2477. genAssets(ast.directives, 'directive', context);
  2478. if (ast.temps > 0) {
  2479. newline();
  2480. }
  2481. }
  2482. if (ast.filters && ast.filters.length) {
  2483. newline();
  2484. genAssets(ast.filters, 'filter', context);
  2485. newline();
  2486. }
  2487. if (ast.temps > 0) {
  2488. push(`let `);
  2489. for (let i = 0; i < ast.temps; i++) {
  2490. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  2491. }
  2492. }
  2493. if (ast.components.length || ast.directives.length || ast.temps) {
  2494. push(`\n`);
  2495. newline();
  2496. }
  2497. // generate the VNode tree expression
  2498. if (!ssr) {
  2499. push(`return `);
  2500. }
  2501. if (ast.codegenNode) {
  2502. genNode(ast.codegenNode, context);
  2503. }
  2504. else {
  2505. push(`null`);
  2506. }
  2507. if (useWithBlock) {
  2508. deindent();
  2509. push(`}`);
  2510. }
  2511. deindent();
  2512. push(`}`);
  2513. return {
  2514. ast,
  2515. code: context.code,
  2516. preamble: ``,
  2517. // SourceMapGenerator does have toJSON() method but it's not in the types
  2518. map: context.map ? context.map.toJSON() : undefined
  2519. };
  2520. }
  2521. function genFunctionPreamble(ast, context) {
  2522. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
  2523. const VueBinding = runtimeGlobalName;
  2524. // Generate const declaration for helpers
  2525. // In prefix mode, we place the const declaration at top so it's done
  2526. // only once; But if we not prefixing, we place the declaration inside the
  2527. // with block so it doesn't incur the `in` check cost for every helper access.
  2528. if (ast.helpers.length > 0) {
  2529. {
  2530. // "with" mode.
  2531. // save Vue in a separate variable to avoid collision
  2532. push(`const _Vue = ${VueBinding}\n`);
  2533. // in "with" mode, helpers are declared inside the with block to avoid
  2534. // has check cost, but hoists are lifted out of the function - we need
  2535. // to provide the helper here.
  2536. if (ast.hoists.length) {
  2537. const staticHelpers = [
  2538. CREATE_VNODE,
  2539. CREATE_ELEMENT_VNODE,
  2540. CREATE_COMMENT,
  2541. CREATE_TEXT,
  2542. CREATE_STATIC
  2543. ]
  2544. .filter(helper => ast.helpers.includes(helper))
  2545. .map(aliasHelper)
  2546. .join(', ');
  2547. push(`const { ${staticHelpers} } = _Vue\n`);
  2548. }
  2549. }
  2550. }
  2551. genHoists(ast.hoists, context);
  2552. newline();
  2553. push(`return `);
  2554. }
  2555. function genAssets(assets, type, { helper, push, newline, isTS }) {
  2556. const resolver = helper(type === 'filter'
  2557. ? RESOLVE_FILTER
  2558. : type === 'component'
  2559. ? RESOLVE_COMPONENT
  2560. : RESOLVE_DIRECTIVE);
  2561. for (let i = 0; i < assets.length; i++) {
  2562. let id = assets[i];
  2563. // potential component implicit self-reference inferred from SFC filename
  2564. const maybeSelfReference = id.endsWith('__self');
  2565. if (maybeSelfReference) {
  2566. id = id.slice(0, -6);
  2567. }
  2568. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
  2569. if (i < assets.length - 1) {
  2570. newline();
  2571. }
  2572. }
  2573. }
  2574. function genHoists(hoists, context) {
  2575. if (!hoists.length) {
  2576. return;
  2577. }
  2578. context.pure = true;
  2579. const { push, newline, helper, scopeId, mode } = context;
  2580. newline();
  2581. for (let i = 0; i < hoists.length; i++) {
  2582. const exp = hoists[i];
  2583. if (exp) {
  2584. push(`const _hoisted_${i + 1} = ${``}`);
  2585. genNode(exp, context);
  2586. newline();
  2587. }
  2588. }
  2589. context.pure = false;
  2590. }
  2591. function isText$1(n) {
  2592. return (isString(n) ||
  2593. n.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  2594. n.type === 2 /* NodeTypes.TEXT */ ||
  2595. n.type === 5 /* NodeTypes.INTERPOLATION */ ||
  2596. n.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */);
  2597. }
  2598. function genNodeListAsArray(nodes, context) {
  2599. const multilines = nodes.length > 3 ||
  2600. (nodes.some(n => isArray(n) || !isText$1(n)));
  2601. context.push(`[`);
  2602. multilines && context.indent();
  2603. genNodeList(nodes, context, multilines);
  2604. multilines && context.deindent();
  2605. context.push(`]`);
  2606. }
  2607. function genNodeList(nodes, context, multilines = false, comma = true) {
  2608. const { push, newline } = context;
  2609. for (let i = 0; i < nodes.length; i++) {
  2610. const node = nodes[i];
  2611. if (isString(node)) {
  2612. push(node);
  2613. }
  2614. else if (isArray(node)) {
  2615. genNodeListAsArray(node, context);
  2616. }
  2617. else {
  2618. genNode(node, context);
  2619. }
  2620. if (i < nodes.length - 1) {
  2621. if (multilines) {
  2622. comma && push(',');
  2623. newline();
  2624. }
  2625. else {
  2626. comma && push(', ');
  2627. }
  2628. }
  2629. }
  2630. }
  2631. function genNode(node, context) {
  2632. if (isString(node)) {
  2633. context.push(node);
  2634. return;
  2635. }
  2636. if (isSymbol(node)) {
  2637. context.push(context.helper(node));
  2638. return;
  2639. }
  2640. switch (node.type) {
  2641. case 1 /* NodeTypes.ELEMENT */:
  2642. case 9 /* NodeTypes.IF */:
  2643. case 11 /* NodeTypes.FOR */:
  2644. assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  2645. `Apply appropriate transforms first.`);
  2646. genNode(node.codegenNode, context);
  2647. break;
  2648. case 2 /* NodeTypes.TEXT */:
  2649. genText(node, context);
  2650. break;
  2651. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  2652. genExpression(node, context);
  2653. break;
  2654. case 5 /* NodeTypes.INTERPOLATION */:
  2655. genInterpolation(node, context);
  2656. break;
  2657. case 12 /* NodeTypes.TEXT_CALL */:
  2658. genNode(node.codegenNode, context);
  2659. break;
  2660. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  2661. genCompoundExpression(node, context);
  2662. break;
  2663. case 3 /* NodeTypes.COMMENT */:
  2664. genComment(node, context);
  2665. break;
  2666. case 13 /* NodeTypes.VNODE_CALL */:
  2667. genVNodeCall(node, context);
  2668. break;
  2669. case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
  2670. genCallExpression(node, context);
  2671. break;
  2672. case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
  2673. genObjectExpression(node, context);
  2674. break;
  2675. case 17 /* NodeTypes.JS_ARRAY_EXPRESSION */:
  2676. genArrayExpression(node, context);
  2677. break;
  2678. case 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */:
  2679. genFunctionExpression(node, context);
  2680. break;
  2681. case 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */:
  2682. genConditionalExpression(node, context);
  2683. break;
  2684. case 20 /* NodeTypes.JS_CACHE_EXPRESSION */:
  2685. genCacheExpression(node, context);
  2686. break;
  2687. case 21 /* NodeTypes.JS_BLOCK_STATEMENT */:
  2688. genNodeList(node.body, context, true, false);
  2689. break;
  2690. // SSR only types
  2691. case 22 /* NodeTypes.JS_TEMPLATE_LITERAL */:
  2692. break;
  2693. case 23 /* NodeTypes.JS_IF_STATEMENT */:
  2694. break;
  2695. case 24 /* NodeTypes.JS_ASSIGNMENT_EXPRESSION */:
  2696. break;
  2697. case 25 /* NodeTypes.JS_SEQUENCE_EXPRESSION */:
  2698. break;
  2699. case 26 /* NodeTypes.JS_RETURN_STATEMENT */:
  2700. break;
  2701. /* istanbul ignore next */
  2702. case 10 /* NodeTypes.IF_BRANCH */:
  2703. // noop
  2704. break;
  2705. default:
  2706. {
  2707. assert(false, `unhandled codegen node type: ${node.type}`);
  2708. // make sure we exhaust all possible types
  2709. const exhaustiveCheck = node;
  2710. return exhaustiveCheck;
  2711. }
  2712. }
  2713. }
  2714. function genText(node, context) {
  2715. context.push(JSON.stringify(node.content), node);
  2716. }
  2717. function genExpression(node, context) {
  2718. const { content, isStatic } = node;
  2719. context.push(isStatic ? JSON.stringify(content) : content, node);
  2720. }
  2721. function genInterpolation(node, context) {
  2722. const { push, helper, pure } = context;
  2723. if (pure)
  2724. push(PURE_ANNOTATION);
  2725. push(`${helper(TO_DISPLAY_STRING)}(`);
  2726. genNode(node.content, context);
  2727. push(`)`);
  2728. }
  2729. function genCompoundExpression(node, context) {
  2730. for (let i = 0; i < node.children.length; i++) {
  2731. const child = node.children[i];
  2732. if (isString(child)) {
  2733. context.push(child);
  2734. }
  2735. else {
  2736. genNode(child, context);
  2737. }
  2738. }
  2739. }
  2740. function genExpressionAsPropertyKey(node, context) {
  2741. const { push } = context;
  2742. if (node.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  2743. push(`[`);
  2744. genCompoundExpression(node, context);
  2745. push(`]`);
  2746. }
  2747. else if (node.isStatic) {
  2748. // only quote keys if necessary
  2749. const text = isSimpleIdentifier(node.content)
  2750. ? node.content
  2751. : JSON.stringify(node.content);
  2752. push(text, node);
  2753. }
  2754. else {
  2755. push(`[${node.content}]`, node);
  2756. }
  2757. }
  2758. function genComment(node, context) {
  2759. const { push, helper, pure } = context;
  2760. if (pure) {
  2761. push(PURE_ANNOTATION);
  2762. }
  2763. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  2764. }
  2765. function genVNodeCall(node, context) {
  2766. const { push, helper, pure } = context;
  2767. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
  2768. if (directives) {
  2769. push(helper(WITH_DIRECTIVES) + `(`);
  2770. }
  2771. if (isBlock) {
  2772. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  2773. }
  2774. if (pure) {
  2775. push(PURE_ANNOTATION);
  2776. }
  2777. const callHelper = isBlock
  2778. ? getVNodeBlockHelper(context.inSSR, isComponent)
  2779. : getVNodeHelper(context.inSSR, isComponent);
  2780. push(helper(callHelper) + `(`, node);
  2781. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  2782. push(`)`);
  2783. if (isBlock) {
  2784. push(`)`);
  2785. }
  2786. if (directives) {
  2787. push(`, `);
  2788. genNode(directives, context);
  2789. push(`)`);
  2790. }
  2791. }
  2792. function genNullableArgs(args) {
  2793. let i = args.length;
  2794. while (i--) {
  2795. if (args[i] != null)
  2796. break;
  2797. }
  2798. return args.slice(0, i + 1).map(arg => arg || `null`);
  2799. }
  2800. // JavaScript
  2801. function genCallExpression(node, context) {
  2802. const { push, helper, pure } = context;
  2803. const callee = isString(node.callee) ? node.callee : helper(node.callee);
  2804. if (pure) {
  2805. push(PURE_ANNOTATION);
  2806. }
  2807. push(callee + `(`, node);
  2808. genNodeList(node.arguments, context);
  2809. push(`)`);
  2810. }
  2811. function genObjectExpression(node, context) {
  2812. const { push, indent, deindent, newline } = context;
  2813. const { properties } = node;
  2814. if (!properties.length) {
  2815. push(`{}`, node);
  2816. return;
  2817. }
  2818. const multilines = properties.length > 1 ||
  2819. (properties.some(p => p.value.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */));
  2820. push(multilines ? `{` : `{ `);
  2821. multilines && indent();
  2822. for (let i = 0; i < properties.length; i++) {
  2823. const { key, value } = properties[i];
  2824. // key
  2825. genExpressionAsPropertyKey(key, context);
  2826. push(`: `);
  2827. // value
  2828. genNode(value, context);
  2829. if (i < properties.length - 1) {
  2830. // will only reach this if it's multilines
  2831. push(`,`);
  2832. newline();
  2833. }
  2834. }
  2835. multilines && deindent();
  2836. push(multilines ? `}` : ` }`);
  2837. }
  2838. function genArrayExpression(node, context) {
  2839. genNodeListAsArray(node.elements, context);
  2840. }
  2841. function genFunctionExpression(node, context) {
  2842. const { push, indent, deindent } = context;
  2843. const { params, returns, body, newline, isSlot } = node;
  2844. if (isSlot) {
  2845. // wrap slot functions with owner context
  2846. push(`_${helperNameMap[WITH_CTX]}(`);
  2847. }
  2848. push(`(`, node);
  2849. if (isArray(params)) {
  2850. genNodeList(params, context);
  2851. }
  2852. else if (params) {
  2853. genNode(params, context);
  2854. }
  2855. push(`) => `);
  2856. if (newline || body) {
  2857. push(`{`);
  2858. indent();
  2859. }
  2860. if (returns) {
  2861. if (newline) {
  2862. push(`return `);
  2863. }
  2864. if (isArray(returns)) {
  2865. genNodeListAsArray(returns, context);
  2866. }
  2867. else {
  2868. genNode(returns, context);
  2869. }
  2870. }
  2871. else if (body) {
  2872. genNode(body, context);
  2873. }
  2874. if (newline || body) {
  2875. deindent();
  2876. push(`}`);
  2877. }
  2878. if (isSlot) {
  2879. if (node.isNonScopedSlot) {
  2880. push(`, undefined, true`);
  2881. }
  2882. push(`)`);
  2883. }
  2884. }
  2885. function genConditionalExpression(node, context) {
  2886. const { test, consequent, alternate, newline: needNewline } = node;
  2887. const { push, indent, deindent, newline } = context;
  2888. if (test.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  2889. const needsParens = !isSimpleIdentifier(test.content);
  2890. needsParens && push(`(`);
  2891. genExpression(test, context);
  2892. needsParens && push(`)`);
  2893. }
  2894. else {
  2895. push(`(`);
  2896. genNode(test, context);
  2897. push(`)`);
  2898. }
  2899. needNewline && indent();
  2900. context.indentLevel++;
  2901. needNewline || push(` `);
  2902. push(`? `);
  2903. genNode(consequent, context);
  2904. context.indentLevel--;
  2905. needNewline && newline();
  2906. needNewline || push(` `);
  2907. push(`: `);
  2908. const isNested = alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */;
  2909. if (!isNested) {
  2910. context.indentLevel++;
  2911. }
  2912. genNode(alternate, context);
  2913. if (!isNested) {
  2914. context.indentLevel--;
  2915. }
  2916. needNewline && deindent(true /* without newline */);
  2917. }
  2918. function genCacheExpression(node, context) {
  2919. const { push, helper, indent, deindent, newline } = context;
  2920. push(`_cache[${node.index}] || (`);
  2921. if (node.isVNode) {
  2922. indent();
  2923. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  2924. newline();
  2925. }
  2926. push(`_cache[${node.index}] = `);
  2927. genNode(node.value, context);
  2928. if (node.isVNode) {
  2929. push(`,`);
  2930. newline();
  2931. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  2932. newline();
  2933. push(`_cache[${node.index}]`);
  2934. deindent();
  2935. }
  2936. push(`)`);
  2937. }
  2938. function walkIdentifiers(root, onIdentifier, includeAll = false, parentStack = [], knownIds = Object.create(null)) {
  2939. {
  2940. return;
  2941. }
  2942. }
  2943. function isReferencedIdentifier(id, parent, parentStack) {
  2944. {
  2945. return false;
  2946. }
  2947. }
  2948. function isInDestructureAssignment(parent, parentStack) {
  2949. if (parent &&
  2950. (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')) {
  2951. let i = parentStack.length;
  2952. while (i--) {
  2953. const p = parentStack[i];
  2954. if (p.type === 'AssignmentExpression') {
  2955. return true;
  2956. }
  2957. else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
  2958. break;
  2959. }
  2960. }
  2961. }
  2962. return false;
  2963. }
  2964. function walkFunctionParams(node, onIdent) {
  2965. for (const p of node.params) {
  2966. for (const id of extractIdentifiers(p)) {
  2967. onIdent(id);
  2968. }
  2969. }
  2970. }
  2971. function walkBlockDeclarations(block, onIdent) {
  2972. for (const stmt of block.body) {
  2973. if (stmt.type === 'VariableDeclaration') {
  2974. if (stmt.declare)
  2975. continue;
  2976. for (const decl of stmt.declarations) {
  2977. for (const id of extractIdentifiers(decl.id)) {
  2978. onIdent(id);
  2979. }
  2980. }
  2981. }
  2982. else if (stmt.type === 'FunctionDeclaration' ||
  2983. stmt.type === 'ClassDeclaration') {
  2984. if (stmt.declare || !stmt.id)
  2985. continue;
  2986. onIdent(stmt.id);
  2987. }
  2988. }
  2989. }
  2990. function extractIdentifiers(param, nodes = []) {
  2991. switch (param.type) {
  2992. case 'Identifier':
  2993. nodes.push(param);
  2994. break;
  2995. case 'MemberExpression':
  2996. let object = param;
  2997. while (object.type === 'MemberExpression') {
  2998. object = object.object;
  2999. }
  3000. nodes.push(object);
  3001. break;
  3002. case 'ObjectPattern':
  3003. for (const prop of param.properties) {
  3004. if (prop.type === 'RestElement') {
  3005. extractIdentifiers(prop.argument, nodes);
  3006. }
  3007. else {
  3008. extractIdentifiers(prop.value, nodes);
  3009. }
  3010. }
  3011. break;
  3012. case 'ArrayPattern':
  3013. param.elements.forEach(element => {
  3014. if (element)
  3015. extractIdentifiers(element, nodes);
  3016. });
  3017. break;
  3018. case 'RestElement':
  3019. extractIdentifiers(param.argument, nodes);
  3020. break;
  3021. case 'AssignmentPattern':
  3022. extractIdentifiers(param.left, nodes);
  3023. break;
  3024. }
  3025. return nodes;
  3026. }
  3027. const isFunctionType = (node) => {
  3028. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  3029. };
  3030. const isStaticProperty = (node) => node &&
  3031. (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
  3032. !node.computed;
  3033. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  3034. // these keywords should not appear inside expressions, but operators like
  3035. // typeof, instanceof and in are allowed
  3036. const prohibitedKeywordRE = new RegExp('\\b' +
  3037. ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
  3038. 'super,throw,while,yield,delete,export,import,return,switch,default,' +
  3039. 'extends,finally,continue,debugger,function,arguments,typeof,void')
  3040. .split(',')
  3041. .join('\\b|\\b') +
  3042. '\\b');
  3043. // strip strings in expressions
  3044. const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
  3045. /**
  3046. * Validate a non-prefixed expression.
  3047. * This is only called when using the in-browser runtime compiler since it
  3048. * doesn't prefix expressions.
  3049. */
  3050. function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
  3051. const exp = node.content;
  3052. // empty expressions are validated per-directive since some directives
  3053. // do allow empty expressions.
  3054. if (!exp.trim()) {
  3055. return;
  3056. }
  3057. try {
  3058. new Function(asRawStatements
  3059. ? ` ${exp} `
  3060. : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
  3061. }
  3062. catch (e) {
  3063. let message = e.message;
  3064. const keywordMatch = exp
  3065. .replace(stripStringRE, '')
  3066. .match(prohibitedKeywordRE);
  3067. if (keywordMatch) {
  3068. message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
  3069. }
  3070. context.onError(createCompilerError(45 /* ErrorCodes.X_INVALID_EXPRESSION */, node.loc, undefined, message));
  3071. }
  3072. }
  3073. const transformExpression = (node, context) => {
  3074. if (node.type === 5 /* NodeTypes.INTERPOLATION */) {
  3075. node.content = processExpression(node.content, context);
  3076. }
  3077. else if (node.type === 1 /* NodeTypes.ELEMENT */) {
  3078. // handle directives on element
  3079. for (let i = 0; i < node.props.length; i++) {
  3080. const dir = node.props[i];
  3081. // do not process for v-on & v-for since they are special handled
  3082. if (dir.type === 7 /* NodeTypes.DIRECTIVE */ && dir.name !== 'for') {
  3083. const exp = dir.exp;
  3084. const arg = dir.arg;
  3085. // do not process exp if this is v-on:arg - we need special handling
  3086. // for wrapping inline statements.
  3087. if (exp &&
  3088. exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  3089. !(dir.name === 'on' && arg)) {
  3090. dir.exp = processExpression(exp, context,
  3091. // slot args must be processed as function params
  3092. dir.name === 'slot');
  3093. }
  3094. if (arg && arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !arg.isStatic) {
  3095. dir.arg = processExpression(arg, context);
  3096. }
  3097. }
  3098. }
  3099. }
  3100. };
  3101. // Important: since this function uses Node.js only dependencies, it should
  3102. // always be used with a leading !true check so that it can be
  3103. // tree-shaken from the browser build.
  3104. function processExpression(node, context,
  3105. // some expressions like v-slot props & v-for aliases should be parsed as
  3106. // function params
  3107. asParams = false,
  3108. // v-on handler values may contain multiple statements
  3109. asRawStatements = false, localVars = Object.create(context.identifiers)) {
  3110. {
  3111. {
  3112. // simple in-browser validation (same logic in 2.x)
  3113. validateBrowserExpression(node, context, asParams, asRawStatements);
  3114. }
  3115. return node;
  3116. }
  3117. }
  3118. function stringifyExpression(exp) {
  3119. if (isString(exp)) {
  3120. return exp;
  3121. }
  3122. else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  3123. return exp.content;
  3124. }
  3125. else {
  3126. return exp.children
  3127. .map(stringifyExpression)
  3128. .join('');
  3129. }
  3130. }
  3131. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  3132. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  3133. // #1587: We need to dynamically increment the key based on the current
  3134. // node's sibling nodes, since chained v-if/else branches are
  3135. // rendered at the same depth
  3136. const siblings = context.parent.children;
  3137. let i = siblings.indexOf(ifNode);
  3138. let key = 0;
  3139. while (i-- >= 0) {
  3140. const sibling = siblings[i];
  3141. if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
  3142. key += sibling.branches.length;
  3143. }
  3144. }
  3145. // Exit callback. Complete the codegenNode when all children have been
  3146. // transformed.
  3147. return () => {
  3148. if (isRoot) {
  3149. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  3150. }
  3151. else {
  3152. // attach this branch's codegen node to the v-if root.
  3153. const parentCondition = getParentCondition(ifNode.codegenNode);
  3154. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  3155. }
  3156. };
  3157. });
  3158. });
  3159. // target-agnostic transform used for both Client and SSR
  3160. function processIf(node, dir, context, processCodegen) {
  3161. if (dir.name !== 'else' &&
  3162. (!dir.exp || !dir.exp.content.trim())) {
  3163. const loc = dir.exp ? dir.exp.loc : node.loc;
  3164. context.onError(createCompilerError(28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */, dir.loc));
  3165. dir.exp = createSimpleExpression(`true`, false, loc);
  3166. }
  3167. if (dir.exp) {
  3168. validateBrowserExpression(dir.exp, context);
  3169. }
  3170. if (dir.name === 'if') {
  3171. const branch = createIfBranch(node, dir);
  3172. const ifNode = {
  3173. type: 9 /* NodeTypes.IF */,
  3174. loc: node.loc,
  3175. branches: [branch]
  3176. };
  3177. context.replaceNode(ifNode);
  3178. if (processCodegen) {
  3179. return processCodegen(ifNode, branch, true);
  3180. }
  3181. }
  3182. else {
  3183. // locate the adjacent v-if
  3184. const siblings = context.parent.children;
  3185. const comments = [];
  3186. let i = siblings.indexOf(node);
  3187. while (i-- >= -1) {
  3188. const sibling = siblings[i];
  3189. if (sibling && sibling.type === 3 /* NodeTypes.COMMENT */) {
  3190. context.removeNode(sibling);
  3191. comments.unshift(sibling);
  3192. continue;
  3193. }
  3194. if (sibling &&
  3195. sibling.type === 2 /* NodeTypes.TEXT */ &&
  3196. !sibling.content.trim().length) {
  3197. context.removeNode(sibling);
  3198. continue;
  3199. }
  3200. if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
  3201. // Check if v-else was followed by v-else-if
  3202. if (dir.name === 'else-if' &&
  3203. sibling.branches[sibling.branches.length - 1].condition === undefined) {
  3204. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  3205. }
  3206. // move the node to the if node's branches
  3207. context.removeNode();
  3208. const branch = createIfBranch(node, dir);
  3209. if (comments.length &&
  3210. // #3619 ignore comments if the v-if is direct child of <transition>
  3211. !(context.parent &&
  3212. context.parent.type === 1 /* NodeTypes.ELEMENT */ &&
  3213. isBuiltInType(context.parent.tag, 'transition'))) {
  3214. branch.children = [...comments, ...branch.children];
  3215. }
  3216. // check if user is forcing same key on different branches
  3217. {
  3218. const key = branch.userKey;
  3219. if (key) {
  3220. sibling.branches.forEach(({ userKey }) => {
  3221. if (isSameKey(userKey, key)) {
  3222. context.onError(createCompilerError(29 /* ErrorCodes.X_V_IF_SAME_KEY */, branch.userKey.loc));
  3223. }
  3224. });
  3225. }
  3226. }
  3227. sibling.branches.push(branch);
  3228. const onExit = processCodegen && processCodegen(sibling, branch, false);
  3229. // since the branch was removed, it will not be traversed.
  3230. // make sure to traverse here.
  3231. traverseNode(branch, context);
  3232. // call on exit
  3233. if (onExit)
  3234. onExit();
  3235. // make sure to reset currentNode after traversal to indicate this
  3236. // node has been removed.
  3237. context.currentNode = null;
  3238. }
  3239. else {
  3240. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  3241. }
  3242. break;
  3243. }
  3244. }
  3245. }
  3246. function createIfBranch(node, dir) {
  3247. const isTemplateIf = node.tagType === 3 /* ElementTypes.TEMPLATE */;
  3248. return {
  3249. type: 10 /* NodeTypes.IF_BRANCH */,
  3250. loc: node.loc,
  3251. condition: dir.name === 'else' ? undefined : dir.exp,
  3252. children: isTemplateIf && !findDir(node, 'for') ? node.children : [node],
  3253. userKey: findProp(node, `key`),
  3254. isTemplateIf
  3255. };
  3256. }
  3257. function createCodegenNodeForBranch(branch, keyIndex, context) {
  3258. if (branch.condition) {
  3259. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  3260. // make sure to pass in asBlock: true so that the comment node call
  3261. // closes the current block.
  3262. createCallExpression(context.helper(CREATE_COMMENT), [
  3263. '"v-if"' ,
  3264. 'true'
  3265. ]));
  3266. }
  3267. else {
  3268. return createChildrenCodegenNode(branch, keyIndex, context);
  3269. }
  3270. }
  3271. function createChildrenCodegenNode(branch, keyIndex, context) {
  3272. const { helper } = context;
  3273. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* ConstantTypes.CAN_HOIST */));
  3274. const { children } = branch;
  3275. const firstChild = children[0];
  3276. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* NodeTypes.ELEMENT */;
  3277. if (needFragmentWrapper) {
  3278. if (children.length === 1 && firstChild.type === 11 /* NodeTypes.FOR */) {
  3279. // optimize away nested fragments when child is a ForNode
  3280. const vnodeCall = firstChild.codegenNode;
  3281. injectProp(vnodeCall, keyProperty, context);
  3282. return vnodeCall;
  3283. }
  3284. else {
  3285. let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
  3286. let patchFlagText = PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
  3287. // check if the fragment actually contains a single valid child with
  3288. // the rest being comments
  3289. if (!branch.isTemplateIf &&
  3290. children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
  3291. patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
  3292. patchFlagText += `, ${PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
  3293. }
  3294. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
  3295. }
  3296. }
  3297. else {
  3298. const ret = firstChild.codegenNode;
  3299. const vnodeCall = getMemoedVNodeCall(ret);
  3300. // Change createVNode to createBlock.
  3301. if (vnodeCall.type === 13 /* NodeTypes.VNODE_CALL */) {
  3302. makeBlock(vnodeCall, context);
  3303. }
  3304. // inject branch key
  3305. injectProp(vnodeCall, keyProperty, context);
  3306. return ret;
  3307. }
  3308. }
  3309. function isSameKey(a, b) {
  3310. if (!a || a.type !== b.type) {
  3311. return false;
  3312. }
  3313. if (a.type === 6 /* NodeTypes.ATTRIBUTE */) {
  3314. if (a.value.content !== b.value.content) {
  3315. return false;
  3316. }
  3317. }
  3318. else {
  3319. // directive
  3320. const exp = a.exp;
  3321. const branchExp = b.exp;
  3322. if (exp.type !== branchExp.type) {
  3323. return false;
  3324. }
  3325. if (exp.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  3326. exp.isStatic !== branchExp.isStatic ||
  3327. exp.content !== branchExp.content) {
  3328. return false;
  3329. }
  3330. }
  3331. return true;
  3332. }
  3333. function getParentCondition(node) {
  3334. while (true) {
  3335. if (node.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  3336. if (node.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  3337. node = node.alternate;
  3338. }
  3339. else {
  3340. return node;
  3341. }
  3342. }
  3343. else if (node.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */) {
  3344. node = node.value;
  3345. }
  3346. }
  3347. }
  3348. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  3349. const { helper, removeHelper } = context;
  3350. return processFor(node, dir, context, forNode => {
  3351. // create the loop render function expression now, and add the
  3352. // iterator on exit after all children have been traversed
  3353. const renderExp = createCallExpression(helper(RENDER_LIST), [
  3354. forNode.source
  3355. ]);
  3356. const isTemplate = isTemplateNode(node);
  3357. const memo = findDir(node, 'memo');
  3358. const keyProp = findProp(node, `key`);
  3359. const keyExp = keyProp &&
  3360. (keyProp.type === 6 /* NodeTypes.ATTRIBUTE */
  3361. ? createSimpleExpression(keyProp.value.content, true)
  3362. : keyProp.exp);
  3363. const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
  3364. const isStableFragment = forNode.source.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  3365. forNode.source.constType > 0 /* ConstantTypes.NOT_CONSTANT */;
  3366. const fragmentFlag = isStableFragment
  3367. ? 64 /* PatchFlags.STABLE_FRAGMENT */
  3368. : keyProp
  3369. ? 128 /* PatchFlags.KEYED_FRAGMENT */
  3370. : 256 /* PatchFlags.UNKEYED_FRAGMENT */;
  3371. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
  3372. (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
  3373. return () => {
  3374. // finish the codegen now that all children have been traversed
  3375. let childBlock;
  3376. const { children } = forNode;
  3377. // check <template v-for> key placement
  3378. if (isTemplate) {
  3379. node.children.some(c => {
  3380. if (c.type === 1 /* NodeTypes.ELEMENT */) {
  3381. const key = findProp(c, 'key');
  3382. if (key) {
  3383. context.onError(createCompilerError(33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  3384. return true;
  3385. }
  3386. }
  3387. });
  3388. }
  3389. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* NodeTypes.ELEMENT */;
  3390. const slotOutlet = isSlotOutlet(node)
  3391. ? node
  3392. : isTemplate &&
  3393. node.children.length === 1 &&
  3394. isSlotOutlet(node.children[0])
  3395. ? node.children[0] // api-extractor somehow fails to infer this
  3396. : null;
  3397. if (slotOutlet) {
  3398. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  3399. childBlock = slotOutlet.codegenNode;
  3400. if (isTemplate && keyProperty) {
  3401. // <template v-for="..." :key="..."><slot/></template>
  3402. // we need to inject the key to the renderSlot() call.
  3403. // the props for renderSlot is passed as the 3rd argument.
  3404. injectProp(childBlock, keyProperty, context);
  3405. }
  3406. }
  3407. else if (needFragmentWrapper) {
  3408. // <template v-for="..."> with text or multi-elements
  3409. // should generate a fragment block for each loop
  3410. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* PatchFlags.STABLE_FRAGMENT */ +
  3411. (` /* ${PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */]} */`
  3412. ), undefined, undefined, true, undefined, false /* isComponent */);
  3413. }
  3414. else {
  3415. // Normal element v-for. Directly use the child's codegenNode
  3416. // but mark it as a block.
  3417. childBlock = children[0]
  3418. .codegenNode;
  3419. if (isTemplate && keyProperty) {
  3420. injectProp(childBlock, keyProperty, context);
  3421. }
  3422. if (childBlock.isBlock !== !isStableFragment) {
  3423. if (childBlock.isBlock) {
  3424. // switch from block to vnode
  3425. removeHelper(OPEN_BLOCK);
  3426. removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  3427. }
  3428. else {
  3429. // switch from vnode to block
  3430. removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  3431. }
  3432. }
  3433. childBlock.isBlock = !isStableFragment;
  3434. if (childBlock.isBlock) {
  3435. helper(OPEN_BLOCK);
  3436. helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  3437. }
  3438. else {
  3439. helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  3440. }
  3441. }
  3442. if (memo) {
  3443. const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
  3444. createSimpleExpression(`_cached`)
  3445. ]));
  3446. loop.body = createBlockStatement([
  3447. createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
  3448. createCompoundExpression([
  3449. `if (_cached`,
  3450. ...(keyExp ? [` && _cached.key === `, keyExp] : []),
  3451. ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
  3452. ]),
  3453. createCompoundExpression([`const _item = `, childBlock]),
  3454. createSimpleExpression(`_item.memo = _memo`),
  3455. createSimpleExpression(`return _item`)
  3456. ]);
  3457. renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
  3458. }
  3459. else {
  3460. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  3461. }
  3462. };
  3463. });
  3464. });
  3465. // target-agnostic transform used for both Client and SSR
  3466. function processFor(node, dir, context, processCodegen) {
  3467. if (!dir.exp) {
  3468. context.onError(createCompilerError(31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */, dir.loc));
  3469. return;
  3470. }
  3471. const parseResult = parseForExpression(
  3472. // can only be simple expression because vFor transform is applied
  3473. // before expression transform.
  3474. dir.exp, context);
  3475. if (!parseResult) {
  3476. context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  3477. return;
  3478. }
  3479. const { addIdentifiers, removeIdentifiers, scopes } = context;
  3480. const { source, value, key, index } = parseResult;
  3481. const forNode = {
  3482. type: 11 /* NodeTypes.FOR */,
  3483. loc: dir.loc,
  3484. source,
  3485. valueAlias: value,
  3486. keyAlias: key,
  3487. objectIndexAlias: index,
  3488. parseResult,
  3489. children: isTemplateNode(node) ? node.children : [node]
  3490. };
  3491. context.replaceNode(forNode);
  3492. // bookkeeping
  3493. scopes.vFor++;
  3494. const onExit = processCodegen && processCodegen(forNode);
  3495. return () => {
  3496. scopes.vFor--;
  3497. if (onExit)
  3498. onExit();
  3499. };
  3500. }
  3501. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  3502. // This regex doesn't cover the case if key or index aliases have destructuring,
  3503. // but those do not make sense in the first place, so this works in practice.
  3504. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  3505. const stripParensRE = /^\(|\)$/g;
  3506. function parseForExpression(input, context) {
  3507. const loc = input.loc;
  3508. const exp = input.content;
  3509. const inMatch = exp.match(forAliasRE);
  3510. if (!inMatch)
  3511. return;
  3512. const [, LHS, RHS] = inMatch;
  3513. const result = {
  3514. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  3515. value: undefined,
  3516. key: undefined,
  3517. index: undefined
  3518. };
  3519. {
  3520. validateBrowserExpression(result.source, context);
  3521. }
  3522. let valueContent = LHS.trim().replace(stripParensRE, '').trim();
  3523. const trimmedOffset = LHS.indexOf(valueContent);
  3524. const iteratorMatch = valueContent.match(forIteratorRE);
  3525. if (iteratorMatch) {
  3526. valueContent = valueContent.replace(forIteratorRE, '').trim();
  3527. const keyContent = iteratorMatch[1].trim();
  3528. let keyOffset;
  3529. if (keyContent) {
  3530. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  3531. result.key = createAliasExpression(loc, keyContent, keyOffset);
  3532. {
  3533. validateBrowserExpression(result.key, context, true);
  3534. }
  3535. }
  3536. if (iteratorMatch[2]) {
  3537. const indexContent = iteratorMatch[2].trim();
  3538. if (indexContent) {
  3539. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  3540. ? keyOffset + keyContent.length
  3541. : trimmedOffset + valueContent.length));
  3542. {
  3543. validateBrowserExpression(result.index, context, true);
  3544. }
  3545. }
  3546. }
  3547. }
  3548. if (valueContent) {
  3549. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  3550. {
  3551. validateBrowserExpression(result.value, context, true);
  3552. }
  3553. }
  3554. return result;
  3555. }
  3556. function createAliasExpression(range, content, offset) {
  3557. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  3558. }
  3559. function createForLoopParams({ value, key, index }, memoArgs = []) {
  3560. return createParamsList([value, key, index, ...memoArgs]);
  3561. }
  3562. function createParamsList(args) {
  3563. let i = args.length;
  3564. while (i--) {
  3565. if (args[i])
  3566. break;
  3567. }
  3568. return args
  3569. .slice(0, i + 1)
  3570. .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
  3571. }
  3572. const defaultFallback = createSimpleExpression(`undefined`, false);
  3573. // A NodeTransform that:
  3574. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  3575. // by transformExpression. This is only applied in non-browser builds with
  3576. // { prefixIdentifiers: true }.
  3577. // 2. Track v-slot depths so that we know a slot is inside another slot.
  3578. // Note the exit callback is executed before buildSlots() on the same node,
  3579. // so only nested slots see positive numbers.
  3580. const trackSlotScopes = (node, context) => {
  3581. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  3582. (node.tagType === 1 /* ElementTypes.COMPONENT */ ||
  3583. node.tagType === 3 /* ElementTypes.TEMPLATE */)) {
  3584. // We are only checking non-empty v-slot here
  3585. // since we only care about slots that introduce scope variables.
  3586. const vSlot = findDir(node, 'slot');
  3587. if (vSlot) {
  3588. vSlot.exp;
  3589. context.scopes.vSlot++;
  3590. return () => {
  3591. context.scopes.vSlot--;
  3592. };
  3593. }
  3594. }
  3595. };
  3596. // A NodeTransform that tracks scope identifiers for scoped slots with v-for.
  3597. // This transform is only applied in non-browser builds with { prefixIdentifiers: true }
  3598. const trackVForSlotScopes = (node, context) => {
  3599. let vFor;
  3600. if (isTemplateNode(node) &&
  3601. node.props.some(isVSlot) &&
  3602. (vFor = findDir(node, 'for'))) {
  3603. const result = (vFor.parseResult = parseForExpression(vFor.exp, context));
  3604. if (result) {
  3605. const { value, key, index } = result;
  3606. const { addIdentifiers, removeIdentifiers } = context;
  3607. value && addIdentifiers(value);
  3608. key && addIdentifiers(key);
  3609. index && addIdentifiers(index);
  3610. return () => {
  3611. value && removeIdentifiers(value);
  3612. key && removeIdentifiers(key);
  3613. index && removeIdentifiers(index);
  3614. };
  3615. }
  3616. }
  3617. };
  3618. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  3619. // Instead of being a DirectiveTransform, v-slot processing is called during
  3620. // transformElement to build the slots object for a component.
  3621. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  3622. context.helper(WITH_CTX);
  3623. const { children, loc } = node;
  3624. const slotsProperties = [];
  3625. const dynamicSlots = [];
  3626. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  3627. // since it likely uses a scope variable.
  3628. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  3629. // 1. Check for slot with slotProps on component itself.
  3630. // <Comp v-slot="{ prop }"/>
  3631. const onComponentSlot = findDir(node, 'slot', true);
  3632. if (onComponentSlot) {
  3633. const { arg, exp } = onComponentSlot;
  3634. if (arg && !isStaticExp(arg)) {
  3635. hasDynamicSlots = true;
  3636. }
  3637. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  3638. }
  3639. // 2. Iterate through children and check for template slots
  3640. // <template v-slot:foo="{ prop }">
  3641. let hasTemplateSlots = false;
  3642. let hasNamedDefaultSlot = false;
  3643. const implicitDefaultChildren = [];
  3644. const seenSlotNames = new Set();
  3645. let conditionalBranchIndex = 0;
  3646. for (let i = 0; i < children.length; i++) {
  3647. const slotElement = children[i];
  3648. let slotDir;
  3649. if (!isTemplateNode(slotElement) ||
  3650. !(slotDir = findDir(slotElement, 'slot', true))) {
  3651. // not a <template v-slot>, skip.
  3652. if (slotElement.type !== 3 /* NodeTypes.COMMENT */) {
  3653. implicitDefaultChildren.push(slotElement);
  3654. }
  3655. continue;
  3656. }
  3657. if (onComponentSlot) {
  3658. // already has on-component slot - this is incorrect usage.
  3659. context.onError(createCompilerError(37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  3660. break;
  3661. }
  3662. hasTemplateSlots = true;
  3663. const { children: slotChildren, loc: slotLoc } = slotElement;
  3664. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  3665. // check if name is dynamic.
  3666. let staticSlotName;
  3667. if (isStaticExp(slotName)) {
  3668. staticSlotName = slotName ? slotName.content : `default`;
  3669. }
  3670. else {
  3671. hasDynamicSlots = true;
  3672. }
  3673. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  3674. // check if this slot is conditional (v-if/v-for)
  3675. let vIf;
  3676. let vElse;
  3677. let vFor;
  3678. if ((vIf = findDir(slotElement, 'if'))) {
  3679. hasDynamicSlots = true;
  3680. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback));
  3681. }
  3682. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  3683. // find adjacent v-if
  3684. let j = i;
  3685. let prev;
  3686. while (j--) {
  3687. prev = children[j];
  3688. if (prev.type !== 3 /* NodeTypes.COMMENT */) {
  3689. break;
  3690. }
  3691. }
  3692. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  3693. // remove node
  3694. children.splice(i, 1);
  3695. i--;
  3696. // attach this slot to previous conditional
  3697. let conditional = dynamicSlots[dynamicSlots.length - 1];
  3698. while (conditional.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  3699. conditional = conditional.alternate;
  3700. }
  3701. conditional.alternate = vElse.exp
  3702. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback)
  3703. : buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++);
  3704. }
  3705. else {
  3706. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  3707. }
  3708. }
  3709. else if ((vFor = findDir(slotElement, 'for'))) {
  3710. hasDynamicSlots = true;
  3711. const parseResult = vFor.parseResult ||
  3712. parseForExpression(vFor.exp, context);
  3713. if (parseResult) {
  3714. // Render the dynamic slots as an array and add it to the createSlot()
  3715. // args. The runtime knows how to handle it appropriately.
  3716. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  3717. parseResult.source,
  3718. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  3719. ]));
  3720. }
  3721. else {
  3722. context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  3723. }
  3724. }
  3725. else {
  3726. // check duplicate static names
  3727. if (staticSlotName) {
  3728. if (seenSlotNames.has(staticSlotName)) {
  3729. context.onError(createCompilerError(38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  3730. continue;
  3731. }
  3732. seenSlotNames.add(staticSlotName);
  3733. if (staticSlotName === 'default') {
  3734. hasNamedDefaultSlot = true;
  3735. }
  3736. }
  3737. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  3738. }
  3739. }
  3740. if (!onComponentSlot) {
  3741. const buildDefaultSlotProperty = (props, children) => {
  3742. const fn = buildSlotFn(props, children, loc);
  3743. if (context.compatConfig) {
  3744. fn.isNonScopedSlot = true;
  3745. }
  3746. return createObjectProperty(`default`, fn);
  3747. };
  3748. if (!hasTemplateSlots) {
  3749. // implicit default slot (on component)
  3750. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  3751. }
  3752. else if (implicitDefaultChildren.length &&
  3753. // #3766
  3754. // with whitespace: 'preserve', whitespaces between slots will end up in
  3755. // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
  3756. implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
  3757. // implicit default slot (mixed with named slots)
  3758. if (hasNamedDefaultSlot) {
  3759. context.onError(createCompilerError(39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  3760. }
  3761. else {
  3762. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  3763. }
  3764. }
  3765. }
  3766. const slotFlag = hasDynamicSlots
  3767. ? 2 /* SlotFlags.DYNAMIC */
  3768. : hasForwardedSlots(node.children)
  3769. ? 3 /* SlotFlags.FORWARDED */
  3770. : 1 /* SlotFlags.STABLE */;
  3771. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  3772. // 2 = compiled but dynamic = can skip normalization, but must run diff
  3773. // 1 = compiled and static = can skip normalization AND diff as optimized
  3774. createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
  3775. if (dynamicSlots.length) {
  3776. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  3777. slots,
  3778. createArrayExpression(dynamicSlots)
  3779. ]);
  3780. }
  3781. return {
  3782. slots,
  3783. hasDynamicSlots
  3784. };
  3785. }
  3786. function buildDynamicSlot(name, fn, index) {
  3787. const props = [
  3788. createObjectProperty(`name`, name),
  3789. createObjectProperty(`fn`, fn)
  3790. ];
  3791. if (index != null) {
  3792. props.push(createObjectProperty(`key`, createSimpleExpression(String(index), true)));
  3793. }
  3794. return createObjectExpression(props);
  3795. }
  3796. function hasForwardedSlots(children) {
  3797. for (let i = 0; i < children.length; i++) {
  3798. const child = children[i];
  3799. switch (child.type) {
  3800. case 1 /* NodeTypes.ELEMENT */:
  3801. if (child.tagType === 2 /* ElementTypes.SLOT */ ||
  3802. hasForwardedSlots(child.children)) {
  3803. return true;
  3804. }
  3805. break;
  3806. case 9 /* NodeTypes.IF */:
  3807. if (hasForwardedSlots(child.branches))
  3808. return true;
  3809. break;
  3810. case 10 /* NodeTypes.IF_BRANCH */:
  3811. case 11 /* NodeTypes.FOR */:
  3812. if (hasForwardedSlots(child.children))
  3813. return true;
  3814. break;
  3815. }
  3816. }
  3817. return false;
  3818. }
  3819. function isNonWhitespaceContent(node) {
  3820. if (node.type !== 2 /* NodeTypes.TEXT */ && node.type !== 12 /* NodeTypes.TEXT_CALL */)
  3821. return true;
  3822. return node.type === 2 /* NodeTypes.TEXT */
  3823. ? !!node.content.trim()
  3824. : isNonWhitespaceContent(node.content);
  3825. }
  3826. // some directive transforms (e.g. v-model) may return a symbol for runtime
  3827. // import, which should be used instead of a resolveDirective call.
  3828. const directiveImportMap = new WeakMap();
  3829. // generate a JavaScript AST for this element's codegen
  3830. const transformElement = (node, context) => {
  3831. // perform the work on exit, after all child expressions have been
  3832. // processed and merged.
  3833. return function postTransformElement() {
  3834. node = context.currentNode;
  3835. if (!(node.type === 1 /* NodeTypes.ELEMENT */ &&
  3836. (node.tagType === 0 /* ElementTypes.ELEMENT */ ||
  3837. node.tagType === 1 /* ElementTypes.COMPONENT */))) {
  3838. return;
  3839. }
  3840. const { tag, props } = node;
  3841. const isComponent = node.tagType === 1 /* ElementTypes.COMPONENT */;
  3842. // The goal of the transform is to create a codegenNode implementing the
  3843. // VNodeCall interface.
  3844. let vnodeTag = isComponent
  3845. ? resolveComponentType(node, context)
  3846. : `"${tag}"`;
  3847. const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  3848. let vnodeProps;
  3849. let vnodeChildren;
  3850. let vnodePatchFlag;
  3851. let patchFlag = 0;
  3852. let vnodeDynamicProps;
  3853. let dynamicPropNames;
  3854. let vnodeDirectives;
  3855. let shouldUseBlock =
  3856. // dynamic component may resolve to plain elements
  3857. isDynamicComponent ||
  3858. vnodeTag === TELEPORT ||
  3859. vnodeTag === SUSPENSE ||
  3860. (!isComponent &&
  3861. // <svg> and <foreignObject> must be forced into blocks so that block
  3862. // updates inside get proper isSVG flag at runtime. (#639, #643)
  3863. // This is technically web-specific, but splitting the logic out of core
  3864. // leads to too much unnecessary complexity.
  3865. (tag === 'svg' || tag === 'foreignObject'));
  3866. // props
  3867. if (props.length > 0) {
  3868. const propsBuildResult = buildProps(node, context, undefined, isComponent, isDynamicComponent);
  3869. vnodeProps = propsBuildResult.props;
  3870. patchFlag = propsBuildResult.patchFlag;
  3871. dynamicPropNames = propsBuildResult.dynamicPropNames;
  3872. const directives = propsBuildResult.directives;
  3873. vnodeDirectives =
  3874. directives && directives.length
  3875. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  3876. : undefined;
  3877. if (propsBuildResult.shouldUseBlock) {
  3878. shouldUseBlock = true;
  3879. }
  3880. }
  3881. // children
  3882. if (node.children.length > 0) {
  3883. if (vnodeTag === KEEP_ALIVE) {
  3884. // Although a built-in component, we compile KeepAlive with raw children
  3885. // instead of slot functions so that it can be used inside Transition
  3886. // or other Transition-wrapping HOCs.
  3887. // To ensure correct updates with block optimizations, we need to:
  3888. // 1. Force keep-alive into a block. This avoids its children being
  3889. // collected by a parent block.
  3890. shouldUseBlock = true;
  3891. // 2. Force keep-alive to always be updated, since it uses raw children.
  3892. patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  3893. if (node.children.length > 1) {
  3894. context.onError(createCompilerError(46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */, {
  3895. start: node.children[0].loc.start,
  3896. end: node.children[node.children.length - 1].loc.end,
  3897. source: ''
  3898. }));
  3899. }
  3900. }
  3901. const shouldBuildAsSlots = isComponent &&
  3902. // Teleport is not a real component and has dedicated runtime handling
  3903. vnodeTag !== TELEPORT &&
  3904. // explained above.
  3905. vnodeTag !== KEEP_ALIVE;
  3906. if (shouldBuildAsSlots) {
  3907. const { slots, hasDynamicSlots } = buildSlots(node, context);
  3908. vnodeChildren = slots;
  3909. if (hasDynamicSlots) {
  3910. patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  3911. }
  3912. }
  3913. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  3914. const child = node.children[0];
  3915. const type = child.type;
  3916. // check for dynamic text children
  3917. const hasDynamicTextChild = type === 5 /* NodeTypes.INTERPOLATION */ ||
  3918. type === 8 /* NodeTypes.COMPOUND_EXPRESSION */;
  3919. if (hasDynamicTextChild &&
  3920. getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
  3921. patchFlag |= 1 /* PatchFlags.TEXT */;
  3922. }
  3923. // pass directly if the only child is a text node
  3924. // (plain / interpolation / expression)
  3925. if (hasDynamicTextChild || type === 2 /* NodeTypes.TEXT */) {
  3926. vnodeChildren = child;
  3927. }
  3928. else {
  3929. vnodeChildren = node.children;
  3930. }
  3931. }
  3932. else {
  3933. vnodeChildren = node.children;
  3934. }
  3935. }
  3936. // patchFlag & dynamicPropNames
  3937. if (patchFlag !== 0) {
  3938. {
  3939. if (patchFlag < 0) {
  3940. // special flags (negative and mutually exclusive)
  3941. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  3942. }
  3943. else {
  3944. // bitwise flags
  3945. const flagNames = Object.keys(PatchFlagNames)
  3946. .map(Number)
  3947. .filter(n => n > 0 && patchFlag & n)
  3948. .map(n => PatchFlagNames[n])
  3949. .join(`, `);
  3950. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  3951. }
  3952. }
  3953. if (dynamicPropNames && dynamicPropNames.length) {
  3954. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  3955. }
  3956. }
  3957. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
  3958. };
  3959. };
  3960. function resolveComponentType(node, context, ssr = false) {
  3961. let { tag } = node;
  3962. // 1. dynamic component
  3963. const isExplicitDynamic = isComponentTag(tag);
  3964. const isProp = findProp(node, 'is');
  3965. if (isProp) {
  3966. if (isExplicitDynamic ||
  3967. (isCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context))) {
  3968. const exp = isProp.type === 6 /* NodeTypes.ATTRIBUTE */
  3969. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  3970. : isProp.exp;
  3971. if (exp) {
  3972. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  3973. exp
  3974. ]);
  3975. }
  3976. }
  3977. else if (isProp.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  3978. isProp.value.content.startsWith('vue:')) {
  3979. // <button is="vue:xxx">
  3980. // if not <component>, only is value that starts with "vue:" will be
  3981. // treated as component by the parse phase and reach here, unless it's
  3982. // compat mode where all is values are considered components
  3983. tag = isProp.value.content.slice(4);
  3984. }
  3985. }
  3986. // 1.5 v-is (TODO: Deprecate)
  3987. const isDir = !isExplicitDynamic && findDir(node, 'is');
  3988. if (isDir && isDir.exp) {
  3989. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  3990. isDir.exp
  3991. ]);
  3992. }
  3993. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  3994. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  3995. if (builtIn) {
  3996. // built-ins are simply fallthroughs / have special handling during ssr
  3997. // so we don't need to import their runtime equivalents
  3998. if (!ssr)
  3999. context.helper(builtIn);
  4000. return builtIn;
  4001. }
  4002. // 5. user component (resolve)
  4003. context.helper(RESOLVE_COMPONENT);
  4004. context.components.add(tag);
  4005. return toValidAssetId(tag, `component`);
  4006. }
  4007. function buildProps(node, context, props = node.props, isComponent, isDynamicComponent, ssr = false) {
  4008. const { tag, loc: elementLoc, children } = node;
  4009. let properties = [];
  4010. const mergeArgs = [];
  4011. const runtimeDirectives = [];
  4012. const hasChildren = children.length > 0;
  4013. let shouldUseBlock = false;
  4014. // patchFlag analysis
  4015. let patchFlag = 0;
  4016. let hasRef = false;
  4017. let hasClassBinding = false;
  4018. let hasStyleBinding = false;
  4019. let hasHydrationEventBinding = false;
  4020. let hasDynamicKeys = false;
  4021. let hasVnodeHook = false;
  4022. const dynamicPropNames = [];
  4023. const pushMergeArg = (arg) => {
  4024. if (properties.length) {
  4025. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  4026. properties = [];
  4027. }
  4028. if (arg)
  4029. mergeArgs.push(arg);
  4030. };
  4031. const analyzePatchFlag = ({ key, value }) => {
  4032. if (isStaticExp(key)) {
  4033. const name = key.content;
  4034. const isEventHandler = isOn(name);
  4035. if (isEventHandler &&
  4036. (!isComponent || isDynamicComponent) &&
  4037. // omit the flag for click handlers because hydration gives click
  4038. // dedicated fast path.
  4039. name.toLowerCase() !== 'onclick' &&
  4040. // omit v-model handlers
  4041. name !== 'onUpdate:modelValue' &&
  4042. // omit onVnodeXXX hooks
  4043. !isReservedProp(name)) {
  4044. hasHydrationEventBinding = true;
  4045. }
  4046. if (isEventHandler && isReservedProp(name)) {
  4047. hasVnodeHook = true;
  4048. }
  4049. if (value.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */ ||
  4050. ((value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  4051. value.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) &&
  4052. getConstantType(value, context) > 0)) {
  4053. // skip if the prop is a cached handler or has constant value
  4054. return;
  4055. }
  4056. if (name === 'ref') {
  4057. hasRef = true;
  4058. }
  4059. else if (name === 'class') {
  4060. hasClassBinding = true;
  4061. }
  4062. else if (name === 'style') {
  4063. hasStyleBinding = true;
  4064. }
  4065. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  4066. dynamicPropNames.push(name);
  4067. }
  4068. // treat the dynamic class and style binding of the component as dynamic props
  4069. if (isComponent &&
  4070. (name === 'class' || name === 'style') &&
  4071. !dynamicPropNames.includes(name)) {
  4072. dynamicPropNames.push(name);
  4073. }
  4074. }
  4075. else {
  4076. hasDynamicKeys = true;
  4077. }
  4078. };
  4079. for (let i = 0; i < props.length; i++) {
  4080. // static attribute
  4081. const prop = props[i];
  4082. if (prop.type === 6 /* NodeTypes.ATTRIBUTE */) {
  4083. const { loc, name, value } = prop;
  4084. let isStatic = true;
  4085. if (name === 'ref') {
  4086. hasRef = true;
  4087. if (context.scopes.vFor > 0) {
  4088. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  4089. }
  4090. }
  4091. // skip is on <component>, or is="vue:xxx"
  4092. if (name === 'is' &&
  4093. (isComponentTag(tag) ||
  4094. (value && value.content.startsWith('vue:')) ||
  4095. (isCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context)))) {
  4096. continue;
  4097. }
  4098. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
  4099. }
  4100. else {
  4101. // directives
  4102. const { name, arg, exp, loc } = prop;
  4103. const isVBind = name === 'bind';
  4104. const isVOn = name === 'on';
  4105. // skip v-slot - it is handled by its dedicated transform.
  4106. if (name === 'slot') {
  4107. if (!isComponent) {
  4108. context.onError(createCompilerError(40 /* ErrorCodes.X_V_SLOT_MISPLACED */, loc));
  4109. }
  4110. continue;
  4111. }
  4112. // skip v-once/v-memo - they are handled by dedicated transforms.
  4113. if (name === 'once' || name === 'memo') {
  4114. continue;
  4115. }
  4116. // skip v-is and :is on <component>
  4117. if (name === 'is' ||
  4118. (isVBind &&
  4119. isStaticArgOf(arg, 'is') &&
  4120. (isComponentTag(tag) ||
  4121. (isCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context))))) {
  4122. continue;
  4123. }
  4124. // skip v-on in SSR compilation
  4125. if (isVOn && ssr) {
  4126. continue;
  4127. }
  4128. if (
  4129. // #938: elements with dynamic keys should be forced into blocks
  4130. (isVBind && isStaticArgOf(arg, 'key')) ||
  4131. // inline before-update hooks need to force block so that it is invoked
  4132. // before children
  4133. (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
  4134. shouldUseBlock = true;
  4135. }
  4136. if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
  4137. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  4138. }
  4139. // special case for v-bind and v-on with no argument
  4140. if (!arg && (isVBind || isVOn)) {
  4141. hasDynamicKeys = true;
  4142. if (exp) {
  4143. if (isVBind) {
  4144. // have to merge early for compat build check
  4145. pushMergeArg();
  4146. {
  4147. // 2.x v-bind object order compat
  4148. {
  4149. const hasOverridableKeys = mergeArgs.some(arg => {
  4150. if (arg.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  4151. return arg.properties.some(({ key }) => {
  4152. if (key.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  4153. !key.isStatic) {
  4154. return true;
  4155. }
  4156. return (key.content !== 'class' &&
  4157. key.content !== 'style' &&
  4158. !isOn(key.content));
  4159. });
  4160. }
  4161. else {
  4162. // dynamic expression
  4163. return true;
  4164. }
  4165. });
  4166. if (hasOverridableKeys) {
  4167. checkCompatEnabled("COMPILER_V_BIND_OBJECT_ORDER" /* CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER */, context, loc);
  4168. }
  4169. }
  4170. if (isCompatEnabled("COMPILER_V_BIND_OBJECT_ORDER" /* CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER */, context)) {
  4171. mergeArgs.unshift(exp);
  4172. continue;
  4173. }
  4174. }
  4175. mergeArgs.push(exp);
  4176. }
  4177. else {
  4178. // v-on="obj" -> toHandlers(obj)
  4179. pushMergeArg({
  4180. type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
  4181. loc,
  4182. callee: context.helper(TO_HANDLERS),
  4183. arguments: isComponent ? [exp] : [exp, `true`]
  4184. });
  4185. }
  4186. }
  4187. else {
  4188. context.onError(createCompilerError(isVBind
  4189. ? 34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */
  4190. : 35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
  4191. }
  4192. continue;
  4193. }
  4194. const directiveTransform = context.directiveTransforms[name];
  4195. if (directiveTransform) {
  4196. // has built-in directive transform.
  4197. const { props, needRuntime } = directiveTransform(prop, node, context);
  4198. !ssr && props.forEach(analyzePatchFlag);
  4199. if (isVOn && arg && !isStaticExp(arg)) {
  4200. pushMergeArg(createObjectExpression(props, elementLoc));
  4201. }
  4202. else {
  4203. properties.push(...props);
  4204. }
  4205. if (needRuntime) {
  4206. runtimeDirectives.push(prop);
  4207. if (isSymbol(needRuntime)) {
  4208. directiveImportMap.set(prop, needRuntime);
  4209. }
  4210. }
  4211. }
  4212. else if (!isBuiltInDirective(name)) {
  4213. // no built-in transform, this is a user custom directive.
  4214. runtimeDirectives.push(prop);
  4215. // custom dirs may use beforeUpdate so they need to force blocks
  4216. // to ensure before-update gets called before children update
  4217. if (hasChildren) {
  4218. shouldUseBlock = true;
  4219. }
  4220. }
  4221. }
  4222. }
  4223. let propsExpression = undefined;
  4224. // has v-bind="object" or v-on="object", wrap with mergeProps
  4225. if (mergeArgs.length) {
  4226. // close up any not-yet-merged props
  4227. pushMergeArg();
  4228. if (mergeArgs.length > 1) {
  4229. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  4230. }
  4231. else {
  4232. // single v-bind with nothing else - no need for a mergeProps call
  4233. propsExpression = mergeArgs[0];
  4234. }
  4235. }
  4236. else if (properties.length) {
  4237. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  4238. }
  4239. // patchFlag analysis
  4240. if (hasDynamicKeys) {
  4241. patchFlag |= 16 /* PatchFlags.FULL_PROPS */;
  4242. }
  4243. else {
  4244. if (hasClassBinding && !isComponent) {
  4245. patchFlag |= 2 /* PatchFlags.CLASS */;
  4246. }
  4247. if (hasStyleBinding && !isComponent) {
  4248. patchFlag |= 4 /* PatchFlags.STYLE */;
  4249. }
  4250. if (dynamicPropNames.length) {
  4251. patchFlag |= 8 /* PatchFlags.PROPS */;
  4252. }
  4253. if (hasHydrationEventBinding) {
  4254. patchFlag |= 32 /* PatchFlags.HYDRATE_EVENTS */;
  4255. }
  4256. }
  4257. if (!shouldUseBlock &&
  4258. (patchFlag === 0 || patchFlag === 32 /* PatchFlags.HYDRATE_EVENTS */) &&
  4259. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  4260. patchFlag |= 512 /* PatchFlags.NEED_PATCH */;
  4261. }
  4262. // pre-normalize props, SSR is skipped for now
  4263. if (!context.inSSR && propsExpression) {
  4264. switch (propsExpression.type) {
  4265. case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
  4266. // means that there is no v-bind,
  4267. // but still need to deal with dynamic key binding
  4268. let classKeyIndex = -1;
  4269. let styleKeyIndex = -1;
  4270. let hasDynamicKey = false;
  4271. for (let i = 0; i < propsExpression.properties.length; i++) {
  4272. const key = propsExpression.properties[i].key;
  4273. if (isStaticExp(key)) {
  4274. if (key.content === 'class') {
  4275. classKeyIndex = i;
  4276. }
  4277. else if (key.content === 'style') {
  4278. styleKeyIndex = i;
  4279. }
  4280. }
  4281. else if (!key.isHandlerKey) {
  4282. hasDynamicKey = true;
  4283. }
  4284. }
  4285. const classProp = propsExpression.properties[classKeyIndex];
  4286. const styleProp = propsExpression.properties[styleKeyIndex];
  4287. // no dynamic key
  4288. if (!hasDynamicKey) {
  4289. if (classProp && !isStaticExp(classProp.value)) {
  4290. classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
  4291. }
  4292. if (styleProp &&
  4293. // the static style is compiled into an object,
  4294. // so use `hasStyleBinding` to ensure that it is a dynamic style binding
  4295. (hasStyleBinding ||
  4296. (styleProp.value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  4297. styleProp.value.content.trim()[0] === `[`) ||
  4298. // v-bind:style and style both exist,
  4299. // v-bind:style with static literal object
  4300. styleProp.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */)) {
  4301. styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
  4302. }
  4303. }
  4304. else {
  4305. // dynamic key binding, wrap with `normalizeProps`
  4306. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
  4307. }
  4308. break;
  4309. case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
  4310. // mergeProps call, do nothing
  4311. break;
  4312. default:
  4313. // single v-bind
  4314. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
  4315. createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
  4316. propsExpression
  4317. ])
  4318. ]);
  4319. break;
  4320. }
  4321. }
  4322. return {
  4323. props: propsExpression,
  4324. directives: runtimeDirectives,
  4325. patchFlag,
  4326. dynamicPropNames,
  4327. shouldUseBlock
  4328. };
  4329. }
  4330. // Dedupe props in an object literal.
  4331. // Literal duplicated attributes would have been warned during the parse phase,
  4332. // however, it's possible to encounter duplicated `onXXX` handlers with different
  4333. // modifiers. We also need to merge static and dynamic class / style attributes.
  4334. // - onXXX handlers / style: merge into array
  4335. // - class: merge into single expression with concatenation
  4336. function dedupeProperties(properties) {
  4337. const knownProps = new Map();
  4338. const deduped = [];
  4339. for (let i = 0; i < properties.length; i++) {
  4340. const prop = properties[i];
  4341. // dynamic keys are always allowed
  4342. if (prop.key.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  4343. deduped.push(prop);
  4344. continue;
  4345. }
  4346. const name = prop.key.content;
  4347. const existing = knownProps.get(name);
  4348. if (existing) {
  4349. if (name === 'style' || name === 'class' || isOn(name)) {
  4350. mergeAsArray(existing, prop);
  4351. }
  4352. // unexpected duplicate, should have emitted error during parse
  4353. }
  4354. else {
  4355. knownProps.set(name, prop);
  4356. deduped.push(prop);
  4357. }
  4358. }
  4359. return deduped;
  4360. }
  4361. function mergeAsArray(existing, incoming) {
  4362. if (existing.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */) {
  4363. existing.value.elements.push(incoming.value);
  4364. }
  4365. else {
  4366. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  4367. }
  4368. }
  4369. function buildDirectiveArgs(dir, context) {
  4370. const dirArgs = [];
  4371. const runtime = directiveImportMap.get(dir);
  4372. if (runtime) {
  4373. // built-in directive with runtime
  4374. dirArgs.push(context.helperString(runtime));
  4375. }
  4376. else {
  4377. {
  4378. // inject statement for resolving directive
  4379. context.helper(RESOLVE_DIRECTIVE);
  4380. context.directives.add(dir.name);
  4381. dirArgs.push(toValidAssetId(dir.name, `directive`));
  4382. }
  4383. }
  4384. const { loc } = dir;
  4385. if (dir.exp)
  4386. dirArgs.push(dir.exp);
  4387. if (dir.arg) {
  4388. if (!dir.exp) {
  4389. dirArgs.push(`void 0`);
  4390. }
  4391. dirArgs.push(dir.arg);
  4392. }
  4393. if (Object.keys(dir.modifiers).length) {
  4394. if (!dir.arg) {
  4395. if (!dir.exp) {
  4396. dirArgs.push(`void 0`);
  4397. }
  4398. dirArgs.push(`void 0`);
  4399. }
  4400. const trueExpression = createSimpleExpression(`true`, false, loc);
  4401. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  4402. }
  4403. return createArrayExpression(dirArgs, dir.loc);
  4404. }
  4405. function stringifyDynamicPropNames(props) {
  4406. let propsNamesString = `[`;
  4407. for (let i = 0, l = props.length; i < l; i++) {
  4408. propsNamesString += JSON.stringify(props[i]);
  4409. if (i < l - 1)
  4410. propsNamesString += ', ';
  4411. }
  4412. return propsNamesString + `]`;
  4413. }
  4414. function isComponentTag(tag) {
  4415. return tag === 'component' || tag === 'Component';
  4416. }
  4417. const transformSlotOutlet = (node, context) => {
  4418. if (isSlotOutlet(node)) {
  4419. const { children, loc } = node;
  4420. const { slotName, slotProps } = processSlotOutlet(node, context);
  4421. const slotArgs = [
  4422. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  4423. slotName,
  4424. '{}',
  4425. 'undefined',
  4426. 'true'
  4427. ];
  4428. let expectedLen = 2;
  4429. if (slotProps) {
  4430. slotArgs[2] = slotProps;
  4431. expectedLen = 3;
  4432. }
  4433. if (children.length) {
  4434. slotArgs[3] = createFunctionExpression([], children, false, false, loc);
  4435. expectedLen = 4;
  4436. }
  4437. if (context.scopeId && !context.slotted) {
  4438. expectedLen = 5;
  4439. }
  4440. slotArgs.splice(expectedLen); // remove unused arguments
  4441. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  4442. }
  4443. };
  4444. function processSlotOutlet(node, context) {
  4445. let slotName = `"default"`;
  4446. let slotProps = undefined;
  4447. const nonNameProps = [];
  4448. for (let i = 0; i < node.props.length; i++) {
  4449. const p = node.props[i];
  4450. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  4451. if (p.value) {
  4452. if (p.name === 'name') {
  4453. slotName = JSON.stringify(p.value.content);
  4454. }
  4455. else {
  4456. p.name = camelize(p.name);
  4457. nonNameProps.push(p);
  4458. }
  4459. }
  4460. }
  4461. else {
  4462. if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
  4463. if (p.exp)
  4464. slotName = p.exp;
  4465. }
  4466. else {
  4467. if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
  4468. p.arg.content = camelize(p.arg.content);
  4469. }
  4470. nonNameProps.push(p);
  4471. }
  4472. }
  4473. }
  4474. if (nonNameProps.length > 0) {
  4475. const { props, directives } = buildProps(node, context, nonNameProps, false, false);
  4476. slotProps = props;
  4477. if (directives.length) {
  4478. context.onError(createCompilerError(36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  4479. }
  4480. }
  4481. return {
  4482. slotName,
  4483. slotProps
  4484. };
  4485. }
  4486. const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*(:[^=]+)?=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
  4487. const transformOn = (dir, node, context, augmentor) => {
  4488. const { loc, modifiers, arg } = dir;
  4489. if (!dir.exp && !modifiers.length) {
  4490. context.onError(createCompilerError(35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
  4491. }
  4492. let eventName;
  4493. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  4494. if (arg.isStatic) {
  4495. let rawName = arg.content;
  4496. // TODO deprecate @vnodeXXX usage
  4497. if (rawName.startsWith('vue:')) {
  4498. rawName = `vnode-${rawName.slice(4)}`;
  4499. }
  4500. const eventString = node.tagType !== 0 /* ElementTypes.ELEMENT */ ||
  4501. rawName.startsWith('vnode') ||
  4502. !/[A-Z]/.test(rawName)
  4503. ? // for non-element and vnode lifecycle event listeners, auto convert
  4504. // it to camelCase. See issue #2249
  4505. toHandlerKey(camelize(rawName))
  4506. : // preserve case for plain element listeners that have uppercase
  4507. // letters, as these may be custom elements' custom events
  4508. `on:${rawName}`;
  4509. eventName = createSimpleExpression(eventString, true, arg.loc);
  4510. }
  4511. else {
  4512. // #2388
  4513. eventName = createCompoundExpression([
  4514. `${context.helperString(TO_HANDLER_KEY)}(`,
  4515. arg,
  4516. `)`
  4517. ]);
  4518. }
  4519. }
  4520. else {
  4521. // already a compound expression.
  4522. eventName = arg;
  4523. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  4524. eventName.children.push(`)`);
  4525. }
  4526. // handler processing
  4527. let exp = dir.exp;
  4528. if (exp && !exp.content.trim()) {
  4529. exp = undefined;
  4530. }
  4531. let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
  4532. if (exp) {
  4533. const isMemberExp = isMemberExpression(exp.content);
  4534. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  4535. const hasMultipleStatements = exp.content.includes(`;`);
  4536. {
  4537. validateBrowserExpression(exp, context, false, hasMultipleStatements);
  4538. }
  4539. if (isInlineStatement || (shouldCache && isMemberExp)) {
  4540. // wrap inline statement in a function expression
  4541. exp = createCompoundExpression([
  4542. `${isInlineStatement
  4543. ? `$event`
  4544. : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  4545. exp,
  4546. hasMultipleStatements ? `}` : `)`
  4547. ]);
  4548. }
  4549. }
  4550. let ret = {
  4551. props: [
  4552. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  4553. ]
  4554. };
  4555. // apply extended compiler augmentor
  4556. if (augmentor) {
  4557. ret = augmentor(ret);
  4558. }
  4559. if (shouldCache) {
  4560. // cache handlers so that it's always the same handler being passed down.
  4561. // this avoids unnecessary re-renders when users use inline handlers on
  4562. // components.
  4563. ret.props[0].value = context.cache(ret.props[0].value);
  4564. }
  4565. // mark the key as handler for props normalization check
  4566. ret.props.forEach(p => (p.key.isHandlerKey = true));
  4567. return ret;
  4568. };
  4569. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  4570. // codegen for the entire props object. This transform here is only for v-bind
  4571. // *with* args.
  4572. const transformBind = (dir, _node, context) => {
  4573. const { exp, modifiers, loc } = dir;
  4574. const arg = dir.arg;
  4575. if (arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  4576. arg.children.unshift(`(`);
  4577. arg.children.push(`) || ""`);
  4578. }
  4579. else if (!arg.isStatic) {
  4580. arg.content = `${arg.content} || ""`;
  4581. }
  4582. // .sync is replaced by v-model:arg
  4583. if (modifiers.includes('camel')) {
  4584. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  4585. if (arg.isStatic) {
  4586. arg.content = camelize(arg.content);
  4587. }
  4588. else {
  4589. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  4590. }
  4591. }
  4592. else {
  4593. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  4594. arg.children.push(`)`);
  4595. }
  4596. }
  4597. if (!context.inSSR) {
  4598. if (modifiers.includes('prop')) {
  4599. injectPrefix(arg, '.');
  4600. }
  4601. if (modifiers.includes('attr')) {
  4602. injectPrefix(arg, '^');
  4603. }
  4604. }
  4605. if (!exp ||
  4606. (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  4607. context.onError(createCompilerError(34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */, loc));
  4608. return {
  4609. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  4610. };
  4611. }
  4612. return {
  4613. props: [createObjectProperty(arg, exp)]
  4614. };
  4615. };
  4616. const injectPrefix = (arg, prefix) => {
  4617. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  4618. if (arg.isStatic) {
  4619. arg.content = prefix + arg.content;
  4620. }
  4621. else {
  4622. arg.content = `\`${prefix}\${${arg.content}}\``;
  4623. }
  4624. }
  4625. else {
  4626. arg.children.unshift(`'${prefix}' + (`);
  4627. arg.children.push(`)`);
  4628. }
  4629. };
  4630. // Merge adjacent text nodes and expressions into a single expression
  4631. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  4632. const transformText = (node, context) => {
  4633. if (node.type === 0 /* NodeTypes.ROOT */ ||
  4634. node.type === 1 /* NodeTypes.ELEMENT */ ||
  4635. node.type === 11 /* NodeTypes.FOR */ ||
  4636. node.type === 10 /* NodeTypes.IF_BRANCH */) {
  4637. // perform the transform on node exit so that all expressions have already
  4638. // been processed.
  4639. return () => {
  4640. const children = node.children;
  4641. let currentContainer = undefined;
  4642. let hasText = false;
  4643. for (let i = 0; i < children.length; i++) {
  4644. const child = children[i];
  4645. if (isText(child)) {
  4646. hasText = true;
  4647. for (let j = i + 1; j < children.length; j++) {
  4648. const next = children[j];
  4649. if (isText(next)) {
  4650. if (!currentContainer) {
  4651. currentContainer = children[i] = createCompoundExpression([child], child.loc);
  4652. }
  4653. // merge adjacent text node into current
  4654. currentContainer.children.push(` + `, next);
  4655. children.splice(j, 1);
  4656. j--;
  4657. }
  4658. else {
  4659. currentContainer = undefined;
  4660. break;
  4661. }
  4662. }
  4663. }
  4664. }
  4665. if (!hasText ||
  4666. // if this is a plain element with a single text child, leave it
  4667. // as-is since the runtime has dedicated fast path for this by directly
  4668. // setting textContent of the element.
  4669. // for component root it's always normalized anyway.
  4670. (children.length === 1 &&
  4671. (node.type === 0 /* NodeTypes.ROOT */ ||
  4672. (node.type === 1 /* NodeTypes.ELEMENT */ &&
  4673. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  4674. // #3756
  4675. // custom directives can potentially add DOM elements arbitrarily,
  4676. // we need to avoid setting textContent of the element at runtime
  4677. // to avoid accidentally overwriting the DOM elements added
  4678. // by the user through custom directives.
  4679. !node.props.find(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  4680. !context.directiveTransforms[p.name]) &&
  4681. // in compat mode, <template> tags with no special directives
  4682. // will be rendered as a fragment so its children must be
  4683. // converted into vnodes.
  4684. !(node.tag === 'template'))))) {
  4685. return;
  4686. }
  4687. // pre-convert text nodes into createTextVNode(text) calls to avoid
  4688. // runtime normalization.
  4689. for (let i = 0; i < children.length; i++) {
  4690. const child = children[i];
  4691. if (isText(child) || child.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  4692. const callArgs = [];
  4693. // createTextVNode defaults to single whitespace, so if it is a
  4694. // single space the code could be an empty call to save bytes.
  4695. if (child.type !== 2 /* NodeTypes.TEXT */ || child.content !== ' ') {
  4696. callArgs.push(child);
  4697. }
  4698. // mark dynamic text with flag so it gets patched inside a block
  4699. if (!context.ssr &&
  4700. getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
  4701. callArgs.push(1 /* PatchFlags.TEXT */ +
  4702. (` /* ${PatchFlagNames[1 /* PatchFlags.TEXT */]} */` ));
  4703. }
  4704. children[i] = {
  4705. type: 12 /* NodeTypes.TEXT_CALL */,
  4706. content: child,
  4707. loc: child.loc,
  4708. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  4709. };
  4710. }
  4711. }
  4712. };
  4713. }
  4714. };
  4715. const seen = new WeakSet();
  4716. const transformOnce = (node, context) => {
  4717. if (node.type === 1 /* NodeTypes.ELEMENT */ && findDir(node, 'once', true)) {
  4718. if (seen.has(node) || context.inVOnce) {
  4719. return;
  4720. }
  4721. seen.add(node);
  4722. context.inVOnce = true;
  4723. context.helper(SET_BLOCK_TRACKING);
  4724. return () => {
  4725. context.inVOnce = false;
  4726. const cur = context.currentNode;
  4727. if (cur.codegenNode) {
  4728. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  4729. }
  4730. };
  4731. }
  4732. };
  4733. const transformModel = (dir, node, context) => {
  4734. const { exp, arg } = dir;
  4735. if (!exp) {
  4736. context.onError(createCompilerError(41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */, dir.loc));
  4737. return createTransformProps();
  4738. }
  4739. const rawExp = exp.loc.source;
  4740. const expString = exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ? exp.content : rawExp;
  4741. // im SFC <script setup> inline mode, the exp may have been transformed into
  4742. // _unref(exp)
  4743. const bindingType = context.bindingMetadata[rawExp];
  4744. // check props
  4745. if (bindingType === "props" /* BindingTypes.PROPS */ ||
  4746. bindingType === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
  4747. context.onError(createCompilerError(44 /* ErrorCodes.X_V_MODEL_ON_PROPS */, exp.loc));
  4748. return createTransformProps();
  4749. }
  4750. const maybeRef = !true ;
  4751. if (!expString.trim() ||
  4752. (!isMemberExpression(expString) && !maybeRef)) {
  4753. context.onError(createCompilerError(42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  4754. return createTransformProps();
  4755. }
  4756. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  4757. const eventName = arg
  4758. ? isStaticExp(arg)
  4759. ? `onUpdate:${arg.content}`
  4760. : createCompoundExpression(['"onUpdate:" + ', arg])
  4761. : `onUpdate:modelValue`;
  4762. let assignmentExp;
  4763. const eventArg = context.isTS ? `($event: any)` : `$event`;
  4764. {
  4765. assignmentExp = createCompoundExpression([
  4766. `${eventArg} => ((`,
  4767. exp,
  4768. `) = $event)`
  4769. ]);
  4770. }
  4771. const props = [
  4772. // modelValue: foo
  4773. createObjectProperty(propName, dir.exp),
  4774. // "onUpdate:modelValue": $event => (foo = $event)
  4775. createObjectProperty(eventName, assignmentExp)
  4776. ];
  4777. // modelModifiers: { foo: true, "bar-baz": true }
  4778. if (dir.modifiers.length && node.tagType === 1 /* ElementTypes.COMPONENT */) {
  4779. const modifiers = dir.modifiers
  4780. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  4781. .join(`, `);
  4782. const modifiersKey = arg
  4783. ? isStaticExp(arg)
  4784. ? `${arg.content}Modifiers`
  4785. : createCompoundExpression([arg, ' + "Modifiers"'])
  4786. : `modelModifiers`;
  4787. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* ConstantTypes.CAN_HOIST */)));
  4788. }
  4789. return createTransformProps(props);
  4790. };
  4791. function createTransformProps(props = []) {
  4792. return { props };
  4793. }
  4794. const validDivisionCharRE = /[\w).+\-_$\]]/;
  4795. const transformFilter = (node, context) => {
  4796. if (!isCompatEnabled("COMPILER_FILTER" /* CompilerDeprecationTypes.COMPILER_FILTERS */, context)) {
  4797. return;
  4798. }
  4799. if (node.type === 5 /* NodeTypes.INTERPOLATION */) {
  4800. // filter rewrite is applied before expression transform so only
  4801. // simple expressions are possible at this stage
  4802. rewriteFilter(node.content, context);
  4803. }
  4804. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  4805. node.props.forEach((prop) => {
  4806. if (prop.type === 7 /* NodeTypes.DIRECTIVE */ &&
  4807. prop.name !== 'for' &&
  4808. prop.exp) {
  4809. rewriteFilter(prop.exp, context);
  4810. }
  4811. });
  4812. }
  4813. };
  4814. function rewriteFilter(node, context) {
  4815. if (node.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  4816. parseFilter(node, context);
  4817. }
  4818. else {
  4819. for (let i = 0; i < node.children.length; i++) {
  4820. const child = node.children[i];
  4821. if (typeof child !== 'object')
  4822. continue;
  4823. if (child.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  4824. parseFilter(child, context);
  4825. }
  4826. else if (child.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  4827. rewriteFilter(node, context);
  4828. }
  4829. else if (child.type === 5 /* NodeTypes.INTERPOLATION */) {
  4830. rewriteFilter(child.content, context);
  4831. }
  4832. }
  4833. }
  4834. }
  4835. function parseFilter(node, context) {
  4836. const exp = node.content;
  4837. let inSingle = false;
  4838. let inDouble = false;
  4839. let inTemplateString = false;
  4840. let inRegex = false;
  4841. let curly = 0;
  4842. let square = 0;
  4843. let paren = 0;
  4844. let lastFilterIndex = 0;
  4845. let c, prev, i, expression, filters = [];
  4846. for (i = 0; i < exp.length; i++) {
  4847. prev = c;
  4848. c = exp.charCodeAt(i);
  4849. if (inSingle) {
  4850. if (c === 0x27 && prev !== 0x5c)
  4851. inSingle = false;
  4852. }
  4853. else if (inDouble) {
  4854. if (c === 0x22 && prev !== 0x5c)
  4855. inDouble = false;
  4856. }
  4857. else if (inTemplateString) {
  4858. if (c === 0x60 && prev !== 0x5c)
  4859. inTemplateString = false;
  4860. }
  4861. else if (inRegex) {
  4862. if (c === 0x2f && prev !== 0x5c)
  4863. inRegex = false;
  4864. }
  4865. else if (c === 0x7c && // pipe
  4866. exp.charCodeAt(i + 1) !== 0x7c &&
  4867. exp.charCodeAt(i - 1) !== 0x7c &&
  4868. !curly &&
  4869. !square &&
  4870. !paren) {
  4871. if (expression === undefined) {
  4872. // first filter, end of expression
  4873. lastFilterIndex = i + 1;
  4874. expression = exp.slice(0, i).trim();
  4875. }
  4876. else {
  4877. pushFilter();
  4878. }
  4879. }
  4880. else {
  4881. switch (c) {
  4882. case 0x22:
  4883. inDouble = true;
  4884. break; // "
  4885. case 0x27:
  4886. inSingle = true;
  4887. break; // '
  4888. case 0x60:
  4889. inTemplateString = true;
  4890. break; // `
  4891. case 0x28:
  4892. paren++;
  4893. break; // (
  4894. case 0x29:
  4895. paren--;
  4896. break; // )
  4897. case 0x5b:
  4898. square++;
  4899. break; // [
  4900. case 0x5d:
  4901. square--;
  4902. break; // ]
  4903. case 0x7b:
  4904. curly++;
  4905. break; // {
  4906. case 0x7d:
  4907. curly--;
  4908. break; // }
  4909. }
  4910. if (c === 0x2f) {
  4911. // /
  4912. let j = i - 1;
  4913. let p;
  4914. // find first non-whitespace prev char
  4915. for (; j >= 0; j--) {
  4916. p = exp.charAt(j);
  4917. if (p !== ' ')
  4918. break;
  4919. }
  4920. if (!p || !validDivisionCharRE.test(p)) {
  4921. inRegex = true;
  4922. }
  4923. }
  4924. }
  4925. }
  4926. if (expression === undefined) {
  4927. expression = exp.slice(0, i).trim();
  4928. }
  4929. else if (lastFilterIndex !== 0) {
  4930. pushFilter();
  4931. }
  4932. function pushFilter() {
  4933. filters.push(exp.slice(lastFilterIndex, i).trim());
  4934. lastFilterIndex = i + 1;
  4935. }
  4936. if (filters.length) {
  4937. warnDeprecation("COMPILER_FILTER" /* CompilerDeprecationTypes.COMPILER_FILTERS */, context, node.loc);
  4938. for (i = 0; i < filters.length; i++) {
  4939. expression = wrapFilter(expression, filters[i], context);
  4940. }
  4941. node.content = expression;
  4942. }
  4943. }
  4944. function wrapFilter(exp, filter, context) {
  4945. context.helper(RESOLVE_FILTER);
  4946. const i = filter.indexOf('(');
  4947. if (i < 0) {
  4948. context.filters.add(filter);
  4949. return `${toValidAssetId(filter, 'filter')}(${exp})`;
  4950. }
  4951. else {
  4952. const name = filter.slice(0, i);
  4953. const args = filter.slice(i + 1);
  4954. context.filters.add(name);
  4955. return `${toValidAssetId(name, 'filter')}(${exp}${args !== ')' ? ',' + args : args}`;
  4956. }
  4957. }
  4958. const seen$1 = new WeakSet();
  4959. const transformMemo = (node, context) => {
  4960. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  4961. const dir = findDir(node, 'memo');
  4962. if (!dir || seen$1.has(node)) {
  4963. return;
  4964. }
  4965. seen$1.add(node);
  4966. return () => {
  4967. const codegenNode = node.codegenNode ||
  4968. context.currentNode.codegenNode;
  4969. if (codegenNode && codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  4970. // non-component sub tree should be turned into a block
  4971. if (node.tagType !== 1 /* ElementTypes.COMPONENT */) {
  4972. makeBlock(codegenNode, context);
  4973. }
  4974. node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
  4975. dir.exp,
  4976. createFunctionExpression(undefined, codegenNode),
  4977. `_cache`,
  4978. String(context.cached++)
  4979. ]);
  4980. }
  4981. };
  4982. }
  4983. };
  4984. function getBaseTransformPreset(prefixIdentifiers) {
  4985. return [
  4986. [
  4987. transformOnce,
  4988. transformIf,
  4989. transformMemo,
  4990. transformFor,
  4991. ...([transformFilter] ),
  4992. ...([transformExpression]
  4993. ),
  4994. transformSlotOutlet,
  4995. transformElement,
  4996. trackSlotScopes,
  4997. transformText
  4998. ],
  4999. {
  5000. on: transformOn,
  5001. bind: transformBind,
  5002. model: transformModel
  5003. }
  5004. ];
  5005. }
  5006. // we name it `baseCompile` so that higher order compilers like
  5007. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  5008. function baseCompile(template, options = {}) {
  5009. const onError = options.onError || defaultOnError;
  5010. const isModuleMode = options.mode === 'module';
  5011. /* istanbul ignore if */
  5012. {
  5013. if (options.prefixIdentifiers === true) {
  5014. onError(createCompilerError(47 /* ErrorCodes.X_PREFIX_ID_NOT_SUPPORTED */));
  5015. }
  5016. else if (isModuleMode) {
  5017. onError(createCompilerError(48 /* ErrorCodes.X_MODULE_MODE_NOT_SUPPORTED */));
  5018. }
  5019. }
  5020. const prefixIdentifiers = !true ;
  5021. if (options.cacheHandlers) {
  5022. onError(createCompilerError(49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */));
  5023. }
  5024. if (options.scopeId && !isModuleMode) {
  5025. onError(createCompilerError(50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */));
  5026. }
  5027. const ast = isString(template) ? baseParse(template, options) : template;
  5028. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
  5029. transform(ast, extend({}, options, {
  5030. prefixIdentifiers,
  5031. nodeTransforms: [
  5032. ...nodeTransforms,
  5033. ...(options.nodeTransforms || []) // user transforms
  5034. ],
  5035. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  5036. )
  5037. }));
  5038. return generate(ast, extend({}, options, {
  5039. prefixIdentifiers
  5040. }));
  5041. }
  5042. const noopDirectiveTransform = () => ({ props: [] });
  5043. const V_MODEL_RADIO = Symbol(`vModelRadio` );
  5044. const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
  5045. const V_MODEL_TEXT = Symbol(`vModelText` );
  5046. const V_MODEL_SELECT = Symbol(`vModelSelect` );
  5047. const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
  5048. const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
  5049. const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
  5050. const V_SHOW = Symbol(`vShow` );
  5051. const TRANSITION = Symbol(`Transition` );
  5052. const TRANSITION_GROUP = Symbol(`TransitionGroup` );
  5053. registerRuntimeHelpers({
  5054. [V_MODEL_RADIO]: `vModelRadio`,
  5055. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  5056. [V_MODEL_TEXT]: `vModelText`,
  5057. [V_MODEL_SELECT]: `vModelSelect`,
  5058. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  5059. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  5060. [V_ON_WITH_KEYS]: `withKeys`,
  5061. [V_SHOW]: `vShow`,
  5062. [TRANSITION]: `Transition`,
  5063. [TRANSITION_GROUP]: `TransitionGroup`
  5064. });
  5065. /* eslint-disable no-restricted-globals */
  5066. let decoder;
  5067. function decodeHtmlBrowser(raw, asAttr = false) {
  5068. if (!decoder) {
  5069. decoder = document.createElement('div');
  5070. }
  5071. if (asAttr) {
  5072. decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
  5073. return decoder.children[0].getAttribute('foo');
  5074. }
  5075. else {
  5076. decoder.innerHTML = raw;
  5077. return decoder.textContent;
  5078. }
  5079. }
  5080. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  5081. const parserOptions = {
  5082. isVoidTag,
  5083. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  5084. isPreTag: tag => tag === 'pre',
  5085. decodeEntities: decodeHtmlBrowser ,
  5086. isBuiltInComponent: (tag) => {
  5087. if (isBuiltInType(tag, `Transition`)) {
  5088. return TRANSITION;
  5089. }
  5090. else if (isBuiltInType(tag, `TransitionGroup`)) {
  5091. return TRANSITION_GROUP;
  5092. }
  5093. },
  5094. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  5095. getNamespace(tag, parent) {
  5096. let ns = parent ? parent.ns : 0 /* DOMNamespaces.HTML */;
  5097. if (parent && ns === 2 /* DOMNamespaces.MATH_ML */) {
  5098. if (parent.tag === 'annotation-xml') {
  5099. if (tag === 'svg') {
  5100. return 1 /* DOMNamespaces.SVG */;
  5101. }
  5102. if (parent.props.some(a => a.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  5103. a.name === 'encoding' &&
  5104. a.value != null &&
  5105. (a.value.content === 'text/html' ||
  5106. a.value.content === 'application/xhtml+xml'))) {
  5107. ns = 0 /* DOMNamespaces.HTML */;
  5108. }
  5109. }
  5110. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  5111. tag !== 'mglyph' &&
  5112. tag !== 'malignmark') {
  5113. ns = 0 /* DOMNamespaces.HTML */;
  5114. }
  5115. }
  5116. else if (parent && ns === 1 /* DOMNamespaces.SVG */) {
  5117. if (parent.tag === 'foreignObject' ||
  5118. parent.tag === 'desc' ||
  5119. parent.tag === 'title') {
  5120. ns = 0 /* DOMNamespaces.HTML */;
  5121. }
  5122. }
  5123. if (ns === 0 /* DOMNamespaces.HTML */) {
  5124. if (tag === 'svg') {
  5125. return 1 /* DOMNamespaces.SVG */;
  5126. }
  5127. if (tag === 'math') {
  5128. return 2 /* DOMNamespaces.MATH_ML */;
  5129. }
  5130. }
  5131. return ns;
  5132. },
  5133. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  5134. getTextMode({ tag, ns }) {
  5135. if (ns === 0 /* DOMNamespaces.HTML */) {
  5136. if (tag === 'textarea' || tag === 'title') {
  5137. return 1 /* TextModes.RCDATA */;
  5138. }
  5139. if (isRawTextContainer(tag)) {
  5140. return 2 /* TextModes.RAWTEXT */;
  5141. }
  5142. }
  5143. return 0 /* TextModes.DATA */;
  5144. }
  5145. };
  5146. // Parse inline CSS strings for static style attributes into an object.
  5147. // This is a NodeTransform since it works on the static `style` attribute and
  5148. // converts it into a dynamic equivalent:
  5149. // style="color: red" -> :style='{ "color": "red" }'
  5150. // It is then processed by `transformElement` and included in the generated
  5151. // props.
  5152. const transformStyle = node => {
  5153. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  5154. node.props.forEach((p, i) => {
  5155. if (p.type === 6 /* NodeTypes.ATTRIBUTE */ && p.name === 'style' && p.value) {
  5156. // replace p with an expression node
  5157. node.props[i] = {
  5158. type: 7 /* NodeTypes.DIRECTIVE */,
  5159. name: `bind`,
  5160. arg: createSimpleExpression(`style`, true, p.loc),
  5161. exp: parseInlineCSS(p.value.content, p.loc),
  5162. modifiers: [],
  5163. loc: p.loc
  5164. };
  5165. }
  5166. });
  5167. }
  5168. };
  5169. const parseInlineCSS = (cssText, loc) => {
  5170. const normalized = parseStringStyle(cssText);
  5171. return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  5172. };
  5173. function createDOMCompilerError(code, loc) {
  5174. return createCompilerError(code, loc, DOMErrorMessages );
  5175. }
  5176. const DOMErrorMessages = {
  5177. [51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  5178. [52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  5179. [53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  5180. [54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  5181. [55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  5182. [56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  5183. [57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
  5184. [58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  5185. [59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  5186. [60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  5187. [61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  5188. };
  5189. const transformVHtml = (dir, node, context) => {
  5190. const { exp, loc } = dir;
  5191. if (!exp) {
  5192. context.onError(createDOMCompilerError(51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */, loc));
  5193. }
  5194. if (node.children.length) {
  5195. context.onError(createDOMCompilerError(52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */, loc));
  5196. node.children.length = 0;
  5197. }
  5198. return {
  5199. props: [
  5200. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  5201. ]
  5202. };
  5203. };
  5204. const transformVText = (dir, node, context) => {
  5205. const { exp, loc } = dir;
  5206. if (!exp) {
  5207. context.onError(createDOMCompilerError(53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */, loc));
  5208. }
  5209. if (node.children.length) {
  5210. context.onError(createDOMCompilerError(54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */, loc));
  5211. node.children.length = 0;
  5212. }
  5213. return {
  5214. props: [
  5215. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  5216. ? getConstantType(exp, context) > 0
  5217. ? exp
  5218. : createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  5219. : createSimpleExpression('', true))
  5220. ]
  5221. };
  5222. };
  5223. const transformModel$1 = (dir, node, context) => {
  5224. const baseResult = transformModel(dir, node, context);
  5225. // base transform has errors OR component v-model (only need props)
  5226. if (!baseResult.props.length || node.tagType === 1 /* ElementTypes.COMPONENT */) {
  5227. return baseResult;
  5228. }
  5229. if (dir.arg) {
  5230. context.onError(createDOMCompilerError(56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  5231. }
  5232. function checkDuplicatedValue() {
  5233. const value = findProp(node, 'value');
  5234. if (value) {
  5235. context.onError(createDOMCompilerError(58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  5236. }
  5237. }
  5238. const { tag } = node;
  5239. const isCustomElement = context.isCustomElement(tag);
  5240. if (tag === 'input' ||
  5241. tag === 'textarea' ||
  5242. tag === 'select' ||
  5243. isCustomElement) {
  5244. let directiveToUse = V_MODEL_TEXT;
  5245. let isInvalidType = false;
  5246. if (tag === 'input' || isCustomElement) {
  5247. const type = findProp(node, `type`);
  5248. if (type) {
  5249. if (type.type === 7 /* NodeTypes.DIRECTIVE */) {
  5250. // :type="foo"
  5251. directiveToUse = V_MODEL_DYNAMIC;
  5252. }
  5253. else if (type.value) {
  5254. switch (type.value.content) {
  5255. case 'radio':
  5256. directiveToUse = V_MODEL_RADIO;
  5257. break;
  5258. case 'checkbox':
  5259. directiveToUse = V_MODEL_CHECKBOX;
  5260. break;
  5261. case 'file':
  5262. isInvalidType = true;
  5263. context.onError(createDOMCompilerError(57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  5264. break;
  5265. default:
  5266. // text type
  5267. checkDuplicatedValue();
  5268. break;
  5269. }
  5270. }
  5271. }
  5272. else if (hasDynamicKeyVBind(node)) {
  5273. // element has bindings with dynamic keys, which can possibly contain
  5274. // "type".
  5275. directiveToUse = V_MODEL_DYNAMIC;
  5276. }
  5277. else {
  5278. // text type
  5279. checkDuplicatedValue();
  5280. }
  5281. }
  5282. else if (tag === 'select') {
  5283. directiveToUse = V_MODEL_SELECT;
  5284. }
  5285. else {
  5286. // textarea
  5287. checkDuplicatedValue();
  5288. }
  5289. // inject runtime directive
  5290. // by returning the helper symbol via needRuntime
  5291. // the import will replaced a resolveDirective call.
  5292. if (!isInvalidType) {
  5293. baseResult.needRuntime = context.helper(directiveToUse);
  5294. }
  5295. }
  5296. else {
  5297. context.onError(createDOMCompilerError(55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  5298. }
  5299. // native vmodel doesn't need the `modelValue` props since they are also
  5300. // passed to the runtime as `binding.value`. removing it reduces code size.
  5301. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  5302. p.key.content === 'modelValue'));
  5303. return baseResult;
  5304. };
  5305. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  5306. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  5307. // event propagation management
  5308. `stop,prevent,self,` +
  5309. // system modifiers + exact
  5310. `ctrl,shift,alt,meta,exact,` +
  5311. // mouse
  5312. `middle`);
  5313. // left & right could be mouse or key modifiers based on event type
  5314. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  5315. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  5316. const resolveModifiers = (key, modifiers, context, loc) => {
  5317. const keyModifiers = [];
  5318. const nonKeyModifiers = [];
  5319. const eventOptionModifiers = [];
  5320. for (let i = 0; i < modifiers.length; i++) {
  5321. const modifier = modifiers[i];
  5322. if (modifier === 'native' &&
  5323. checkCompatEnabled("COMPILER_V_ON_NATIVE" /* CompilerDeprecationTypes.COMPILER_V_ON_NATIVE */, context, loc)) {
  5324. eventOptionModifiers.push(modifier);
  5325. }
  5326. else if (isEventOptionModifier(modifier)) {
  5327. // eventOptionModifiers: modifiers for addEventListener() options,
  5328. // e.g. .passive & .capture
  5329. eventOptionModifiers.push(modifier);
  5330. }
  5331. else {
  5332. // runtimeModifiers: modifiers that needs runtime guards
  5333. if (maybeKeyModifier(modifier)) {
  5334. if (isStaticExp(key)) {
  5335. if (isKeyboardEvent(key.content)) {
  5336. keyModifiers.push(modifier);
  5337. }
  5338. else {
  5339. nonKeyModifiers.push(modifier);
  5340. }
  5341. }
  5342. else {
  5343. keyModifiers.push(modifier);
  5344. nonKeyModifiers.push(modifier);
  5345. }
  5346. }
  5347. else {
  5348. if (isNonKeyModifier(modifier)) {
  5349. nonKeyModifiers.push(modifier);
  5350. }
  5351. else {
  5352. keyModifiers.push(modifier);
  5353. }
  5354. }
  5355. }
  5356. }
  5357. return {
  5358. keyModifiers,
  5359. nonKeyModifiers,
  5360. eventOptionModifiers
  5361. };
  5362. };
  5363. const transformClick = (key, event) => {
  5364. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  5365. return isStaticClick
  5366. ? createSimpleExpression(event, true)
  5367. : key.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */
  5368. ? createCompoundExpression([
  5369. `(`,
  5370. key,
  5371. `) === "onClick" ? "${event}" : (`,
  5372. key,
  5373. `)`
  5374. ])
  5375. : key;
  5376. };
  5377. const transformOn$1 = (dir, node, context) => {
  5378. return transformOn(dir, node, context, baseResult => {
  5379. const { modifiers } = dir;
  5380. if (!modifiers.length)
  5381. return baseResult;
  5382. let { key, value: handlerExp } = baseResult.props[0];
  5383. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
  5384. // normalize click.right and click.middle since they don't actually fire
  5385. if (nonKeyModifiers.includes('right')) {
  5386. key = transformClick(key, `onContextmenu`);
  5387. }
  5388. if (nonKeyModifiers.includes('middle')) {
  5389. key = transformClick(key, `onMouseup`);
  5390. }
  5391. if (nonKeyModifiers.length) {
  5392. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  5393. handlerExp,
  5394. JSON.stringify(nonKeyModifiers)
  5395. ]);
  5396. }
  5397. if (keyModifiers.length &&
  5398. // if event name is dynamic, always wrap with keys guard
  5399. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  5400. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  5401. handlerExp,
  5402. JSON.stringify(keyModifiers)
  5403. ]);
  5404. }
  5405. if (eventOptionModifiers.length) {
  5406. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  5407. key = isStaticExp(key)
  5408. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  5409. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  5410. }
  5411. return {
  5412. props: [createObjectProperty(key, handlerExp)]
  5413. };
  5414. });
  5415. };
  5416. const transformShow = (dir, node, context) => {
  5417. const { exp, loc } = dir;
  5418. if (!exp) {
  5419. context.onError(createDOMCompilerError(59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */, loc));
  5420. }
  5421. return {
  5422. props: [],
  5423. needRuntime: context.helper(V_SHOW)
  5424. };
  5425. };
  5426. const transformTransition = (node, context) => {
  5427. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  5428. node.tagType === 1 /* ElementTypes.COMPONENT */) {
  5429. const component = context.isBuiltInComponent(node.tag);
  5430. if (component === TRANSITION) {
  5431. return () => {
  5432. if (!node.children.length) {
  5433. return;
  5434. }
  5435. // warn multiple transition children
  5436. if (hasMultipleChildren(node)) {
  5437. context.onError(createDOMCompilerError(60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */, {
  5438. start: node.children[0].loc.start,
  5439. end: node.children[node.children.length - 1].loc.end,
  5440. source: ''
  5441. }));
  5442. }
  5443. // check if it's s single child w/ v-show
  5444. // if yes, inject "persisted: true" to the transition props
  5445. const child = node.children[0];
  5446. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  5447. for (const p of child.props) {
  5448. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'show') {
  5449. node.props.push({
  5450. type: 6 /* NodeTypes.ATTRIBUTE */,
  5451. name: 'persisted',
  5452. value: undefined,
  5453. loc: node.loc
  5454. });
  5455. }
  5456. }
  5457. }
  5458. };
  5459. }
  5460. }
  5461. };
  5462. function hasMultipleChildren(node) {
  5463. // #1352 filter out potential comment nodes.
  5464. const children = (node.children = node.children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */ &&
  5465. !(c.type === 2 /* NodeTypes.TEXT */ && !c.content.trim())));
  5466. const child = children[0];
  5467. return (children.length !== 1 ||
  5468. child.type === 11 /* NodeTypes.FOR */ ||
  5469. (child.type === 9 /* NodeTypes.IF */ && child.branches.some(hasMultipleChildren)));
  5470. }
  5471. const ignoreSideEffectTags = (node, context) => {
  5472. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  5473. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  5474. (node.tag === 'script' || node.tag === 'style')) {
  5475. context.onError(createDOMCompilerError(61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  5476. context.removeNode();
  5477. }
  5478. };
  5479. const DOMNodeTransforms = [
  5480. transformStyle,
  5481. ...([transformTransition] )
  5482. ];
  5483. const DOMDirectiveTransforms = {
  5484. cloak: noopDirectiveTransform,
  5485. html: transformVHtml,
  5486. text: transformVText,
  5487. model: transformModel$1,
  5488. on: transformOn$1,
  5489. show: transformShow
  5490. };
  5491. function compile(template, options = {}) {
  5492. return baseCompile(template, extend({}, parserOptions, options, {
  5493. nodeTransforms: [
  5494. // ignore <script> and <tag>
  5495. // this is not put inside DOMNodeTransforms because that list is used
  5496. // by compiler-ssr to generate vnode fallback branches
  5497. ignoreSideEffectTags,
  5498. ...DOMNodeTransforms,
  5499. ...(options.nodeTransforms || [])
  5500. ],
  5501. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  5502. transformHoist: null
  5503. }));
  5504. }
  5505. function parse(template, options = {}) {
  5506. return baseParse(template, extend({}, parserOptions, options));
  5507. }
  5508. exports.BASE_TRANSITION = BASE_TRANSITION;
  5509. exports.CAMELIZE = CAMELIZE;
  5510. exports.CAPITALIZE = CAPITALIZE;
  5511. exports.CREATE_BLOCK = CREATE_BLOCK;
  5512. exports.CREATE_COMMENT = CREATE_COMMENT;
  5513. exports.CREATE_ELEMENT_BLOCK = CREATE_ELEMENT_BLOCK;
  5514. exports.CREATE_ELEMENT_VNODE = CREATE_ELEMENT_VNODE;
  5515. exports.CREATE_SLOTS = CREATE_SLOTS;
  5516. exports.CREATE_STATIC = CREATE_STATIC;
  5517. exports.CREATE_TEXT = CREATE_TEXT;
  5518. exports.CREATE_VNODE = CREATE_VNODE;
  5519. exports.DOMDirectiveTransforms = DOMDirectiveTransforms;
  5520. exports.DOMNodeTransforms = DOMNodeTransforms;
  5521. exports.FRAGMENT = FRAGMENT;
  5522. exports.GUARD_REACTIVE_PROPS = GUARD_REACTIVE_PROPS;
  5523. exports.IS_MEMO_SAME = IS_MEMO_SAME;
  5524. exports.IS_REF = IS_REF;
  5525. exports.KEEP_ALIVE = KEEP_ALIVE;
  5526. exports.MERGE_PROPS = MERGE_PROPS;
  5527. exports.NORMALIZE_CLASS = NORMALIZE_CLASS;
  5528. exports.NORMALIZE_PROPS = NORMALIZE_PROPS;
  5529. exports.NORMALIZE_STYLE = NORMALIZE_STYLE;
  5530. exports.OPEN_BLOCK = OPEN_BLOCK;
  5531. exports.POP_SCOPE_ID = POP_SCOPE_ID;
  5532. exports.PUSH_SCOPE_ID = PUSH_SCOPE_ID;
  5533. exports.RENDER_LIST = RENDER_LIST;
  5534. exports.RENDER_SLOT = RENDER_SLOT;
  5535. exports.RESOLVE_COMPONENT = RESOLVE_COMPONENT;
  5536. exports.RESOLVE_DIRECTIVE = RESOLVE_DIRECTIVE;
  5537. exports.RESOLVE_DYNAMIC_COMPONENT = RESOLVE_DYNAMIC_COMPONENT;
  5538. exports.RESOLVE_FILTER = RESOLVE_FILTER;
  5539. exports.SET_BLOCK_TRACKING = SET_BLOCK_TRACKING;
  5540. exports.SUSPENSE = SUSPENSE;
  5541. exports.TELEPORT = TELEPORT;
  5542. exports.TO_DISPLAY_STRING = TO_DISPLAY_STRING;
  5543. exports.TO_HANDLERS = TO_HANDLERS;
  5544. exports.TO_HANDLER_KEY = TO_HANDLER_KEY;
  5545. exports.TRANSITION = TRANSITION;
  5546. exports.TRANSITION_GROUP = TRANSITION_GROUP;
  5547. exports.UNREF = UNREF;
  5548. exports.V_MODEL_CHECKBOX = V_MODEL_CHECKBOX;
  5549. exports.V_MODEL_DYNAMIC = V_MODEL_DYNAMIC;
  5550. exports.V_MODEL_RADIO = V_MODEL_RADIO;
  5551. exports.V_MODEL_SELECT = V_MODEL_SELECT;
  5552. exports.V_MODEL_TEXT = V_MODEL_TEXT;
  5553. exports.V_ON_WITH_KEYS = V_ON_WITH_KEYS;
  5554. exports.V_ON_WITH_MODIFIERS = V_ON_WITH_MODIFIERS;
  5555. exports.V_SHOW = V_SHOW;
  5556. exports.WITH_CTX = WITH_CTX;
  5557. exports.WITH_DIRECTIVES = WITH_DIRECTIVES;
  5558. exports.WITH_MEMO = WITH_MEMO;
  5559. exports.advancePositionWithClone = advancePositionWithClone;
  5560. exports.advancePositionWithMutation = advancePositionWithMutation;
  5561. exports.assert = assert;
  5562. exports.baseCompile = baseCompile;
  5563. exports.baseParse = baseParse;
  5564. exports.buildDirectiveArgs = buildDirectiveArgs;
  5565. exports.buildProps = buildProps;
  5566. exports.buildSlots = buildSlots;
  5567. exports.checkCompatEnabled = checkCompatEnabled;
  5568. exports.compile = compile;
  5569. exports.createArrayExpression = createArrayExpression;
  5570. exports.createAssignmentExpression = createAssignmentExpression;
  5571. exports.createBlockStatement = createBlockStatement;
  5572. exports.createCacheExpression = createCacheExpression;
  5573. exports.createCallExpression = createCallExpression;
  5574. exports.createCompilerError = createCompilerError;
  5575. exports.createCompoundExpression = createCompoundExpression;
  5576. exports.createConditionalExpression = createConditionalExpression;
  5577. exports.createDOMCompilerError = createDOMCompilerError;
  5578. exports.createForLoopParams = createForLoopParams;
  5579. exports.createFunctionExpression = createFunctionExpression;
  5580. exports.createIfStatement = createIfStatement;
  5581. exports.createInterpolation = createInterpolation;
  5582. exports.createObjectExpression = createObjectExpression;
  5583. exports.createObjectProperty = createObjectProperty;
  5584. exports.createReturnStatement = createReturnStatement;
  5585. exports.createRoot = createRoot;
  5586. exports.createSequenceExpression = createSequenceExpression;
  5587. exports.createSimpleExpression = createSimpleExpression;
  5588. exports.createStructuralDirectiveTransform = createStructuralDirectiveTransform;
  5589. exports.createTemplateLiteral = createTemplateLiteral;
  5590. exports.createTransformContext = createTransformContext;
  5591. exports.createVNodeCall = createVNodeCall;
  5592. exports.extractIdentifiers = extractIdentifiers;
  5593. exports.findDir = findDir;
  5594. exports.findProp = findProp;
  5595. exports.generate = generate;
  5596. exports.generateCodeFrame = generateCodeFrame;
  5597. exports.getBaseTransformPreset = getBaseTransformPreset;
  5598. exports.getConstantType = getConstantType;
  5599. exports.getInnerRange = getInnerRange;
  5600. exports.getMemoedVNodeCall = getMemoedVNodeCall;
  5601. exports.getVNodeBlockHelper = getVNodeBlockHelper;
  5602. exports.getVNodeHelper = getVNodeHelper;
  5603. exports.hasDynamicKeyVBind = hasDynamicKeyVBind;
  5604. exports.hasScopeRef = hasScopeRef;
  5605. exports.helperNameMap = helperNameMap;
  5606. exports.injectProp = injectProp;
  5607. exports.isBuiltInType = isBuiltInType;
  5608. exports.isCoreComponent = isCoreComponent;
  5609. exports.isFunctionType = isFunctionType;
  5610. exports.isInDestructureAssignment = isInDestructureAssignment;
  5611. exports.isMemberExpression = isMemberExpression;
  5612. exports.isMemberExpressionBrowser = isMemberExpressionBrowser;
  5613. exports.isMemberExpressionNode = isMemberExpressionNode;
  5614. exports.isReferencedIdentifier = isReferencedIdentifier;
  5615. exports.isSimpleIdentifier = isSimpleIdentifier;
  5616. exports.isSlotOutlet = isSlotOutlet;
  5617. exports.isStaticArgOf = isStaticArgOf;
  5618. exports.isStaticExp = isStaticExp;
  5619. exports.isStaticProperty = isStaticProperty;
  5620. exports.isStaticPropertyKey = isStaticPropertyKey;
  5621. exports.isTemplateNode = isTemplateNode;
  5622. exports.isText = isText;
  5623. exports.isVSlot = isVSlot;
  5624. exports.locStub = locStub;
  5625. exports.makeBlock = makeBlock;
  5626. exports.noopDirectiveTransform = noopDirectiveTransform;
  5627. exports.parse = parse;
  5628. exports.parserOptions = parserOptions;
  5629. exports.processExpression = processExpression;
  5630. exports.processFor = processFor;
  5631. exports.processIf = processIf;
  5632. exports.processSlotOutlet = processSlotOutlet;
  5633. exports.registerRuntimeHelpers = registerRuntimeHelpers;
  5634. exports.resolveComponentType = resolveComponentType;
  5635. exports.stringifyExpression = stringifyExpression;
  5636. exports.toValidAssetId = toValidAssetId;
  5637. exports.trackSlotScopes = trackSlotScopes;
  5638. exports.trackVForSlotScopes = trackVForSlotScopes;
  5639. exports.transform = transform;
  5640. exports.transformBind = transformBind;
  5641. exports.transformElement = transformElement;
  5642. exports.transformExpression = transformExpression;
  5643. exports.transformModel = transformModel;
  5644. exports.transformOn = transformOn;
  5645. exports.transformStyle = transformStyle;
  5646. exports.traverseNode = traverseNode;
  5647. exports.walkBlockDeclarations = walkBlockDeclarations;
  5648. exports.walkFunctionParams = walkFunctionParams;
  5649. exports.walkIdentifiers = walkIdentifiers;
  5650. exports.warnDeprecation = warnDeprecation;
  5651. Object.defineProperty(exports, '__esModule', { value: true });
  5652. return exports;
  5653. }({}));