compiler-dom.esm-browser.js 163 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410
  1. /**
  2. * Make a map and return a function for checking if a key
  3. * is in that map.
  4. * IMPORTANT: all calls of this function must be prefixed with
  5. * \/\*#\_\_PURE\_\_\*\/
  6. * So that rollup can tree-shake them if necessary.
  7. */
  8. function makeMap(str, expectsLowerCase) {
  9. const map = Object.create(null);
  10. const list = str.split(',');
  11. for (let i = 0; i < list.length; i++) {
  12. map[list[i]] = true;
  13. }
  14. return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
  15. }
  16. /**
  17. * dev only flag -> name mapping
  18. */
  19. const PatchFlagNames = {
  20. [1 /* TEXT */]: `TEXT`,
  21. [2 /* CLASS */]: `CLASS`,
  22. [4 /* STYLE */]: `STYLE`,
  23. [8 /* PROPS */]: `PROPS`,
  24. [16 /* FULL_PROPS */]: `FULL_PROPS`,
  25. [32 /* HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
  26. [64 /* STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
  27. [128 /* KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
  28. [256 /* UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
  29. [512 /* NEED_PATCH */]: `NEED_PATCH`,
  30. [1024 /* DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
  31. [2048 /* DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
  32. [-1 /* HOISTED */]: `HOISTED`,
  33. [-2 /* BAIL */]: `BAIL`
  34. };
  35. /**
  36. * Dev only
  37. */
  38. const slotFlagsText = {
  39. [1 /* STABLE */]: 'STABLE',
  40. [2 /* DYNAMIC */]: 'DYNAMIC',
  41. [3 /* FORWARDED */]: 'FORWARDED'
  42. };
  43. const range = 2;
  44. function generateCodeFrame(source, start = 0, end = source.length) {
  45. const lines = source.split(/\r?\n/);
  46. let count = 0;
  47. const res = [];
  48. for (let i = 0; i < lines.length; i++) {
  49. count += lines[i].length + 1;
  50. if (count >= start) {
  51. for (let j = i - range; j <= i + range || end > count; j++) {
  52. if (j < 0 || j >= lines.length)
  53. continue;
  54. const line = j + 1;
  55. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  56. const lineLength = lines[j].length;
  57. if (j === i) {
  58. // push underline
  59. const pad = start - (count - lineLength) + 1;
  60. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  61. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  62. }
  63. else if (j > i) {
  64. if (end > count) {
  65. const length = Math.max(Math.min(end - count, lineLength), 1);
  66. res.push(` | ` + '^'.repeat(length));
  67. }
  68. count += lineLength + 1;
  69. }
  70. }
  71. break;
  72. }
  73. }
  74. return res.join('\n');
  75. }
  76. const listDelimiterRE = /;(?![^(]*\))/g;
  77. const propertyDelimiterRE = /:(.+)/;
  78. function parseStringStyle(cssText) {
  79. const ret = {};
  80. cssText.split(listDelimiterRE).forEach(item => {
  81. if (item) {
  82. const tmp = item.split(propertyDelimiterRE);
  83. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  84. }
  85. });
  86. return ret;
  87. }
  88. // These tag configs are shared between compiler-dom and runtime-dom, so they
  89. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  90. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  91. 'header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,' +
  92. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  93. 'data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,' +
  94. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  95. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  96. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  97. 'option,output,progress,select,textarea,details,dialog,menu,' +
  98. 'summary,template,blockquote,iframe,tfoot';
  99. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  100. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  101. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  102. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  103. 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  104. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  105. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  106. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  107. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  108. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  109. 'text,textPath,title,tspan,unknown,use,view';
  110. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  111. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  112. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  113. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  114. const EMPTY_OBJ = Object.freeze({})
  115. ;
  116. Object.freeze([]) ;
  117. const NOOP = () => { };
  118. /**
  119. * Always return false.
  120. */
  121. const NO = () => false;
  122. const onRE = /^on[^a-z]/;
  123. const isOn = (key) => onRE.test(key);
  124. const extend = Object.assign;
  125. const isArray = Array.isArray;
  126. const isString = (val) => typeof val === 'string';
  127. const isSymbol = (val) => typeof val === 'symbol';
  128. const isObject = (val) => val !== null && typeof val === 'object';
  129. const isReservedProp = /*#__PURE__*/ makeMap(
  130. // the leading comma is intentional so empty string "" is also included
  131. ',key,ref,' +
  132. 'onVnodeBeforeMount,onVnodeMounted,' +
  133. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  134. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  135. const cacheStringFunction = (fn) => {
  136. const cache = Object.create(null);
  137. return ((str) => {
  138. const hit = cache[str];
  139. return hit || (cache[str] = fn(str));
  140. });
  141. };
  142. const camelizeRE = /-(\w)/g;
  143. /**
  144. * @private
  145. */
  146. const camelize = cacheStringFunction((str) => {
  147. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  148. });
  149. const hyphenateRE = /\B([A-Z])/g;
  150. /**
  151. * @private
  152. */
  153. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  154. /**
  155. * @private
  156. */
  157. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  158. /**
  159. * @private
  160. */
  161. const toHandlerKey = cacheStringFunction((str) => (str ? `on${capitalize(str)}` : ``));
  162. function defaultOnError(error) {
  163. throw error;
  164. }
  165. function createCompilerError(code, loc, messages, additionalMessage) {
  166. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  167. ;
  168. const error = new SyntaxError(String(msg));
  169. error.code = code;
  170. error.loc = loc;
  171. return error;
  172. }
  173. const errorMessages = {
  174. // parse errors
  175. [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  176. [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  177. [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  178. [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  179. [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  180. [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  181. [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  182. [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  183. [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  184. [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  185. [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  186. [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  187. [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  188. [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  189. [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  190. [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  191. [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  192. [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  193. [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  194. [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  195. [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  196. [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  197. // Vue-specific parse errors
  198. [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
  199. [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
  200. [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  201. [26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  202. 'Note that dynamic directive argument cannot contain spaces.',
  203. // transform errors
  204. [27 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  205. [28 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  206. [29 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
  207. [30 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  208. [31 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  209. [32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  210. [33 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  211. [34 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  212. [35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  213. [36 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
  214. `When there are multiple named slots, all slots should use <template> ` +
  215. `syntax to avoid scope ambiguity.`,
  216. [37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  217. [38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  218. `default slot. These children will be ignored.`,
  219. [39 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  220. [40 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  221. [41 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  222. [42 /* X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  223. [43 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  224. [44 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  225. // generic errors
  226. [45 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  227. [46 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  228. [47 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  229. [48 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`
  230. };
  231. const FRAGMENT = Symbol(`Fragment` );
  232. const TELEPORT = Symbol(`Teleport` );
  233. const SUSPENSE = Symbol(`Suspense` );
  234. const KEEP_ALIVE = Symbol(`KeepAlive` );
  235. const BASE_TRANSITION = Symbol(`BaseTransition` );
  236. const OPEN_BLOCK = Symbol(`openBlock` );
  237. const CREATE_BLOCK = Symbol(`createBlock` );
  238. const CREATE_VNODE = Symbol(`createVNode` );
  239. const CREATE_COMMENT = Symbol(`createCommentVNode` );
  240. const CREATE_TEXT = Symbol(`createTextVNode` );
  241. const CREATE_STATIC = Symbol(`createStaticVNode` );
  242. const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
  243. const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
  244. const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
  245. const WITH_DIRECTIVES = Symbol(`withDirectives` );
  246. const RENDER_LIST = Symbol(`renderList` );
  247. const RENDER_SLOT = Symbol(`renderSlot` );
  248. const CREATE_SLOTS = Symbol(`createSlots` );
  249. const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
  250. const MERGE_PROPS = Symbol(`mergeProps` );
  251. const TO_HANDLERS = Symbol(`toHandlers` );
  252. const CAMELIZE = Symbol(`camelize` );
  253. const CAPITALIZE = Symbol(`capitalize` );
  254. const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
  255. const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
  256. const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
  257. const POP_SCOPE_ID = Symbol(`popScopeId` );
  258. const WITH_SCOPE_ID = Symbol(`withScopeId` );
  259. const WITH_CTX = Symbol(`withCtx` );
  260. const UNREF = Symbol(`unref` );
  261. const IS_REF = Symbol(`isRef` );
  262. // Name mapping for runtime helpers that need to be imported from 'vue' in
  263. // generated code. Make sure these are correctly exported in the runtime!
  264. // Using `any` here because TS doesn't allow symbols as index type.
  265. const helperNameMap = {
  266. [FRAGMENT]: `Fragment`,
  267. [TELEPORT]: `Teleport`,
  268. [SUSPENSE]: `Suspense`,
  269. [KEEP_ALIVE]: `KeepAlive`,
  270. [BASE_TRANSITION]: `BaseTransition`,
  271. [OPEN_BLOCK]: `openBlock`,
  272. [CREATE_BLOCK]: `createBlock`,
  273. [CREATE_VNODE]: `createVNode`,
  274. [CREATE_COMMENT]: `createCommentVNode`,
  275. [CREATE_TEXT]: `createTextVNode`,
  276. [CREATE_STATIC]: `createStaticVNode`,
  277. [RESOLVE_COMPONENT]: `resolveComponent`,
  278. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  279. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  280. [WITH_DIRECTIVES]: `withDirectives`,
  281. [RENDER_LIST]: `renderList`,
  282. [RENDER_SLOT]: `renderSlot`,
  283. [CREATE_SLOTS]: `createSlots`,
  284. [TO_DISPLAY_STRING]: `toDisplayString`,
  285. [MERGE_PROPS]: `mergeProps`,
  286. [TO_HANDLERS]: `toHandlers`,
  287. [CAMELIZE]: `camelize`,
  288. [CAPITALIZE]: `capitalize`,
  289. [TO_HANDLER_KEY]: `toHandlerKey`,
  290. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  291. [PUSH_SCOPE_ID]: `pushScopeId`,
  292. [POP_SCOPE_ID]: `popScopeId`,
  293. [WITH_SCOPE_ID]: `withScopeId`,
  294. [WITH_CTX]: `withCtx`,
  295. [UNREF]: `unref`,
  296. [IS_REF]: `isRef`
  297. };
  298. function registerRuntimeHelpers(helpers) {
  299. Object.getOwnPropertySymbols(helpers).forEach(s => {
  300. helperNameMap[s] = helpers[s];
  301. });
  302. }
  303. // AST Utilities ---------------------------------------------------------------
  304. // Some expressions, e.g. sequence and conditional expressions, are never
  305. // associated with template nodes, so their source locations are just a stub.
  306. // Container types like CompoundExpression also don't need a real location.
  307. const locStub = {
  308. source: '',
  309. start: { line: 1, column: 1, offset: 0 },
  310. end: { line: 1, column: 1, offset: 0 }
  311. };
  312. function createRoot(children, loc = locStub) {
  313. return {
  314. type: 0 /* ROOT */,
  315. children,
  316. helpers: [],
  317. components: [],
  318. directives: [],
  319. hoists: [],
  320. imports: [],
  321. cached: 0,
  322. temps: 0,
  323. codegenNode: undefined,
  324. loc
  325. };
  326. }
  327. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, loc = locStub) {
  328. if (context) {
  329. if (isBlock) {
  330. context.helper(OPEN_BLOCK);
  331. context.helper(CREATE_BLOCK);
  332. }
  333. else {
  334. context.helper(CREATE_VNODE);
  335. }
  336. if (directives) {
  337. context.helper(WITH_DIRECTIVES);
  338. }
  339. }
  340. return {
  341. type: 13 /* VNODE_CALL */,
  342. tag,
  343. props,
  344. children,
  345. patchFlag,
  346. dynamicProps,
  347. directives,
  348. isBlock,
  349. disableTracking,
  350. loc
  351. };
  352. }
  353. function createArrayExpression(elements, loc = locStub) {
  354. return {
  355. type: 17 /* JS_ARRAY_EXPRESSION */,
  356. loc,
  357. elements
  358. };
  359. }
  360. function createObjectExpression(properties, loc = locStub) {
  361. return {
  362. type: 15 /* JS_OBJECT_EXPRESSION */,
  363. loc,
  364. properties
  365. };
  366. }
  367. function createObjectProperty(key, value) {
  368. return {
  369. type: 16 /* JS_PROPERTY */,
  370. loc: locStub,
  371. key: isString(key) ? createSimpleExpression(key, true) : key,
  372. value
  373. };
  374. }
  375. function createSimpleExpression(content, isStatic, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
  376. return {
  377. type: 4 /* SIMPLE_EXPRESSION */,
  378. loc,
  379. content,
  380. isStatic,
  381. constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
  382. };
  383. }
  384. function createInterpolation(content, loc) {
  385. return {
  386. type: 5 /* INTERPOLATION */,
  387. loc,
  388. content: isString(content)
  389. ? createSimpleExpression(content, false, loc)
  390. : content
  391. };
  392. }
  393. function createCompoundExpression(children, loc = locStub) {
  394. return {
  395. type: 8 /* COMPOUND_EXPRESSION */,
  396. loc,
  397. children
  398. };
  399. }
  400. function createCallExpression(callee, args = [], loc = locStub) {
  401. return {
  402. type: 14 /* JS_CALL_EXPRESSION */,
  403. loc,
  404. callee,
  405. arguments: args
  406. };
  407. }
  408. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  409. return {
  410. type: 18 /* JS_FUNCTION_EXPRESSION */,
  411. params,
  412. returns,
  413. newline,
  414. isSlot,
  415. loc
  416. };
  417. }
  418. function createConditionalExpression(test, consequent, alternate, newline = true) {
  419. return {
  420. type: 19 /* JS_CONDITIONAL_EXPRESSION */,
  421. test,
  422. consequent,
  423. alternate,
  424. newline,
  425. loc: locStub
  426. };
  427. }
  428. function createCacheExpression(index, value, isVNode = false) {
  429. return {
  430. type: 20 /* JS_CACHE_EXPRESSION */,
  431. index,
  432. value,
  433. isVNode,
  434. loc: locStub
  435. };
  436. }
  437. function createBlockStatement(body) {
  438. return {
  439. type: 21 /* JS_BLOCK_STATEMENT */,
  440. body,
  441. loc: locStub
  442. };
  443. }
  444. function createTemplateLiteral(elements) {
  445. return {
  446. type: 22 /* JS_TEMPLATE_LITERAL */,
  447. elements,
  448. loc: locStub
  449. };
  450. }
  451. function createIfStatement(test, consequent, alternate) {
  452. return {
  453. type: 23 /* JS_IF_STATEMENT */,
  454. test,
  455. consequent,
  456. alternate,
  457. loc: locStub
  458. };
  459. }
  460. function createAssignmentExpression(left, right) {
  461. return {
  462. type: 24 /* JS_ASSIGNMENT_EXPRESSION */,
  463. left,
  464. right,
  465. loc: locStub
  466. };
  467. }
  468. function createSequenceExpression(expressions) {
  469. return {
  470. type: 25 /* JS_SEQUENCE_EXPRESSION */,
  471. expressions,
  472. loc: locStub
  473. };
  474. }
  475. function createReturnStatement(returns) {
  476. return {
  477. type: 26 /* JS_RETURN_STATEMENT */,
  478. returns,
  479. loc: locStub
  480. };
  481. }
  482. const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
  483. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  484. function isCoreComponent(tag) {
  485. if (isBuiltInType(tag, 'Teleport')) {
  486. return TELEPORT;
  487. }
  488. else if (isBuiltInType(tag, 'Suspense')) {
  489. return SUSPENSE;
  490. }
  491. else if (isBuiltInType(tag, 'KeepAlive')) {
  492. return KEEP_ALIVE;
  493. }
  494. else if (isBuiltInType(tag, 'BaseTransition')) {
  495. return BASE_TRANSITION;
  496. }
  497. }
  498. const nonIdentifierRE = /^\d|[^\$\w]/;
  499. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  500. const memberExpRE = /^[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*|\[[^\]]+\])*$/;
  501. const isMemberExpression = (path) => {
  502. if (!path)
  503. return false;
  504. return memberExpRE.test(path.trim());
  505. };
  506. function getInnerRange(loc, offset, length) {
  507. const source = loc.source.substr(offset, length);
  508. const newLoc = {
  509. source,
  510. start: advancePositionWithClone(loc.start, loc.source, offset),
  511. end: loc.end
  512. };
  513. if (length != null) {
  514. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  515. }
  516. return newLoc;
  517. }
  518. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  519. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  520. }
  521. // advance by mutation without cloning (for performance reasons), since this
  522. // gets called a lot in the parser
  523. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  524. let linesCount = 0;
  525. let lastNewLinePos = -1;
  526. for (let i = 0; i < numberOfCharacters; i++) {
  527. if (source.charCodeAt(i) === 10 /* newline char code */) {
  528. linesCount++;
  529. lastNewLinePos = i;
  530. }
  531. }
  532. pos.offset += numberOfCharacters;
  533. pos.line += linesCount;
  534. pos.column =
  535. lastNewLinePos === -1
  536. ? pos.column + numberOfCharacters
  537. : numberOfCharacters - lastNewLinePos;
  538. return pos;
  539. }
  540. function assert(condition, msg) {
  541. /* istanbul ignore if */
  542. if (!condition) {
  543. throw new Error(msg || `unexpected compiler condition`);
  544. }
  545. }
  546. function findDir(node, name, allowEmpty = false) {
  547. for (let i = 0; i < node.props.length; i++) {
  548. const p = node.props[i];
  549. if (p.type === 7 /* DIRECTIVE */ &&
  550. (allowEmpty || p.exp) &&
  551. (isString(name) ? p.name === name : name.test(p.name))) {
  552. return p;
  553. }
  554. }
  555. }
  556. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  557. for (let i = 0; i < node.props.length; i++) {
  558. const p = node.props[i];
  559. if (p.type === 6 /* ATTRIBUTE */) {
  560. if (dynamicOnly)
  561. continue;
  562. if (p.name === name && (p.value || allowEmpty)) {
  563. return p;
  564. }
  565. }
  566. else if (p.name === 'bind' &&
  567. (p.exp || allowEmpty) &&
  568. isBindKey(p.arg, name)) {
  569. return p;
  570. }
  571. }
  572. }
  573. function isBindKey(arg, name) {
  574. return !!(arg && isStaticExp(arg) && arg.content === name);
  575. }
  576. function hasDynamicKeyVBind(node) {
  577. return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
  578. p.name === 'bind' &&
  579. (!p.arg || // v-bind="obj"
  580. p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  581. !p.arg.isStatic) // v-bind:[foo]
  582. );
  583. }
  584. function isText(node) {
  585. return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
  586. }
  587. function isVSlot(p) {
  588. return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
  589. }
  590. function isTemplateNode(node) {
  591. return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
  592. }
  593. function isSlotOutlet(node) {
  594. return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
  595. }
  596. function injectProp(node, prop, context) {
  597. let propsWithInjection;
  598. const props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
  599. if (props == null || isString(props)) {
  600. propsWithInjection = createObjectExpression([prop]);
  601. }
  602. else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
  603. // merged props... add ours
  604. // only inject key to object literal if it's the first argument so that
  605. // if doesn't override user provided keys
  606. const first = props.arguments[0];
  607. if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
  608. first.properties.unshift(prop);
  609. }
  610. else {
  611. if (props.callee === TO_HANDLERS) {
  612. // #2366
  613. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  614. createObjectExpression([prop]),
  615. props
  616. ]);
  617. }
  618. else {
  619. props.arguments.unshift(createObjectExpression([prop]));
  620. }
  621. }
  622. !propsWithInjection && (propsWithInjection = props);
  623. }
  624. else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  625. let alreadyExists = false;
  626. // check existing key to avoid overriding user provided keys
  627. if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
  628. const propKeyName = prop.key.content;
  629. alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  630. p.key.content === propKeyName);
  631. }
  632. if (!alreadyExists) {
  633. props.properties.unshift(prop);
  634. }
  635. propsWithInjection = props;
  636. }
  637. else {
  638. // single v-bind with expression, return a merged replacement
  639. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  640. createObjectExpression([prop]),
  641. props
  642. ]);
  643. }
  644. if (node.type === 13 /* VNODE_CALL */) {
  645. node.props = propsWithInjection;
  646. }
  647. else {
  648. node.arguments[2] = propsWithInjection;
  649. }
  650. }
  651. function toValidAssetId(name, type) {
  652. return `_${type}_${name.replace(/[^\w]/g, '_')}`;
  653. }
  654. // Check if a node contains expressions that reference current context scope ids
  655. function hasScopeRef(node, ids) {
  656. if (!node || Object.keys(ids).length === 0) {
  657. return false;
  658. }
  659. switch (node.type) {
  660. case 1 /* ELEMENT */:
  661. for (let i = 0; i < node.props.length; i++) {
  662. const p = node.props[i];
  663. if (p.type === 7 /* DIRECTIVE */ &&
  664. (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {
  665. return true;
  666. }
  667. }
  668. return node.children.some(c => hasScopeRef(c, ids));
  669. case 11 /* FOR */:
  670. if (hasScopeRef(node.source, ids)) {
  671. return true;
  672. }
  673. return node.children.some(c => hasScopeRef(c, ids));
  674. case 9 /* IF */:
  675. return node.branches.some(b => hasScopeRef(b, ids));
  676. case 10 /* IF_BRANCH */:
  677. if (hasScopeRef(node.condition, ids)) {
  678. return true;
  679. }
  680. return node.children.some(c => hasScopeRef(c, ids));
  681. case 4 /* SIMPLE_EXPRESSION */:
  682. return (!node.isStatic &&
  683. isSimpleIdentifier(node.content) &&
  684. !!ids[node.content]);
  685. case 8 /* COMPOUND_EXPRESSION */:
  686. return node.children.some(c => isObject(c) && hasScopeRef(c, ids));
  687. case 5 /* INTERPOLATION */:
  688. case 12 /* TEXT_CALL */:
  689. return hasScopeRef(node.content, ids);
  690. case 2 /* TEXT */:
  691. case 3 /* COMMENT */:
  692. return false;
  693. default:
  694. return false;
  695. }
  696. }
  697. // The default decoder only provides escapes for characters reserved as part of
  698. // the template syntax, and is only used if the custom renderer did not provide
  699. // a platform-specific decoder.
  700. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  701. const decodeMap = {
  702. gt: '>',
  703. lt: '<',
  704. amp: '&',
  705. apos: "'",
  706. quot: '"'
  707. };
  708. const defaultParserOptions = {
  709. delimiters: [`{{`, `}}`],
  710. getNamespace: () => 0 /* HTML */,
  711. getTextMode: () => 0 /* DATA */,
  712. isVoidTag: NO,
  713. isPreTag: NO,
  714. isCustomElement: NO,
  715. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  716. onError: defaultOnError,
  717. comments: false
  718. };
  719. function baseParse(content, options = {}) {
  720. const context = createParserContext(content, options);
  721. const start = getCursor(context);
  722. return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
  723. }
  724. function createParserContext(content, rawOptions) {
  725. const options = extend({}, defaultParserOptions);
  726. for (const key in rawOptions) {
  727. // @ts-ignore
  728. options[key] = rawOptions[key] || defaultParserOptions[key];
  729. }
  730. return {
  731. options,
  732. column: 1,
  733. line: 1,
  734. offset: 0,
  735. originalSource: content,
  736. source: content,
  737. inPre: false,
  738. inVPre: false
  739. };
  740. }
  741. function parseChildren(context, mode, ancestors) {
  742. const parent = last(ancestors);
  743. const ns = parent ? parent.ns : 0 /* HTML */;
  744. const nodes = [];
  745. while (!isEnd(context, mode, ancestors)) {
  746. const s = context.source;
  747. let node = undefined;
  748. if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
  749. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  750. // '{{'
  751. node = parseInterpolation(context, mode);
  752. }
  753. else if (mode === 0 /* DATA */ && s[0] === '<') {
  754. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  755. if (s.length === 1) {
  756. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
  757. }
  758. else if (s[1] === '!') {
  759. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  760. if (startsWith(s, '<!--')) {
  761. node = parseComment(context);
  762. }
  763. else if (startsWith(s, '<!DOCTYPE')) {
  764. // Ignore DOCTYPE by a limitation.
  765. node = parseBogusComment(context);
  766. }
  767. else if (startsWith(s, '<![CDATA[')) {
  768. if (ns !== 0 /* HTML */) {
  769. node = parseCDATA(context, ancestors);
  770. }
  771. else {
  772. emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
  773. node = parseBogusComment(context);
  774. }
  775. }
  776. else {
  777. emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
  778. node = parseBogusComment(context);
  779. }
  780. }
  781. else if (s[1] === '/') {
  782. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  783. if (s.length === 2) {
  784. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
  785. }
  786. else if (s[2] === '>') {
  787. emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
  788. advanceBy(context, 3);
  789. continue;
  790. }
  791. else if (/[a-z]/i.test(s[2])) {
  792. emitError(context, 23 /* X_INVALID_END_TAG */);
  793. parseTag(context, 1 /* End */, parent);
  794. continue;
  795. }
  796. else {
  797. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  798. node = parseBogusComment(context);
  799. }
  800. }
  801. else if (/[a-z]/i.test(s[1])) {
  802. node = parseElement(context, ancestors);
  803. }
  804. else if (s[1] === '?') {
  805. emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  806. node = parseBogusComment(context);
  807. }
  808. else {
  809. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  810. }
  811. }
  812. }
  813. if (!node) {
  814. node = parseText(context, mode);
  815. }
  816. if (isArray(node)) {
  817. for (let i = 0; i < node.length; i++) {
  818. pushNode(nodes, node[i]);
  819. }
  820. }
  821. else {
  822. pushNode(nodes, node);
  823. }
  824. }
  825. // Whitespace management for more efficient output
  826. // (same as v2 whitespace: 'condense')
  827. let removedWhitespace = false;
  828. if (mode !== 2 /* RAWTEXT */) {
  829. for (let i = 0; i < nodes.length; i++) {
  830. const node = nodes[i];
  831. if (!context.inPre && node.type === 2 /* TEXT */) {
  832. if (!/[^\t\r\n\f ]/.test(node.content)) {
  833. const prev = nodes[i - 1];
  834. const next = nodes[i + 1];
  835. // If:
  836. // - the whitespace is the first or last node, or:
  837. // - the whitespace is adjacent to a comment, or:
  838. // - the whitespace is between two elements AND contains newline
  839. // Then the whitespace is ignored.
  840. if (!prev ||
  841. !next ||
  842. prev.type === 3 /* COMMENT */ ||
  843. next.type === 3 /* COMMENT */ ||
  844. (prev.type === 1 /* ELEMENT */ &&
  845. next.type === 1 /* ELEMENT */ &&
  846. /[\r\n]/.test(node.content))) {
  847. removedWhitespace = true;
  848. nodes[i] = null;
  849. }
  850. else {
  851. // Otherwise, condensed consecutive whitespace inside the text
  852. // down to a single space
  853. node.content = ' ';
  854. }
  855. }
  856. else {
  857. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  858. }
  859. }
  860. }
  861. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  862. // remove leading newline per html spec
  863. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  864. const first = nodes[0];
  865. if (first && first.type === 2 /* TEXT */) {
  866. first.content = first.content.replace(/^\r?\n/, '');
  867. }
  868. }
  869. }
  870. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  871. }
  872. function pushNode(nodes, node) {
  873. if (node.type === 2 /* TEXT */) {
  874. const prev = last(nodes);
  875. // Merge if both this and the previous node are text and those are
  876. // consecutive. This happens for cases like "a < b".
  877. if (prev &&
  878. prev.type === 2 /* TEXT */ &&
  879. prev.loc.end.offset === node.loc.start.offset) {
  880. prev.content += node.content;
  881. prev.loc.end = node.loc.end;
  882. prev.loc.source += node.loc.source;
  883. return;
  884. }
  885. }
  886. nodes.push(node);
  887. }
  888. function parseCDATA(context, ancestors) {
  889. advanceBy(context, 9);
  890. const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
  891. if (context.source.length === 0) {
  892. emitError(context, 6 /* EOF_IN_CDATA */);
  893. }
  894. else {
  895. advanceBy(context, 3);
  896. }
  897. return nodes;
  898. }
  899. function parseComment(context) {
  900. const start = getCursor(context);
  901. let content;
  902. // Regular comment.
  903. const match = /--(\!)?>/.exec(context.source);
  904. if (!match) {
  905. content = context.source.slice(4);
  906. advanceBy(context, context.source.length);
  907. emitError(context, 7 /* EOF_IN_COMMENT */);
  908. }
  909. else {
  910. if (match.index <= 3) {
  911. emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  912. }
  913. if (match[1]) {
  914. emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
  915. }
  916. content = context.source.slice(4, match.index);
  917. // Advancing with reporting nested comments.
  918. const s = context.source.slice(0, match.index);
  919. let prevIndex = 1, nestedIndex = 0;
  920. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  921. advanceBy(context, nestedIndex - prevIndex + 1);
  922. if (nestedIndex + 4 < s.length) {
  923. emitError(context, 16 /* NESTED_COMMENT */);
  924. }
  925. prevIndex = nestedIndex + 1;
  926. }
  927. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  928. }
  929. return {
  930. type: 3 /* COMMENT */,
  931. content,
  932. loc: getSelection(context, start)
  933. };
  934. }
  935. function parseBogusComment(context) {
  936. const start = getCursor(context);
  937. const contentStart = context.source[1] === '?' ? 1 : 2;
  938. let content;
  939. const closeIndex = context.source.indexOf('>');
  940. if (closeIndex === -1) {
  941. content = context.source.slice(contentStart);
  942. advanceBy(context, context.source.length);
  943. }
  944. else {
  945. content = context.source.slice(contentStart, closeIndex);
  946. advanceBy(context, closeIndex + 1);
  947. }
  948. return {
  949. type: 3 /* COMMENT */,
  950. content,
  951. loc: getSelection(context, start)
  952. };
  953. }
  954. function parseElement(context, ancestors) {
  955. // Start tag.
  956. const wasInPre = context.inPre;
  957. const wasInVPre = context.inVPre;
  958. const parent = last(ancestors);
  959. const element = parseTag(context, 0 /* Start */, parent);
  960. const isPreBoundary = context.inPre && !wasInPre;
  961. const isVPreBoundary = context.inVPre && !wasInVPre;
  962. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  963. return element;
  964. }
  965. // Children.
  966. ancestors.push(element);
  967. const mode = context.options.getTextMode(element, parent);
  968. const children = parseChildren(context, mode, ancestors);
  969. ancestors.pop();
  970. element.children = children;
  971. // End tag.
  972. if (startsWithEndTagOpen(context.source, element.tag)) {
  973. parseTag(context, 1 /* End */, parent);
  974. }
  975. else {
  976. emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
  977. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  978. const first = children[0];
  979. if (first && startsWith(first.loc.source, '<!--')) {
  980. emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  981. }
  982. }
  983. }
  984. element.loc = getSelection(context, element.loc.start);
  985. if (isPreBoundary) {
  986. context.inPre = false;
  987. }
  988. if (isVPreBoundary) {
  989. context.inVPre = false;
  990. }
  991. return element;
  992. }
  993. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  994. /**
  995. * Parse a tag (E.g. `<div id=a>`) with that type (start tag or end tag).
  996. */
  997. function parseTag(context, type, parent) {
  998. // Tag open.
  999. const start = getCursor(context);
  1000. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  1001. const tag = match[1];
  1002. const ns = context.options.getNamespace(tag, parent);
  1003. advanceBy(context, match[0].length);
  1004. advanceSpaces(context);
  1005. // save current state in case we need to re-parse attributes with v-pre
  1006. const cursor = getCursor(context);
  1007. const currentSource = context.source;
  1008. // Attributes.
  1009. let props = parseAttributes(context, type);
  1010. // check <pre> tag
  1011. if (context.options.isPreTag(tag)) {
  1012. context.inPre = true;
  1013. }
  1014. // check v-pre
  1015. if (!context.inVPre &&
  1016. props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
  1017. context.inVPre = true;
  1018. // reset context
  1019. extend(context, cursor);
  1020. context.source = currentSource;
  1021. // re-parse attrs and filter out v-pre itself
  1022. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  1023. }
  1024. // Tag close.
  1025. let isSelfClosing = false;
  1026. if (context.source.length === 0) {
  1027. emitError(context, 9 /* EOF_IN_TAG */);
  1028. }
  1029. else {
  1030. isSelfClosing = startsWith(context.source, '/>');
  1031. if (type === 1 /* End */ && isSelfClosing) {
  1032. emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
  1033. }
  1034. advanceBy(context, isSelfClosing ? 2 : 1);
  1035. }
  1036. let tagType = 0 /* ELEMENT */;
  1037. const options = context.options;
  1038. if (!context.inVPre && !options.isCustomElement(tag)) {
  1039. const hasVIs = props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'is');
  1040. if (options.isNativeTag && !hasVIs) {
  1041. if (!options.isNativeTag(tag))
  1042. tagType = 1 /* COMPONENT */;
  1043. }
  1044. else if (hasVIs ||
  1045. isCoreComponent(tag) ||
  1046. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  1047. /^[A-Z]/.test(tag) ||
  1048. tag === 'component') {
  1049. tagType = 1 /* COMPONENT */;
  1050. }
  1051. if (tag === 'slot') {
  1052. tagType = 2 /* SLOT */;
  1053. }
  1054. else if (tag === 'template' &&
  1055. props.some(p => {
  1056. return (p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name));
  1057. })) {
  1058. tagType = 3 /* TEMPLATE */;
  1059. }
  1060. }
  1061. return {
  1062. type: 1 /* ELEMENT */,
  1063. ns,
  1064. tag,
  1065. tagType,
  1066. props,
  1067. isSelfClosing,
  1068. children: [],
  1069. loc: getSelection(context, start),
  1070. codegenNode: undefined // to be created during transform phase
  1071. };
  1072. }
  1073. function parseAttributes(context, type) {
  1074. const props = [];
  1075. const attributeNames = new Set();
  1076. while (context.source.length > 0 &&
  1077. !startsWith(context.source, '>') &&
  1078. !startsWith(context.source, '/>')) {
  1079. if (startsWith(context.source, '/')) {
  1080. emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
  1081. advanceBy(context, 1);
  1082. advanceSpaces(context);
  1083. continue;
  1084. }
  1085. if (type === 1 /* End */) {
  1086. emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
  1087. }
  1088. const attr = parseAttribute(context, attributeNames);
  1089. if (type === 0 /* Start */) {
  1090. props.push(attr);
  1091. }
  1092. if (/^[^\t\r\n\f />]/.test(context.source)) {
  1093. emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  1094. }
  1095. advanceSpaces(context);
  1096. }
  1097. return props;
  1098. }
  1099. function parseAttribute(context, nameSet) {
  1100. // Name.
  1101. const start = getCursor(context);
  1102. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  1103. const name = match[0];
  1104. if (nameSet.has(name)) {
  1105. emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
  1106. }
  1107. nameSet.add(name);
  1108. if (name[0] === '=') {
  1109. emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  1110. }
  1111. {
  1112. const pattern = /["'<]/g;
  1113. let m;
  1114. while ((m = pattern.exec(name))) {
  1115. emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  1116. }
  1117. }
  1118. advanceBy(context, name.length);
  1119. // Value
  1120. let value = undefined;
  1121. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  1122. advanceSpaces(context);
  1123. advanceBy(context, 1);
  1124. advanceSpaces(context);
  1125. value = parseAttributeValue(context);
  1126. if (!value) {
  1127. emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
  1128. }
  1129. }
  1130. const loc = getSelection(context, start);
  1131. if (!context.inVPre && /^(v-|:|@|#)/.test(name)) {
  1132. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  1133. const dirName = match[1] ||
  1134. (startsWith(name, ':') ? 'bind' : startsWith(name, '@') ? 'on' : 'slot');
  1135. let arg;
  1136. if (match[2]) {
  1137. const isSlot = dirName === 'slot';
  1138. const startOffset = name.indexOf(match[2]);
  1139. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  1140. let content = match[2];
  1141. let isStatic = true;
  1142. if (content.startsWith('[')) {
  1143. isStatic = false;
  1144. if (!content.endsWith(']')) {
  1145. emitError(context, 26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  1146. }
  1147. content = content.substr(1, content.length - 2);
  1148. }
  1149. else if (isSlot) {
  1150. // #1241 special case for v-slot: vuetify relies extensively on slot
  1151. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  1152. // supports such usage so we are keeping it consistent with 2.x.
  1153. content += match[3] || '';
  1154. }
  1155. arg = {
  1156. type: 4 /* SIMPLE_EXPRESSION */,
  1157. content,
  1158. isStatic,
  1159. constType: isStatic
  1160. ? 3 /* CAN_STRINGIFY */
  1161. : 0 /* NOT_CONSTANT */,
  1162. loc
  1163. };
  1164. }
  1165. if (value && value.isQuoted) {
  1166. const valueLoc = value.loc;
  1167. valueLoc.start.offset++;
  1168. valueLoc.start.column++;
  1169. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  1170. valueLoc.source = valueLoc.source.slice(1, -1);
  1171. }
  1172. return {
  1173. type: 7 /* DIRECTIVE */,
  1174. name: dirName,
  1175. exp: value && {
  1176. type: 4 /* SIMPLE_EXPRESSION */,
  1177. content: value.content,
  1178. isStatic: false,
  1179. // Treat as non-constant by default. This can be potentially set to
  1180. // other values by `transformExpression` to make it eligible for hoisting.
  1181. constType: 0 /* NOT_CONSTANT */,
  1182. loc: value.loc
  1183. },
  1184. arg,
  1185. modifiers: match[3] ? match[3].substr(1).split('.') : [],
  1186. loc
  1187. };
  1188. }
  1189. return {
  1190. type: 6 /* ATTRIBUTE */,
  1191. name,
  1192. value: value && {
  1193. type: 2 /* TEXT */,
  1194. content: value.content,
  1195. loc: value.loc
  1196. },
  1197. loc
  1198. };
  1199. }
  1200. function parseAttributeValue(context) {
  1201. const start = getCursor(context);
  1202. let content;
  1203. const quote = context.source[0];
  1204. const isQuoted = quote === `"` || quote === `'`;
  1205. if (isQuoted) {
  1206. // Quoted value.
  1207. advanceBy(context, 1);
  1208. const endIndex = context.source.indexOf(quote);
  1209. if (endIndex === -1) {
  1210. content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
  1211. }
  1212. else {
  1213. content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
  1214. advanceBy(context, 1);
  1215. }
  1216. }
  1217. else {
  1218. // Unquoted
  1219. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  1220. if (!match) {
  1221. return undefined;
  1222. }
  1223. const unexpectedChars = /["'<=`]/g;
  1224. let m;
  1225. while ((m = unexpectedChars.exec(match[0]))) {
  1226. emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  1227. }
  1228. content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
  1229. }
  1230. return { content, isQuoted, loc: getSelection(context, start) };
  1231. }
  1232. function parseInterpolation(context, mode) {
  1233. const [open, close] = context.options.delimiters;
  1234. const closeIndex = context.source.indexOf(close, open.length);
  1235. if (closeIndex === -1) {
  1236. emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
  1237. return undefined;
  1238. }
  1239. const start = getCursor(context);
  1240. advanceBy(context, open.length);
  1241. const innerStart = getCursor(context);
  1242. const innerEnd = getCursor(context);
  1243. const rawContentLength = closeIndex - open.length;
  1244. const rawContent = context.source.slice(0, rawContentLength);
  1245. const preTrimContent = parseTextData(context, rawContentLength, mode);
  1246. const content = preTrimContent.trim();
  1247. const startOffset = preTrimContent.indexOf(content);
  1248. if (startOffset > 0) {
  1249. advancePositionWithMutation(innerStart, rawContent, startOffset);
  1250. }
  1251. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  1252. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  1253. advanceBy(context, close.length);
  1254. return {
  1255. type: 5 /* INTERPOLATION */,
  1256. content: {
  1257. type: 4 /* SIMPLE_EXPRESSION */,
  1258. isStatic: false,
  1259. // Set `isConstant` to false by default and will decide in transformExpression
  1260. constType: 0 /* NOT_CONSTANT */,
  1261. content,
  1262. loc: getSelection(context, innerStart, innerEnd)
  1263. },
  1264. loc: getSelection(context, start)
  1265. };
  1266. }
  1267. function parseText(context, mode) {
  1268. const endTokens = ['<', context.options.delimiters[0]];
  1269. if (mode === 3 /* CDATA */) {
  1270. endTokens.push(']]>');
  1271. }
  1272. let endIndex = context.source.length;
  1273. for (let i = 0; i < endTokens.length; i++) {
  1274. const index = context.source.indexOf(endTokens[i], 1);
  1275. if (index !== -1 && endIndex > index) {
  1276. endIndex = index;
  1277. }
  1278. }
  1279. const start = getCursor(context);
  1280. const content = parseTextData(context, endIndex, mode);
  1281. return {
  1282. type: 2 /* TEXT */,
  1283. content,
  1284. loc: getSelection(context, start)
  1285. };
  1286. }
  1287. /**
  1288. * Get text data with a given length from the current location.
  1289. * This translates HTML entities in the text data.
  1290. */
  1291. function parseTextData(context, length, mode) {
  1292. const rawText = context.source.slice(0, length);
  1293. advanceBy(context, length);
  1294. if (mode === 2 /* RAWTEXT */ ||
  1295. mode === 3 /* CDATA */ ||
  1296. rawText.indexOf('&') === -1) {
  1297. return rawText;
  1298. }
  1299. else {
  1300. // DATA or RCDATA containing "&"". Entity decoding required.
  1301. return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
  1302. }
  1303. }
  1304. function getCursor(context) {
  1305. const { column, line, offset } = context;
  1306. return { column, line, offset };
  1307. }
  1308. function getSelection(context, start, end) {
  1309. end = end || getCursor(context);
  1310. return {
  1311. start,
  1312. end,
  1313. source: context.originalSource.slice(start.offset, end.offset)
  1314. };
  1315. }
  1316. function last(xs) {
  1317. return xs[xs.length - 1];
  1318. }
  1319. function startsWith(source, searchString) {
  1320. return source.startsWith(searchString);
  1321. }
  1322. function advanceBy(context, numberOfCharacters) {
  1323. const { source } = context;
  1324. advancePositionWithMutation(context, source, numberOfCharacters);
  1325. context.source = source.slice(numberOfCharacters);
  1326. }
  1327. function advanceSpaces(context) {
  1328. const match = /^[\t\r\n\f ]+/.exec(context.source);
  1329. if (match) {
  1330. advanceBy(context, match[0].length);
  1331. }
  1332. }
  1333. function getNewPosition(context, start, numberOfCharacters) {
  1334. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  1335. }
  1336. function emitError(context, code, offset, loc = getCursor(context)) {
  1337. if (offset) {
  1338. loc.offset += offset;
  1339. loc.column += offset;
  1340. }
  1341. context.options.onError(createCompilerError(code, {
  1342. start: loc,
  1343. end: loc,
  1344. source: ''
  1345. }));
  1346. }
  1347. function isEnd(context, mode, ancestors) {
  1348. const s = context.source;
  1349. switch (mode) {
  1350. case 0 /* DATA */:
  1351. if (startsWith(s, '</')) {
  1352. // TODO: probably bad performance
  1353. for (let i = ancestors.length - 1; i >= 0; --i) {
  1354. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  1355. return true;
  1356. }
  1357. }
  1358. }
  1359. break;
  1360. case 1 /* RCDATA */:
  1361. case 2 /* RAWTEXT */: {
  1362. const parent = last(ancestors);
  1363. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  1364. return true;
  1365. }
  1366. break;
  1367. }
  1368. case 3 /* CDATA */:
  1369. if (startsWith(s, ']]>')) {
  1370. return true;
  1371. }
  1372. break;
  1373. }
  1374. return !s;
  1375. }
  1376. function startsWithEndTagOpen(source, tag) {
  1377. return (startsWith(source, '</') &&
  1378. source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
  1379. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  1380. }
  1381. function hoistStatic(root, context) {
  1382. walk(root, context,
  1383. // Root node is unfortunately non-hoistable due to potential parent
  1384. // fallthrough attributes.
  1385. isSingleElementRoot(root, root.children[0]));
  1386. }
  1387. function isSingleElementRoot(root, child) {
  1388. const { children } = root;
  1389. return (children.length === 1 &&
  1390. child.type === 1 /* ELEMENT */ &&
  1391. !isSlotOutlet(child));
  1392. }
  1393. function walk(node, context, doNotHoistNode = false) {
  1394. let hasHoistedNode = false;
  1395. // Some transforms, e.g. transformAssetUrls from @vue/compiler-sfc, replaces
  1396. // static bindings with expressions. These expressions are guaranteed to be
  1397. // constant so they are still eligible for hoisting, but they are only
  1398. // available at runtime and therefore cannot be evaluated ahead of time.
  1399. // This is only a concern for pre-stringification (via transformHoist by
  1400. // @vue/compiler-dom), but doing it here allows us to perform only one full
  1401. // walk of the AST and allow `stringifyStatic` to stop walking as soon as its
  1402. // stringficiation threshold is met.
  1403. let canStringify = true;
  1404. const { children } = node;
  1405. for (let i = 0; i < children.length; i++) {
  1406. const child = children[i];
  1407. // only plain elements & text calls are eligible for hoisting.
  1408. if (child.type === 1 /* ELEMENT */ &&
  1409. child.tagType === 0 /* ELEMENT */) {
  1410. const constantType = doNotHoistNode
  1411. ? 0 /* NOT_CONSTANT */
  1412. : getConstantType(child, context);
  1413. if (constantType > 0 /* NOT_CONSTANT */) {
  1414. if (constantType < 3 /* CAN_STRINGIFY */) {
  1415. canStringify = false;
  1416. }
  1417. if (constantType >= 2 /* CAN_HOIST */) {
  1418. child.codegenNode.patchFlag =
  1419. -1 /* HOISTED */ + (` /* HOISTED */` );
  1420. child.codegenNode = context.hoist(child.codegenNode);
  1421. hasHoistedNode = true;
  1422. continue;
  1423. }
  1424. }
  1425. else {
  1426. // node may contain dynamic children, but its props may be eligible for
  1427. // hoisting.
  1428. const codegenNode = child.codegenNode;
  1429. if (codegenNode.type === 13 /* VNODE_CALL */) {
  1430. const flag = getPatchFlag(codegenNode);
  1431. if ((!flag ||
  1432. flag === 512 /* NEED_PATCH */ ||
  1433. flag === 1 /* TEXT */) &&
  1434. getGeneratedPropsConstantType(child, context) >=
  1435. 2 /* CAN_HOIST */) {
  1436. const props = getNodeProps(child);
  1437. if (props) {
  1438. codegenNode.props = context.hoist(props);
  1439. }
  1440. }
  1441. }
  1442. }
  1443. }
  1444. else if (child.type === 12 /* TEXT_CALL */) {
  1445. const contentType = getConstantType(child.content, context);
  1446. if (contentType > 0) {
  1447. if (contentType < 3 /* CAN_STRINGIFY */) {
  1448. canStringify = false;
  1449. }
  1450. if (contentType >= 2 /* CAN_HOIST */) {
  1451. child.codegenNode = context.hoist(child.codegenNode);
  1452. hasHoistedNode = true;
  1453. }
  1454. }
  1455. }
  1456. // walk further
  1457. if (child.type === 1 /* ELEMENT */) {
  1458. walk(child, context);
  1459. }
  1460. else if (child.type === 11 /* FOR */) {
  1461. // Do not hoist v-for single child because it has to be a block
  1462. walk(child, context, child.children.length === 1);
  1463. }
  1464. else if (child.type === 9 /* IF */) {
  1465. for (let i = 0; i < child.branches.length; i++) {
  1466. // Do not hoist v-if single child because it has to be a block
  1467. walk(child.branches[i], context, child.branches[i].children.length === 1);
  1468. }
  1469. }
  1470. }
  1471. if (canStringify && hasHoistedNode && context.transformHoist) {
  1472. context.transformHoist(children, context, node);
  1473. }
  1474. }
  1475. function getConstantType(node, context) {
  1476. const { constantCache } = context;
  1477. switch (node.type) {
  1478. case 1 /* ELEMENT */:
  1479. if (node.tagType !== 0 /* ELEMENT */) {
  1480. return 0 /* NOT_CONSTANT */;
  1481. }
  1482. const cached = constantCache.get(node);
  1483. if (cached !== undefined) {
  1484. return cached;
  1485. }
  1486. const codegenNode = node.codegenNode;
  1487. if (codegenNode.type !== 13 /* VNODE_CALL */) {
  1488. return 0 /* NOT_CONSTANT */;
  1489. }
  1490. const flag = getPatchFlag(codegenNode);
  1491. if (!flag) {
  1492. let returnType = 3 /* CAN_STRINGIFY */;
  1493. // Element itself has no patch flag. However we still need to check:
  1494. // 1. Even for a node with no patch flag, it is possible for it to contain
  1495. // non-hoistable expressions that refers to scope variables, e.g. compiler
  1496. // injected keys or cached event handlers. Therefore we need to always
  1497. // check the codegenNode's props to be sure.
  1498. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  1499. if (generatedPropsType === 0 /* NOT_CONSTANT */) {
  1500. constantCache.set(node, 0 /* NOT_CONSTANT */);
  1501. return 0 /* NOT_CONSTANT */;
  1502. }
  1503. if (generatedPropsType < returnType) {
  1504. returnType = generatedPropsType;
  1505. }
  1506. // 2. its children.
  1507. for (let i = 0; i < node.children.length; i++) {
  1508. const childType = getConstantType(node.children[i], context);
  1509. if (childType === 0 /* NOT_CONSTANT */) {
  1510. constantCache.set(node, 0 /* NOT_CONSTANT */);
  1511. return 0 /* NOT_CONSTANT */;
  1512. }
  1513. if (childType < returnType) {
  1514. returnType = childType;
  1515. }
  1516. }
  1517. // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
  1518. // type, check if any of the props can cause the type to be lowered
  1519. // we can skip can_patch because it's guaranteed by the absence of a
  1520. // patchFlag.
  1521. if (returnType > 1 /* CAN_SKIP_PATCH */) {
  1522. for (let i = 0; i < node.props.length; i++) {
  1523. const p = node.props[i];
  1524. if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
  1525. const expType = getConstantType(p.exp, context);
  1526. if (expType === 0 /* NOT_CONSTANT */) {
  1527. constantCache.set(node, 0 /* NOT_CONSTANT */);
  1528. return 0 /* NOT_CONSTANT */;
  1529. }
  1530. if (expType < returnType) {
  1531. returnType = expType;
  1532. }
  1533. }
  1534. }
  1535. }
  1536. // only svg/foreignObject could be block here, however if they are
  1537. // static then they don't need to be blocks since there will be no
  1538. // nested updates.
  1539. if (codegenNode.isBlock) {
  1540. codegenNode.isBlock = false;
  1541. context.helper(CREATE_VNODE);
  1542. }
  1543. constantCache.set(node, returnType);
  1544. return returnType;
  1545. }
  1546. else {
  1547. constantCache.set(node, 0 /* NOT_CONSTANT */);
  1548. return 0 /* NOT_CONSTANT */;
  1549. }
  1550. case 2 /* TEXT */:
  1551. case 3 /* COMMENT */:
  1552. return 3 /* CAN_STRINGIFY */;
  1553. case 9 /* IF */:
  1554. case 11 /* FOR */:
  1555. case 10 /* IF_BRANCH */:
  1556. return 0 /* NOT_CONSTANT */;
  1557. case 5 /* INTERPOLATION */:
  1558. case 12 /* TEXT_CALL */:
  1559. return getConstantType(node.content, context);
  1560. case 4 /* SIMPLE_EXPRESSION */:
  1561. return node.constType;
  1562. case 8 /* COMPOUND_EXPRESSION */:
  1563. let returnType = 3 /* CAN_STRINGIFY */;
  1564. for (let i = 0; i < node.children.length; i++) {
  1565. const child = node.children[i];
  1566. if (isString(child) || isSymbol(child)) {
  1567. continue;
  1568. }
  1569. const childType = getConstantType(child, context);
  1570. if (childType === 0 /* NOT_CONSTANT */) {
  1571. return 0 /* NOT_CONSTANT */;
  1572. }
  1573. else if (childType < returnType) {
  1574. returnType = childType;
  1575. }
  1576. }
  1577. return returnType;
  1578. default:
  1579. return 0 /* NOT_CONSTANT */;
  1580. }
  1581. }
  1582. function getGeneratedPropsConstantType(node, context) {
  1583. let returnType = 3 /* CAN_STRINGIFY */;
  1584. const props = getNodeProps(node);
  1585. if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  1586. const { properties } = props;
  1587. for (let i = 0; i < properties.length; i++) {
  1588. const { key, value } = properties[i];
  1589. const keyType = getConstantType(key, context);
  1590. if (keyType === 0 /* NOT_CONSTANT */) {
  1591. return keyType;
  1592. }
  1593. if (keyType < returnType) {
  1594. returnType = keyType;
  1595. }
  1596. if (value.type !== 4 /* SIMPLE_EXPRESSION */) {
  1597. return 0 /* NOT_CONSTANT */;
  1598. }
  1599. const valueType = getConstantType(value, context);
  1600. if (valueType === 0 /* NOT_CONSTANT */) {
  1601. return valueType;
  1602. }
  1603. if (valueType < returnType) {
  1604. returnType = valueType;
  1605. }
  1606. }
  1607. }
  1608. return returnType;
  1609. }
  1610. function getNodeProps(node) {
  1611. const codegenNode = node.codegenNode;
  1612. if (codegenNode.type === 13 /* VNODE_CALL */) {
  1613. return codegenNode.props;
  1614. }
  1615. }
  1616. function getPatchFlag(node) {
  1617. const flag = node.patchFlag;
  1618. return flag ? parseInt(flag, 10) : undefined;
  1619. }
  1620. function createTransformContext(root, { filename = '', prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = NOOP, isCustomElement = NOOP, expressionPlugins = [], scopeId = null, ssr = false, ssrCssVars = ``, bindingMetadata = EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError }) {
  1621. const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
  1622. const context = {
  1623. // options
  1624. selfName: nameMatch && capitalize(camelize(nameMatch[1])),
  1625. prefixIdentifiers,
  1626. hoistStatic,
  1627. cacheHandlers,
  1628. nodeTransforms,
  1629. directiveTransforms,
  1630. transformHoist,
  1631. isBuiltInComponent,
  1632. isCustomElement,
  1633. expressionPlugins,
  1634. scopeId,
  1635. ssr,
  1636. ssrCssVars,
  1637. bindingMetadata,
  1638. inline,
  1639. isTS,
  1640. onError,
  1641. // state
  1642. root,
  1643. helpers: new Set(),
  1644. components: new Set(),
  1645. directives: new Set(),
  1646. hoists: [],
  1647. imports: [],
  1648. constantCache: new Map(),
  1649. temps: 0,
  1650. cached: 0,
  1651. identifiers: Object.create(null),
  1652. scopes: {
  1653. vFor: 0,
  1654. vSlot: 0,
  1655. vPre: 0,
  1656. vOnce: 0
  1657. },
  1658. parent: null,
  1659. currentNode: root,
  1660. childIndex: 0,
  1661. // methods
  1662. helper(name) {
  1663. context.helpers.add(name);
  1664. return name;
  1665. },
  1666. helperString(name) {
  1667. return `_${helperNameMap[context.helper(name)]}`;
  1668. },
  1669. replaceNode(node) {
  1670. /* istanbul ignore if */
  1671. {
  1672. if (!context.currentNode) {
  1673. throw new Error(`Node being replaced is already removed.`);
  1674. }
  1675. if (!context.parent) {
  1676. throw new Error(`Cannot replace root node.`);
  1677. }
  1678. }
  1679. context.parent.children[context.childIndex] = context.currentNode = node;
  1680. },
  1681. removeNode(node) {
  1682. if (!context.parent) {
  1683. throw new Error(`Cannot remove root node.`);
  1684. }
  1685. const list = context.parent.children;
  1686. const removalIndex = node
  1687. ? list.indexOf(node)
  1688. : context.currentNode
  1689. ? context.childIndex
  1690. : -1;
  1691. /* istanbul ignore if */
  1692. if (removalIndex < 0) {
  1693. throw new Error(`node being removed is not a child of current parent`);
  1694. }
  1695. if (!node || node === context.currentNode) {
  1696. // current node removed
  1697. context.currentNode = null;
  1698. context.onNodeRemoved();
  1699. }
  1700. else {
  1701. // sibling node removed
  1702. if (context.childIndex > removalIndex) {
  1703. context.childIndex--;
  1704. context.onNodeRemoved();
  1705. }
  1706. }
  1707. context.parent.children.splice(removalIndex, 1);
  1708. },
  1709. onNodeRemoved: () => { },
  1710. addIdentifiers(exp) {
  1711. },
  1712. removeIdentifiers(exp) {
  1713. },
  1714. hoist(exp) {
  1715. context.hoists.push(exp);
  1716. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
  1717. identifier.hoisted = exp;
  1718. return identifier;
  1719. },
  1720. cache(exp, isVNode = false) {
  1721. return createCacheExpression(++context.cached, exp, isVNode);
  1722. }
  1723. };
  1724. return context;
  1725. }
  1726. function transform(root, options) {
  1727. const context = createTransformContext(root, options);
  1728. traverseNode(root, context);
  1729. if (options.hoistStatic) {
  1730. hoistStatic(root, context);
  1731. }
  1732. if (!options.ssr) {
  1733. createRootCodegen(root, context);
  1734. }
  1735. // finalize meta information
  1736. root.helpers = [...context.helpers];
  1737. root.components = [...context.components];
  1738. root.directives = [...context.directives];
  1739. root.imports = context.imports;
  1740. root.hoists = context.hoists;
  1741. root.temps = context.temps;
  1742. root.cached = context.cached;
  1743. }
  1744. function createRootCodegen(root, context) {
  1745. const { helper } = context;
  1746. const { children } = root;
  1747. if (children.length === 1) {
  1748. const child = children[0];
  1749. // if the single child is an element, turn it into a block.
  1750. if (isSingleElementRoot(root, child) && child.codegenNode) {
  1751. // single element root is never hoisted so codegenNode will never be
  1752. // SimpleExpressionNode
  1753. const codegenNode = child.codegenNode;
  1754. if (codegenNode.type === 13 /* VNODE_CALL */) {
  1755. codegenNode.isBlock = true;
  1756. helper(OPEN_BLOCK);
  1757. helper(CREATE_BLOCK);
  1758. }
  1759. root.codegenNode = codegenNode;
  1760. }
  1761. else {
  1762. // - single <slot/>, IfNode, ForNode: already blocks.
  1763. // - single text node: always patched.
  1764. // root codegen falls through via genNode()
  1765. root.codegenNode = child;
  1766. }
  1767. }
  1768. else if (children.length > 1) {
  1769. // root has multiple nodes - return a fragment block.
  1770. let patchFlag = 64 /* STABLE_FRAGMENT */;
  1771. let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
  1772. // check if the fragment actually contains a single valid child with
  1773. // the rest being comments
  1774. if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
  1775. patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
  1776. patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
  1777. }
  1778. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true);
  1779. }
  1780. else ;
  1781. }
  1782. function traverseChildren(parent, context) {
  1783. let i = 0;
  1784. const nodeRemoved = () => {
  1785. i--;
  1786. };
  1787. for (; i < parent.children.length; i++) {
  1788. const child = parent.children[i];
  1789. if (isString(child))
  1790. continue;
  1791. context.parent = parent;
  1792. context.childIndex = i;
  1793. context.onNodeRemoved = nodeRemoved;
  1794. traverseNode(child, context);
  1795. }
  1796. }
  1797. function traverseNode(node, context) {
  1798. context.currentNode = node;
  1799. // apply transform plugins
  1800. const { nodeTransforms } = context;
  1801. const exitFns = [];
  1802. for (let i = 0; i < nodeTransforms.length; i++) {
  1803. const onExit = nodeTransforms[i](node, context);
  1804. if (onExit) {
  1805. if (isArray(onExit)) {
  1806. exitFns.push(...onExit);
  1807. }
  1808. else {
  1809. exitFns.push(onExit);
  1810. }
  1811. }
  1812. if (!context.currentNode) {
  1813. // node was removed
  1814. return;
  1815. }
  1816. else {
  1817. // node may have been replaced
  1818. node = context.currentNode;
  1819. }
  1820. }
  1821. switch (node.type) {
  1822. case 3 /* COMMENT */:
  1823. if (!context.ssr) {
  1824. // inject import for the Comment symbol, which is needed for creating
  1825. // comment nodes with `createVNode`
  1826. context.helper(CREATE_COMMENT);
  1827. }
  1828. break;
  1829. case 5 /* INTERPOLATION */:
  1830. // no need to traverse, but we need to inject toString helper
  1831. if (!context.ssr) {
  1832. context.helper(TO_DISPLAY_STRING);
  1833. }
  1834. break;
  1835. // for container types, further traverse downwards
  1836. case 9 /* IF */:
  1837. for (let i = 0; i < node.branches.length; i++) {
  1838. traverseNode(node.branches[i], context);
  1839. }
  1840. break;
  1841. case 10 /* IF_BRANCH */:
  1842. case 11 /* FOR */:
  1843. case 1 /* ELEMENT */:
  1844. case 0 /* ROOT */:
  1845. traverseChildren(node, context);
  1846. break;
  1847. }
  1848. // exit transforms
  1849. context.currentNode = node;
  1850. let i = exitFns.length;
  1851. while (i--) {
  1852. exitFns[i]();
  1853. }
  1854. }
  1855. function createStructuralDirectiveTransform(name, fn) {
  1856. const matches = isString(name)
  1857. ? (n) => n === name
  1858. : (n) => name.test(n);
  1859. return (node, context) => {
  1860. if (node.type === 1 /* ELEMENT */) {
  1861. const { props } = node;
  1862. // structural directive transforms are not concerned with slots
  1863. // as they are handled separately in vSlot.ts
  1864. if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
  1865. return;
  1866. }
  1867. const exitFns = [];
  1868. for (let i = 0; i < props.length; i++) {
  1869. const prop = props[i];
  1870. if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
  1871. // structural directives are removed to avoid infinite recursion
  1872. // also we remove them *before* applying so that it can further
  1873. // traverse itself in case it moves the node around
  1874. props.splice(i, 1);
  1875. i--;
  1876. const onExit = fn(node, prop, context);
  1877. if (onExit)
  1878. exitFns.push(onExit);
  1879. }
  1880. }
  1881. return exitFns;
  1882. }
  1883. };
  1884. }
  1885. const PURE_ANNOTATION = `/*#__PURE__*/`;
  1886. function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssr = false }) {
  1887. const context = {
  1888. mode,
  1889. prefixIdentifiers,
  1890. sourceMap,
  1891. filename,
  1892. scopeId,
  1893. optimizeImports,
  1894. runtimeGlobalName,
  1895. runtimeModuleName,
  1896. ssr,
  1897. source: ast.loc.source,
  1898. code: ``,
  1899. column: 1,
  1900. line: 1,
  1901. offset: 0,
  1902. indentLevel: 0,
  1903. pure: false,
  1904. map: undefined,
  1905. helper(key) {
  1906. return `_${helperNameMap[key]}`;
  1907. },
  1908. push(code, node) {
  1909. context.code += code;
  1910. },
  1911. indent() {
  1912. newline(++context.indentLevel);
  1913. },
  1914. deindent(withoutNewLine = false) {
  1915. if (withoutNewLine) {
  1916. --context.indentLevel;
  1917. }
  1918. else {
  1919. newline(--context.indentLevel);
  1920. }
  1921. },
  1922. newline() {
  1923. newline(context.indentLevel);
  1924. }
  1925. };
  1926. function newline(n) {
  1927. context.push('\n' + ` `.repeat(n));
  1928. }
  1929. return context;
  1930. }
  1931. function generate(ast, options = {}) {
  1932. const context = createCodegenContext(ast, options);
  1933. if (options.onContextCreated)
  1934. options.onContextCreated(context);
  1935. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  1936. const hasHelpers = ast.helpers.length > 0;
  1937. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  1938. // preambles
  1939. // in setup() inline mode, the preamble is generated in a sub context
  1940. // and returned separately.
  1941. const preambleContext = context;
  1942. {
  1943. genFunctionPreamble(ast, preambleContext);
  1944. }
  1945. // enter render function
  1946. const functionName = ssr ? `ssrRender` : `render`;
  1947. const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
  1948. const signature = args.join(', ');
  1949. {
  1950. push(`function ${functionName}(${signature}) {`);
  1951. }
  1952. indent();
  1953. if (useWithBlock) {
  1954. push(`with (_ctx) {`);
  1955. indent();
  1956. // function mode const declarations should be inside with block
  1957. // also they should be renamed to avoid collision with user properties
  1958. if (hasHelpers) {
  1959. push(`const { ${ast.helpers
  1960. .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
  1961. .join(', ')} } = _Vue`);
  1962. push(`\n`);
  1963. newline();
  1964. }
  1965. }
  1966. // generate asset resolution statements
  1967. if (ast.components.length) {
  1968. genAssets(ast.components, 'component', context);
  1969. if (ast.directives.length || ast.temps > 0) {
  1970. newline();
  1971. }
  1972. }
  1973. if (ast.directives.length) {
  1974. genAssets(ast.directives, 'directive', context);
  1975. if (ast.temps > 0) {
  1976. newline();
  1977. }
  1978. }
  1979. if (ast.temps > 0) {
  1980. push(`let `);
  1981. for (let i = 0; i < ast.temps; i++) {
  1982. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  1983. }
  1984. }
  1985. if (ast.components.length || ast.directives.length || ast.temps) {
  1986. push(`\n`);
  1987. newline();
  1988. }
  1989. // generate the VNode tree expression
  1990. if (!ssr) {
  1991. push(`return `);
  1992. }
  1993. if (ast.codegenNode) {
  1994. genNode(ast.codegenNode, context);
  1995. }
  1996. else {
  1997. push(`null`);
  1998. }
  1999. if (useWithBlock) {
  2000. deindent();
  2001. push(`}`);
  2002. }
  2003. deindent();
  2004. push(`}`);
  2005. return {
  2006. ast,
  2007. code: context.code,
  2008. preamble: ``,
  2009. // SourceMapGenerator does have toJSON() method but it's not in the types
  2010. map: context.map ? context.map.toJSON() : undefined
  2011. };
  2012. }
  2013. function genFunctionPreamble(ast, context) {
  2014. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context;
  2015. const VueBinding = runtimeGlobalName;
  2016. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  2017. // Generate const declaration for helpers
  2018. // In prefix mode, we place the const declaration at top so it's done
  2019. // only once; But if we not prefixing, we place the declaration inside the
  2020. // with block so it doesn't incur the `in` check cost for every helper access.
  2021. if (ast.helpers.length > 0) {
  2022. {
  2023. // "with" mode.
  2024. // save Vue in a separate variable to avoid collision
  2025. push(`const _Vue = ${VueBinding}\n`);
  2026. // in "with" mode, helpers are declared inside the with block to avoid
  2027. // has check cost, but hoists are lifted out of the function - we need
  2028. // to provide the helper here.
  2029. if (ast.hoists.length) {
  2030. const staticHelpers = [
  2031. CREATE_VNODE,
  2032. CREATE_COMMENT,
  2033. CREATE_TEXT,
  2034. CREATE_STATIC
  2035. ]
  2036. .filter(helper => ast.helpers.includes(helper))
  2037. .map(aliasHelper)
  2038. .join(', ');
  2039. push(`const { ${staticHelpers} } = _Vue\n`);
  2040. }
  2041. }
  2042. }
  2043. genHoists(ast.hoists, context);
  2044. newline();
  2045. push(`return `);
  2046. }
  2047. function genAssets(assets, type, { helper, push, newline }) {
  2048. const resolver = helper(type === 'component' ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE);
  2049. for (let i = 0; i < assets.length; i++) {
  2050. const id = assets[i];
  2051. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)})`);
  2052. if (i < assets.length - 1) {
  2053. newline();
  2054. }
  2055. }
  2056. }
  2057. function genHoists(hoists, context) {
  2058. if (!hoists.length) {
  2059. return;
  2060. }
  2061. context.pure = true;
  2062. const { push, newline, helper, scopeId, mode } = context;
  2063. newline();
  2064. hoists.forEach((exp, i) => {
  2065. if (exp) {
  2066. push(`const _hoisted_${i + 1} = `);
  2067. genNode(exp, context);
  2068. newline();
  2069. }
  2070. });
  2071. context.pure = false;
  2072. }
  2073. function isText$1(n) {
  2074. return (isString(n) ||
  2075. n.type === 4 /* SIMPLE_EXPRESSION */ ||
  2076. n.type === 2 /* TEXT */ ||
  2077. n.type === 5 /* INTERPOLATION */ ||
  2078. n.type === 8 /* COMPOUND_EXPRESSION */);
  2079. }
  2080. function genNodeListAsArray(nodes, context) {
  2081. const multilines = nodes.length > 3 ||
  2082. (nodes.some(n => isArray(n) || !isText$1(n)));
  2083. context.push(`[`);
  2084. multilines && context.indent();
  2085. genNodeList(nodes, context, multilines);
  2086. multilines && context.deindent();
  2087. context.push(`]`);
  2088. }
  2089. function genNodeList(nodes, context, multilines = false, comma = true) {
  2090. const { push, newline } = context;
  2091. for (let i = 0; i < nodes.length; i++) {
  2092. const node = nodes[i];
  2093. if (isString(node)) {
  2094. push(node);
  2095. }
  2096. else if (isArray(node)) {
  2097. genNodeListAsArray(node, context);
  2098. }
  2099. else {
  2100. genNode(node, context);
  2101. }
  2102. if (i < nodes.length - 1) {
  2103. if (multilines) {
  2104. comma && push(',');
  2105. newline();
  2106. }
  2107. else {
  2108. comma && push(', ');
  2109. }
  2110. }
  2111. }
  2112. }
  2113. function genNode(node, context) {
  2114. if (isString(node)) {
  2115. context.push(node);
  2116. return;
  2117. }
  2118. if (isSymbol(node)) {
  2119. context.push(context.helper(node));
  2120. return;
  2121. }
  2122. switch (node.type) {
  2123. case 1 /* ELEMENT */:
  2124. case 9 /* IF */:
  2125. case 11 /* FOR */:
  2126. assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  2127. `Apply appropriate transforms first.`);
  2128. genNode(node.codegenNode, context);
  2129. break;
  2130. case 2 /* TEXT */:
  2131. genText(node, context);
  2132. break;
  2133. case 4 /* SIMPLE_EXPRESSION */:
  2134. genExpression(node, context);
  2135. break;
  2136. case 5 /* INTERPOLATION */:
  2137. genInterpolation(node, context);
  2138. break;
  2139. case 12 /* TEXT_CALL */:
  2140. genNode(node.codegenNode, context);
  2141. break;
  2142. case 8 /* COMPOUND_EXPRESSION */:
  2143. genCompoundExpression(node, context);
  2144. break;
  2145. case 3 /* COMMENT */:
  2146. genComment(node, context);
  2147. break;
  2148. case 13 /* VNODE_CALL */:
  2149. genVNodeCall(node, context);
  2150. break;
  2151. case 14 /* JS_CALL_EXPRESSION */:
  2152. genCallExpression(node, context);
  2153. break;
  2154. case 15 /* JS_OBJECT_EXPRESSION */:
  2155. genObjectExpression(node, context);
  2156. break;
  2157. case 17 /* JS_ARRAY_EXPRESSION */:
  2158. genArrayExpression(node, context);
  2159. break;
  2160. case 18 /* JS_FUNCTION_EXPRESSION */:
  2161. genFunctionExpression(node, context);
  2162. break;
  2163. case 19 /* JS_CONDITIONAL_EXPRESSION */:
  2164. genConditionalExpression(node, context);
  2165. break;
  2166. case 20 /* JS_CACHE_EXPRESSION */:
  2167. genCacheExpression(node, context);
  2168. break;
  2169. // SSR only types
  2170. case 21 /* JS_BLOCK_STATEMENT */:
  2171. break;
  2172. case 22 /* JS_TEMPLATE_LITERAL */:
  2173. break;
  2174. case 23 /* JS_IF_STATEMENT */:
  2175. break;
  2176. case 24 /* JS_ASSIGNMENT_EXPRESSION */:
  2177. break;
  2178. case 25 /* JS_SEQUENCE_EXPRESSION */:
  2179. break;
  2180. case 26 /* JS_RETURN_STATEMENT */:
  2181. break;
  2182. /* istanbul ignore next */
  2183. case 10 /* IF_BRANCH */:
  2184. // noop
  2185. break;
  2186. default:
  2187. {
  2188. assert(false, `unhandled codegen node type: ${node.type}`);
  2189. // make sure we exhaust all possible types
  2190. const exhaustiveCheck = node;
  2191. return exhaustiveCheck;
  2192. }
  2193. }
  2194. }
  2195. function genText(node, context) {
  2196. context.push(JSON.stringify(node.content), node);
  2197. }
  2198. function genExpression(node, context) {
  2199. const { content, isStatic } = node;
  2200. context.push(isStatic ? JSON.stringify(content) : content, node);
  2201. }
  2202. function genInterpolation(node, context) {
  2203. const { push, helper, pure } = context;
  2204. if (pure)
  2205. push(PURE_ANNOTATION);
  2206. push(`${helper(TO_DISPLAY_STRING)}(`);
  2207. genNode(node.content, context);
  2208. push(`)`);
  2209. }
  2210. function genCompoundExpression(node, context) {
  2211. for (let i = 0; i < node.children.length; i++) {
  2212. const child = node.children[i];
  2213. if (isString(child)) {
  2214. context.push(child);
  2215. }
  2216. else {
  2217. genNode(child, context);
  2218. }
  2219. }
  2220. }
  2221. function genExpressionAsPropertyKey(node, context) {
  2222. const { push } = context;
  2223. if (node.type === 8 /* COMPOUND_EXPRESSION */) {
  2224. push(`[`);
  2225. genCompoundExpression(node, context);
  2226. push(`]`);
  2227. }
  2228. else if (node.isStatic) {
  2229. // only quote keys if necessary
  2230. const text = isSimpleIdentifier(node.content)
  2231. ? node.content
  2232. : JSON.stringify(node.content);
  2233. push(text, node);
  2234. }
  2235. else {
  2236. push(`[${node.content}]`, node);
  2237. }
  2238. }
  2239. function genComment(node, context) {
  2240. {
  2241. const { push, helper, pure } = context;
  2242. if (pure) {
  2243. push(PURE_ANNOTATION);
  2244. }
  2245. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  2246. }
  2247. }
  2248. function genVNodeCall(node, context) {
  2249. const { push, helper, pure } = context;
  2250. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking } = node;
  2251. if (directives) {
  2252. push(helper(WITH_DIRECTIVES) + `(`);
  2253. }
  2254. if (isBlock) {
  2255. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  2256. }
  2257. if (pure) {
  2258. push(PURE_ANNOTATION);
  2259. }
  2260. push(helper(isBlock ? CREATE_BLOCK : CREATE_VNODE) + `(`, node);
  2261. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  2262. push(`)`);
  2263. if (isBlock) {
  2264. push(`)`);
  2265. }
  2266. if (directives) {
  2267. push(`, `);
  2268. genNode(directives, context);
  2269. push(`)`);
  2270. }
  2271. }
  2272. function genNullableArgs(args) {
  2273. let i = args.length;
  2274. while (i--) {
  2275. if (args[i] != null)
  2276. break;
  2277. }
  2278. return args.slice(0, i + 1).map(arg => arg || `null`);
  2279. }
  2280. // JavaScript
  2281. function genCallExpression(node, context) {
  2282. const { push, helper, pure } = context;
  2283. const callee = isString(node.callee) ? node.callee : helper(node.callee);
  2284. if (pure) {
  2285. push(PURE_ANNOTATION);
  2286. }
  2287. push(callee + `(`, node);
  2288. genNodeList(node.arguments, context);
  2289. push(`)`);
  2290. }
  2291. function genObjectExpression(node, context) {
  2292. const { push, indent, deindent, newline } = context;
  2293. const { properties } = node;
  2294. if (!properties.length) {
  2295. push(`{}`, node);
  2296. return;
  2297. }
  2298. const multilines = properties.length > 1 ||
  2299. (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
  2300. push(multilines ? `{` : `{ `);
  2301. multilines && indent();
  2302. for (let i = 0; i < properties.length; i++) {
  2303. const { key, value } = properties[i];
  2304. // key
  2305. genExpressionAsPropertyKey(key, context);
  2306. push(`: `);
  2307. // value
  2308. genNode(value, context);
  2309. if (i < properties.length - 1) {
  2310. // will only reach this if it's multilines
  2311. push(`,`);
  2312. newline();
  2313. }
  2314. }
  2315. multilines && deindent();
  2316. push(multilines ? `}` : ` }`);
  2317. }
  2318. function genArrayExpression(node, context) {
  2319. genNodeListAsArray(node.elements, context);
  2320. }
  2321. function genFunctionExpression(node, context) {
  2322. const { push, indent, deindent, scopeId, mode } = context;
  2323. const { params, returns, body, newline, isSlot } = node;
  2324. if (isSlot) {
  2325. push(`_${helperNameMap[WITH_CTX]}(`);
  2326. }
  2327. push(`(`, node);
  2328. if (isArray(params)) {
  2329. genNodeList(params, context);
  2330. }
  2331. else if (params) {
  2332. genNode(params, context);
  2333. }
  2334. push(`) => `);
  2335. if (newline || body) {
  2336. push(`{`);
  2337. indent();
  2338. }
  2339. if (returns) {
  2340. if (newline) {
  2341. push(`return `);
  2342. }
  2343. if (isArray(returns)) {
  2344. genNodeListAsArray(returns, context);
  2345. }
  2346. else {
  2347. genNode(returns, context);
  2348. }
  2349. }
  2350. else if (body) {
  2351. genNode(body, context);
  2352. }
  2353. if (newline || body) {
  2354. deindent();
  2355. push(`}`);
  2356. }
  2357. if (isSlot) {
  2358. push(`)`);
  2359. }
  2360. }
  2361. function genConditionalExpression(node, context) {
  2362. const { test, consequent, alternate, newline: needNewline } = node;
  2363. const { push, indent, deindent, newline } = context;
  2364. if (test.type === 4 /* SIMPLE_EXPRESSION */) {
  2365. const needsParens = !isSimpleIdentifier(test.content);
  2366. needsParens && push(`(`);
  2367. genExpression(test, context);
  2368. needsParens && push(`)`);
  2369. }
  2370. else {
  2371. push(`(`);
  2372. genNode(test, context);
  2373. push(`)`);
  2374. }
  2375. needNewline && indent();
  2376. context.indentLevel++;
  2377. needNewline || push(` `);
  2378. push(`? `);
  2379. genNode(consequent, context);
  2380. context.indentLevel--;
  2381. needNewline && newline();
  2382. needNewline || push(` `);
  2383. push(`: `);
  2384. const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
  2385. if (!isNested) {
  2386. context.indentLevel++;
  2387. }
  2388. genNode(alternate, context);
  2389. if (!isNested) {
  2390. context.indentLevel--;
  2391. }
  2392. needNewline && deindent(true /* without newline */);
  2393. }
  2394. function genCacheExpression(node, context) {
  2395. const { push, helper, indent, deindent, newline } = context;
  2396. push(`_cache[${node.index}] || (`);
  2397. if (node.isVNode) {
  2398. indent();
  2399. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  2400. newline();
  2401. }
  2402. push(`_cache[${node.index}] = `);
  2403. genNode(node.value, context);
  2404. if (node.isVNode) {
  2405. push(`,`);
  2406. newline();
  2407. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  2408. newline();
  2409. push(`_cache[${node.index}]`);
  2410. deindent();
  2411. }
  2412. push(`)`);
  2413. }
  2414. // these keywords should not appear inside expressions, but operators like
  2415. // typeof, instanceof and in are allowed
  2416. const prohibitedKeywordRE = new RegExp('\\b' +
  2417. ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
  2418. 'super,throw,while,yield,delete,export,import,return,switch,default,' +
  2419. 'extends,finally,continue,debugger,function,arguments,typeof,void')
  2420. .split(',')
  2421. .join('\\b|\\b') +
  2422. '\\b');
  2423. // strip strings in expressions
  2424. const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
  2425. /**
  2426. * Validate a non-prefixed expression.
  2427. * This is only called when using the in-browser runtime compiler since it
  2428. * doesn't prefix expressions.
  2429. */
  2430. function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
  2431. const exp = node.content;
  2432. // empty expressions are validated per-directive since some directives
  2433. // do allow empty expressions.
  2434. if (!exp.trim()) {
  2435. return;
  2436. }
  2437. try {
  2438. new Function(asRawStatements
  2439. ? ` ${exp} `
  2440. : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
  2441. }
  2442. catch (e) {
  2443. let message = e.message;
  2444. const keywordMatch = exp
  2445. .replace(stripStringRE, '')
  2446. .match(prohibitedKeywordRE);
  2447. if (keywordMatch) {
  2448. message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
  2449. }
  2450. context.onError(createCompilerError(43 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
  2451. }
  2452. }
  2453. const transformExpression = (node, context) => {
  2454. if (node.type === 5 /* INTERPOLATION */) {
  2455. node.content = processExpression(node.content, context);
  2456. }
  2457. else if (node.type === 1 /* ELEMENT */) {
  2458. // handle directives on element
  2459. for (let i = 0; i < node.props.length; i++) {
  2460. const dir = node.props[i];
  2461. // do not process for v-on & v-for since they are special handled
  2462. if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
  2463. const exp = dir.exp;
  2464. const arg = dir.arg;
  2465. // do not process exp if this is v-on:arg - we need special handling
  2466. // for wrapping inline statements.
  2467. if (exp &&
  2468. exp.type === 4 /* SIMPLE_EXPRESSION */ &&
  2469. !(dir.name === 'on' && arg)) {
  2470. dir.exp = processExpression(exp, context,
  2471. // slot args must be processed as function params
  2472. dir.name === 'slot');
  2473. }
  2474. if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
  2475. dir.arg = processExpression(arg, context);
  2476. }
  2477. }
  2478. }
  2479. }
  2480. };
  2481. // Important: since this function uses Node.js only dependencies, it should
  2482. // always be used with a leading !true check so that it can be
  2483. // tree-shaken from the browser build.
  2484. function processExpression(node, context,
  2485. // some expressions like v-slot props & v-for aliases should be parsed as
  2486. // function params
  2487. asParams = false,
  2488. // v-on handler values may contain multiple statements
  2489. asRawStatements = false) {
  2490. {
  2491. {
  2492. // simple in-browser validation (same logic in 2.x)
  2493. validateBrowserExpression(node, context, asParams, asRawStatements);
  2494. }
  2495. return node;
  2496. }
  2497. }
  2498. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  2499. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  2500. // #1587: We need to dynamically increment the key based on the current
  2501. // node's sibling nodes, since chained v-if/else branches are
  2502. // rendered at the same depth
  2503. const siblings = context.parent.children;
  2504. let i = siblings.indexOf(ifNode);
  2505. let key = 0;
  2506. while (i-- >= 0) {
  2507. const sibling = siblings[i];
  2508. if (sibling && sibling.type === 9 /* IF */) {
  2509. key += sibling.branches.length;
  2510. }
  2511. }
  2512. // Exit callback. Complete the codegenNode when all children have been
  2513. // transformed.
  2514. return () => {
  2515. if (isRoot) {
  2516. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  2517. }
  2518. else {
  2519. // attach this branch's codegen node to the v-if root.
  2520. const parentCondition = getParentCondition(ifNode.codegenNode);
  2521. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  2522. }
  2523. };
  2524. });
  2525. });
  2526. // target-agnostic transform used for both Client and SSR
  2527. function processIf(node, dir, context, processCodegen) {
  2528. if (dir.name !== 'else' &&
  2529. (!dir.exp || !dir.exp.content.trim())) {
  2530. const loc = dir.exp ? dir.exp.loc : node.loc;
  2531. context.onError(createCompilerError(27 /* X_V_IF_NO_EXPRESSION */, dir.loc));
  2532. dir.exp = createSimpleExpression(`true`, false, loc);
  2533. }
  2534. if (dir.exp) {
  2535. validateBrowserExpression(dir.exp, context);
  2536. }
  2537. if (dir.name === 'if') {
  2538. const branch = createIfBranch(node, dir);
  2539. const ifNode = {
  2540. type: 9 /* IF */,
  2541. loc: node.loc,
  2542. branches: [branch]
  2543. };
  2544. context.replaceNode(ifNode);
  2545. if (processCodegen) {
  2546. return processCodegen(ifNode, branch, true);
  2547. }
  2548. }
  2549. else {
  2550. // locate the adjacent v-if
  2551. const siblings = context.parent.children;
  2552. const comments = [];
  2553. let i = siblings.indexOf(node);
  2554. while (i-- >= -1) {
  2555. const sibling = siblings[i];
  2556. if (sibling && sibling.type === 3 /* COMMENT */) {
  2557. context.removeNode(sibling);
  2558. comments.unshift(sibling);
  2559. continue;
  2560. }
  2561. if (sibling &&
  2562. sibling.type === 2 /* TEXT */ &&
  2563. !sibling.content.trim().length) {
  2564. context.removeNode(sibling);
  2565. continue;
  2566. }
  2567. if (sibling && sibling.type === 9 /* IF */) {
  2568. // move the node to the if node's branches
  2569. context.removeNode();
  2570. const branch = createIfBranch(node, dir);
  2571. if (comments.length) {
  2572. branch.children = [...comments, ...branch.children];
  2573. }
  2574. // check if user is forcing same key on different branches
  2575. {
  2576. const key = branch.userKey;
  2577. if (key) {
  2578. sibling.branches.forEach(({ userKey }) => {
  2579. if (isSameKey(userKey, key)) {
  2580. context.onError(createCompilerError(28 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
  2581. }
  2582. });
  2583. }
  2584. }
  2585. sibling.branches.push(branch);
  2586. const onExit = processCodegen && processCodegen(sibling, branch, false);
  2587. // since the branch was removed, it will not be traversed.
  2588. // make sure to traverse here.
  2589. traverseNode(branch, context);
  2590. // call on exit
  2591. if (onExit)
  2592. onExit();
  2593. // make sure to reset currentNode after traversal to indicate this
  2594. // node has been removed.
  2595. context.currentNode = null;
  2596. }
  2597. else {
  2598. context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  2599. }
  2600. break;
  2601. }
  2602. }
  2603. }
  2604. function createIfBranch(node, dir) {
  2605. return {
  2606. type: 10 /* IF_BRANCH */,
  2607. loc: node.loc,
  2608. condition: dir.name === 'else' ? undefined : dir.exp,
  2609. children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
  2610. ? node.children
  2611. : [node],
  2612. userKey: findProp(node, `key`)
  2613. };
  2614. }
  2615. function createCodegenNodeForBranch(branch, keyIndex, context) {
  2616. if (branch.condition) {
  2617. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  2618. // make sure to pass in asBlock: true so that the comment node call
  2619. // closes the current block.
  2620. createCallExpression(context.helper(CREATE_COMMENT), [
  2621. '"v-if"' ,
  2622. 'true'
  2623. ]));
  2624. }
  2625. else {
  2626. return createChildrenCodegenNode(branch, keyIndex, context);
  2627. }
  2628. }
  2629. function createChildrenCodegenNode(branch, keyIndex, context) {
  2630. const { helper } = context;
  2631. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
  2632. const { children } = branch;
  2633. const firstChild = children[0];
  2634. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
  2635. if (needFragmentWrapper) {
  2636. if (children.length === 1 && firstChild.type === 11 /* FOR */) {
  2637. // optimize away nested fragments when child is a ForNode
  2638. const vnodeCall = firstChild.codegenNode;
  2639. injectProp(vnodeCall, keyProperty, context);
  2640. return vnodeCall;
  2641. }
  2642. else {
  2643. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, 64 /* STABLE_FRAGMENT */ +
  2644. (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
  2645. ), undefined, undefined, true, false, branch.loc);
  2646. }
  2647. }
  2648. else {
  2649. const vnodeCall = firstChild
  2650. .codegenNode;
  2651. // Change createVNode to createBlock.
  2652. if (vnodeCall.type === 13 /* VNODE_CALL */) {
  2653. vnodeCall.isBlock = true;
  2654. helper(OPEN_BLOCK);
  2655. helper(CREATE_BLOCK);
  2656. }
  2657. // inject branch key
  2658. injectProp(vnodeCall, keyProperty, context);
  2659. return vnodeCall;
  2660. }
  2661. }
  2662. function isSameKey(a, b) {
  2663. if (!a || a.type !== b.type) {
  2664. return false;
  2665. }
  2666. if (a.type === 6 /* ATTRIBUTE */) {
  2667. if (a.value.content !== b.value.content) {
  2668. return false;
  2669. }
  2670. }
  2671. else {
  2672. // directive
  2673. const exp = a.exp;
  2674. const branchExp = b.exp;
  2675. if (exp.type !== branchExp.type) {
  2676. return false;
  2677. }
  2678. if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
  2679. (exp.isStatic !== branchExp.isStatic ||
  2680. exp.content !== branchExp.content)) {
  2681. return false;
  2682. }
  2683. }
  2684. return true;
  2685. }
  2686. function getParentCondition(node) {
  2687. while (true) {
  2688. if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  2689. if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  2690. node = node.alternate;
  2691. }
  2692. else {
  2693. return node;
  2694. }
  2695. }
  2696. else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
  2697. node = node.value;
  2698. }
  2699. }
  2700. }
  2701. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  2702. const { helper } = context;
  2703. return processFor(node, dir, context, forNode => {
  2704. // create the loop render function expression now, and add the
  2705. // iterator on exit after all children have been traversed
  2706. const renderExp = createCallExpression(helper(RENDER_LIST), [
  2707. forNode.source
  2708. ]);
  2709. const keyProp = findProp(node, `key`);
  2710. const keyProperty = keyProp
  2711. ? createObjectProperty(`key`, keyProp.type === 6 /* ATTRIBUTE */
  2712. ? createSimpleExpression(keyProp.value.content, true)
  2713. : keyProp.exp)
  2714. : null;
  2715. const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
  2716. forNode.source.constType > 0 /* NOT_CONSTANT */;
  2717. const fragmentFlag = isStableFragment
  2718. ? 64 /* STABLE_FRAGMENT */
  2719. : keyProp
  2720. ? 128 /* KEYED_FRAGMENT */
  2721. : 256 /* UNKEYED_FRAGMENT */;
  2722. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
  2723. (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, node.loc);
  2724. return () => {
  2725. // finish the codegen now that all children have been traversed
  2726. let childBlock;
  2727. const isTemplate = isTemplateNode(node);
  2728. const { children } = forNode;
  2729. // check <template v-for> key placement
  2730. if (isTemplate) {
  2731. node.children.some(c => {
  2732. if (c.type === 1 /* ELEMENT */) {
  2733. const key = findProp(c, 'key');
  2734. if (key) {
  2735. context.onError(createCompilerError(32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  2736. return true;
  2737. }
  2738. }
  2739. });
  2740. }
  2741. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
  2742. const slotOutlet = isSlotOutlet(node)
  2743. ? node
  2744. : isTemplate &&
  2745. node.children.length === 1 &&
  2746. isSlotOutlet(node.children[0])
  2747. ? node.children[0] // api-extractor somehow fails to infer this
  2748. : null;
  2749. if (slotOutlet) {
  2750. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  2751. childBlock = slotOutlet.codegenNode;
  2752. if (isTemplate && keyProperty) {
  2753. // <template v-for="..." :key="..."><slot/></template>
  2754. // we need to inject the key to the renderSlot() call.
  2755. // the props for renderSlot is passed as the 3rd argument.
  2756. injectProp(childBlock, keyProperty, context);
  2757. }
  2758. }
  2759. else if (needFragmentWrapper) {
  2760. // <template v-for="..."> with text or multi-elements
  2761. // should generate a fragment block for each loop
  2762. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
  2763. (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
  2764. ), undefined, undefined, true);
  2765. }
  2766. else {
  2767. // Normal element v-for. Directly use the child's codegenNode
  2768. // but mark it as a block.
  2769. childBlock = children[0]
  2770. .codegenNode;
  2771. if (isTemplate && keyProperty) {
  2772. injectProp(childBlock, keyProperty, context);
  2773. }
  2774. childBlock.isBlock = !isStableFragment;
  2775. if (childBlock.isBlock) {
  2776. helper(OPEN_BLOCK);
  2777. helper(CREATE_BLOCK);
  2778. }
  2779. else {
  2780. helper(CREATE_VNODE);
  2781. }
  2782. }
  2783. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  2784. };
  2785. });
  2786. });
  2787. // target-agnostic transform used for both Client and SSR
  2788. function processFor(node, dir, context, processCodegen) {
  2789. if (!dir.exp) {
  2790. context.onError(createCompilerError(30 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
  2791. return;
  2792. }
  2793. const parseResult = parseForExpression(
  2794. // can only be simple expression because vFor transform is applied
  2795. // before expression transform.
  2796. dir.exp, context);
  2797. if (!parseResult) {
  2798. context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  2799. return;
  2800. }
  2801. const { addIdentifiers, removeIdentifiers, scopes } = context;
  2802. const { source, value, key, index } = parseResult;
  2803. const forNode = {
  2804. type: 11 /* FOR */,
  2805. loc: dir.loc,
  2806. source,
  2807. valueAlias: value,
  2808. keyAlias: key,
  2809. objectIndexAlias: index,
  2810. parseResult,
  2811. children: isTemplateNode(node) ? node.children : [node]
  2812. };
  2813. context.replaceNode(forNode);
  2814. // bookkeeping
  2815. scopes.vFor++;
  2816. const onExit = processCodegen && processCodegen(forNode);
  2817. return () => {
  2818. scopes.vFor--;
  2819. if (onExit)
  2820. onExit();
  2821. };
  2822. }
  2823. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  2824. // This regex doesn't cover the case if key or index aliases have destructuring,
  2825. // but those do not make sense in the first place, so this works in practice.
  2826. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  2827. const stripParensRE = /^\(|\)$/g;
  2828. function parseForExpression(input, context) {
  2829. const loc = input.loc;
  2830. const exp = input.content;
  2831. const inMatch = exp.match(forAliasRE);
  2832. if (!inMatch)
  2833. return;
  2834. const [, LHS, RHS] = inMatch;
  2835. const result = {
  2836. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  2837. value: undefined,
  2838. key: undefined,
  2839. index: undefined
  2840. };
  2841. {
  2842. validateBrowserExpression(result.source, context);
  2843. }
  2844. let valueContent = LHS.trim()
  2845. .replace(stripParensRE, '')
  2846. .trim();
  2847. const trimmedOffset = LHS.indexOf(valueContent);
  2848. const iteratorMatch = valueContent.match(forIteratorRE);
  2849. if (iteratorMatch) {
  2850. valueContent = valueContent.replace(forIteratorRE, '').trim();
  2851. const keyContent = iteratorMatch[1].trim();
  2852. let keyOffset;
  2853. if (keyContent) {
  2854. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  2855. result.key = createAliasExpression(loc, keyContent, keyOffset);
  2856. {
  2857. validateBrowserExpression(result.key, context, true);
  2858. }
  2859. }
  2860. if (iteratorMatch[2]) {
  2861. const indexContent = iteratorMatch[2].trim();
  2862. if (indexContent) {
  2863. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  2864. ? keyOffset + keyContent.length
  2865. : trimmedOffset + valueContent.length));
  2866. {
  2867. validateBrowserExpression(result.index, context, true);
  2868. }
  2869. }
  2870. }
  2871. }
  2872. if (valueContent) {
  2873. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  2874. {
  2875. validateBrowserExpression(result.value, context, true);
  2876. }
  2877. }
  2878. return result;
  2879. }
  2880. function createAliasExpression(range, content, offset) {
  2881. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  2882. }
  2883. function createForLoopParams({ value, key, index }) {
  2884. const params = [];
  2885. if (value) {
  2886. params.push(value);
  2887. }
  2888. if (key) {
  2889. if (!value) {
  2890. params.push(createSimpleExpression(`_`, false));
  2891. }
  2892. params.push(key);
  2893. }
  2894. if (index) {
  2895. if (!key) {
  2896. if (!value) {
  2897. params.push(createSimpleExpression(`_`, false));
  2898. }
  2899. params.push(createSimpleExpression(`__`, false));
  2900. }
  2901. params.push(index);
  2902. }
  2903. return params;
  2904. }
  2905. const defaultFallback = createSimpleExpression(`undefined`, false);
  2906. // A NodeTransform that:
  2907. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  2908. // by transformExpression. This is only applied in non-browser builds with
  2909. // { prefixIdentifiers: true }.
  2910. // 2. Track v-slot depths so that we know a slot is inside another slot.
  2911. // Note the exit callback is executed before buildSlots() on the same node,
  2912. // so only nested slots see positive numbers.
  2913. const trackSlotScopes = (node, context) => {
  2914. if (node.type === 1 /* ELEMENT */ &&
  2915. (node.tagType === 1 /* COMPONENT */ ||
  2916. node.tagType === 3 /* TEMPLATE */)) {
  2917. // We are only checking non-empty v-slot here
  2918. // since we only care about slots that introduce scope variables.
  2919. const vSlot = findDir(node, 'slot');
  2920. if (vSlot) {
  2921. vSlot.exp;
  2922. context.scopes.vSlot++;
  2923. return () => {
  2924. context.scopes.vSlot--;
  2925. };
  2926. }
  2927. }
  2928. };
  2929. // A NodeTransform that tracks scope identifiers for scoped slots with v-for.
  2930. // This transform is only applied in non-browser builds with { prefixIdentifiers: true }
  2931. const trackVForSlotScopes = (node, context) => {
  2932. let vFor;
  2933. if (isTemplateNode(node) &&
  2934. node.props.some(isVSlot) &&
  2935. (vFor = findDir(node, 'for'))) {
  2936. const result = (vFor.parseResult = parseForExpression(vFor.exp, context));
  2937. if (result) {
  2938. const { value, key, index } = result;
  2939. const { addIdentifiers, removeIdentifiers } = context;
  2940. value && addIdentifiers(value);
  2941. key && addIdentifiers(key);
  2942. index && addIdentifiers(index);
  2943. return () => {
  2944. value && removeIdentifiers(value);
  2945. key && removeIdentifiers(key);
  2946. index && removeIdentifiers(index);
  2947. };
  2948. }
  2949. }
  2950. };
  2951. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  2952. // Instead of being a DirectiveTransform, v-slot processing is called during
  2953. // transformElement to build the slots object for a component.
  2954. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  2955. context.helper(WITH_CTX);
  2956. const { children, loc } = node;
  2957. const slotsProperties = [];
  2958. const dynamicSlots = [];
  2959. const buildDefaultSlotProperty = (props, children) => createObjectProperty(`default`, buildSlotFn(props, children, loc));
  2960. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  2961. // since it likely uses a scope variable.
  2962. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  2963. // 1. Check for slot with slotProps on component itself.
  2964. // <Comp v-slot="{ prop }"/>
  2965. const onComponentSlot = findDir(node, 'slot', true);
  2966. if (onComponentSlot) {
  2967. const { arg, exp } = onComponentSlot;
  2968. if (arg && !isStaticExp(arg)) {
  2969. hasDynamicSlots = true;
  2970. }
  2971. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  2972. }
  2973. // 2. Iterate through children and check for template slots
  2974. // <template v-slot:foo="{ prop }">
  2975. let hasTemplateSlots = false;
  2976. let hasNamedDefaultSlot = false;
  2977. const implicitDefaultChildren = [];
  2978. const seenSlotNames = new Set();
  2979. for (let i = 0; i < children.length; i++) {
  2980. const slotElement = children[i];
  2981. let slotDir;
  2982. if (!isTemplateNode(slotElement) ||
  2983. !(slotDir = findDir(slotElement, 'slot', true))) {
  2984. // not a <template v-slot>, skip.
  2985. if (slotElement.type !== 3 /* COMMENT */) {
  2986. implicitDefaultChildren.push(slotElement);
  2987. }
  2988. continue;
  2989. }
  2990. if (onComponentSlot) {
  2991. // already has on-component slot - this is incorrect usage.
  2992. context.onError(createCompilerError(36 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  2993. break;
  2994. }
  2995. hasTemplateSlots = true;
  2996. const { children: slotChildren, loc: slotLoc } = slotElement;
  2997. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  2998. // check if name is dynamic.
  2999. let staticSlotName;
  3000. if (isStaticExp(slotName)) {
  3001. staticSlotName = slotName ? slotName.content : `default`;
  3002. }
  3003. else {
  3004. hasDynamicSlots = true;
  3005. }
  3006. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  3007. // check if this slot is conditional (v-if/v-for)
  3008. let vIf;
  3009. let vElse;
  3010. let vFor;
  3011. if ((vIf = findDir(slotElement, 'if'))) {
  3012. hasDynamicSlots = true;
  3013. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
  3014. }
  3015. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  3016. // find adjacent v-if
  3017. let j = i;
  3018. let prev;
  3019. while (j--) {
  3020. prev = children[j];
  3021. if (prev.type !== 3 /* COMMENT */) {
  3022. break;
  3023. }
  3024. }
  3025. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  3026. // remove node
  3027. children.splice(i, 1);
  3028. i--;
  3029. // attach this slot to previous conditional
  3030. let conditional = dynamicSlots[dynamicSlots.length - 1];
  3031. while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  3032. conditional = conditional.alternate;
  3033. }
  3034. conditional.alternate = vElse.exp
  3035. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
  3036. : buildDynamicSlot(slotName, slotFunction);
  3037. }
  3038. else {
  3039. context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  3040. }
  3041. }
  3042. else if ((vFor = findDir(slotElement, 'for'))) {
  3043. hasDynamicSlots = true;
  3044. const parseResult = vFor.parseResult ||
  3045. parseForExpression(vFor.exp, context);
  3046. if (parseResult) {
  3047. // Render the dynamic slots as an array and add it to the createSlot()
  3048. // args. The runtime knows how to handle it appropriately.
  3049. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  3050. parseResult.source,
  3051. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  3052. ]));
  3053. }
  3054. else {
  3055. context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  3056. }
  3057. }
  3058. else {
  3059. // check duplicate static names
  3060. if (staticSlotName) {
  3061. if (seenSlotNames.has(staticSlotName)) {
  3062. context.onError(createCompilerError(37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  3063. continue;
  3064. }
  3065. seenSlotNames.add(staticSlotName);
  3066. if (staticSlotName === 'default') {
  3067. hasNamedDefaultSlot = true;
  3068. }
  3069. }
  3070. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  3071. }
  3072. }
  3073. if (!onComponentSlot) {
  3074. if (!hasTemplateSlots) {
  3075. // implicit default slot (on component)
  3076. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  3077. }
  3078. else if (implicitDefaultChildren.length) {
  3079. // implicit default slot (mixed with named slots)
  3080. if (hasNamedDefaultSlot) {
  3081. context.onError(createCompilerError(38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  3082. }
  3083. else {
  3084. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  3085. }
  3086. }
  3087. }
  3088. const slotFlag = hasDynamicSlots
  3089. ? 2 /* DYNAMIC */
  3090. : hasForwardedSlots(node.children)
  3091. ? 3 /* FORWARDED */
  3092. : 1 /* STABLE */;
  3093. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  3094. // 2 = compiled but dynamic = can skip normalization, but must run diff
  3095. // 1 = compiled and static = can skip normalization AND diff as optimized
  3096. createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
  3097. if (dynamicSlots.length) {
  3098. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  3099. slots,
  3100. createArrayExpression(dynamicSlots)
  3101. ]);
  3102. }
  3103. return {
  3104. slots,
  3105. hasDynamicSlots
  3106. };
  3107. }
  3108. function buildDynamicSlot(name, fn) {
  3109. return createObjectExpression([
  3110. createObjectProperty(`name`, name),
  3111. createObjectProperty(`fn`, fn)
  3112. ]);
  3113. }
  3114. function hasForwardedSlots(children) {
  3115. for (let i = 0; i < children.length; i++) {
  3116. const child = children[i];
  3117. if (child.type === 1 /* ELEMENT */) {
  3118. if (child.tagType === 2 /* SLOT */ ||
  3119. (child.tagType === 0 /* ELEMENT */ &&
  3120. hasForwardedSlots(child.children))) {
  3121. return true;
  3122. }
  3123. }
  3124. }
  3125. return false;
  3126. }
  3127. // some directive transforms (e.g. v-model) may return a symbol for runtime
  3128. // import, which should be used instead of a resolveDirective call.
  3129. const directiveImportMap = new WeakMap();
  3130. // generate a JavaScript AST for this element's codegen
  3131. const transformElement = (node, context) => {
  3132. if (!(node.type === 1 /* ELEMENT */ &&
  3133. (node.tagType === 0 /* ELEMENT */ ||
  3134. node.tagType === 1 /* COMPONENT */))) {
  3135. return;
  3136. }
  3137. // perform the work on exit, after all child expressions have been
  3138. // processed and merged.
  3139. return function postTransformElement() {
  3140. const { tag, props } = node;
  3141. const isComponent = node.tagType === 1 /* COMPONENT */;
  3142. // The goal of the transform is to create a codegenNode implementing the
  3143. // VNodeCall interface.
  3144. const vnodeTag = isComponent
  3145. ? resolveComponentType(node, context)
  3146. : `"${tag}"`;
  3147. const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  3148. let vnodeProps;
  3149. let vnodeChildren;
  3150. let vnodePatchFlag;
  3151. let patchFlag = 0;
  3152. let vnodeDynamicProps;
  3153. let dynamicPropNames;
  3154. let vnodeDirectives;
  3155. let shouldUseBlock =
  3156. // dynamic component may resolve to plain elements
  3157. isDynamicComponent ||
  3158. vnodeTag === TELEPORT ||
  3159. vnodeTag === SUSPENSE ||
  3160. (!isComponent &&
  3161. // <svg> and <foreignObject> must be forced into blocks so that block
  3162. // updates inside get proper isSVG flag at runtime. (#639, #643)
  3163. // This is technically web-specific, but splitting the logic out of core
  3164. // leads to too much unnecessary complexity.
  3165. (tag === 'svg' ||
  3166. tag === 'foreignObject' ||
  3167. // #938: elements with dynamic keys should be forced into blocks
  3168. findProp(node, 'key', true)));
  3169. // props
  3170. if (props.length > 0) {
  3171. const propsBuildResult = buildProps(node, context);
  3172. vnodeProps = propsBuildResult.props;
  3173. patchFlag = propsBuildResult.patchFlag;
  3174. dynamicPropNames = propsBuildResult.dynamicPropNames;
  3175. const directives = propsBuildResult.directives;
  3176. vnodeDirectives =
  3177. directives && directives.length
  3178. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  3179. : undefined;
  3180. }
  3181. // children
  3182. if (node.children.length > 0) {
  3183. if (vnodeTag === KEEP_ALIVE) {
  3184. // Although a built-in component, we compile KeepAlive with raw children
  3185. // instead of slot functions so that it can be used inside Transition
  3186. // or other Transition-wrapping HOCs.
  3187. // To ensure correct updates with block optimizations, we need to:
  3188. // 1. Force keep-alive into a block. This avoids its children being
  3189. // collected by a parent block.
  3190. shouldUseBlock = true;
  3191. // 2. Force keep-alive to always be updated, since it uses raw children.
  3192. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  3193. if (node.children.length > 1) {
  3194. context.onError(createCompilerError(44 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
  3195. start: node.children[0].loc.start,
  3196. end: node.children[node.children.length - 1].loc.end,
  3197. source: ''
  3198. }));
  3199. }
  3200. }
  3201. const shouldBuildAsSlots = isComponent &&
  3202. // Teleport is not a real component and has dedicated runtime handling
  3203. vnodeTag !== TELEPORT &&
  3204. // explained above.
  3205. vnodeTag !== KEEP_ALIVE;
  3206. if (shouldBuildAsSlots) {
  3207. const { slots, hasDynamicSlots } = buildSlots(node, context);
  3208. vnodeChildren = slots;
  3209. if (hasDynamicSlots) {
  3210. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  3211. }
  3212. }
  3213. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  3214. const child = node.children[0];
  3215. const type = child.type;
  3216. // check for dynamic text children
  3217. const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
  3218. type === 8 /* COMPOUND_EXPRESSION */;
  3219. if (hasDynamicTextChild &&
  3220. getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
  3221. patchFlag |= 1 /* TEXT */;
  3222. }
  3223. // pass directly if the only child is a text node
  3224. // (plain / interpolation / expression)
  3225. if (hasDynamicTextChild || type === 2 /* TEXT */) {
  3226. vnodeChildren = child;
  3227. }
  3228. else {
  3229. vnodeChildren = node.children;
  3230. }
  3231. }
  3232. else {
  3233. vnodeChildren = node.children;
  3234. }
  3235. }
  3236. // patchFlag & dynamicPropNames
  3237. if (patchFlag !== 0) {
  3238. {
  3239. if (patchFlag < 0) {
  3240. // special flags (negative and mutually exclusive)
  3241. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  3242. }
  3243. else {
  3244. // bitwise flags
  3245. const flagNames = Object.keys(PatchFlagNames)
  3246. .map(Number)
  3247. .filter(n => n > 0 && patchFlag & n)
  3248. .map(n => PatchFlagNames[n])
  3249. .join(`, `);
  3250. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  3251. }
  3252. }
  3253. if (dynamicPropNames && dynamicPropNames.length) {
  3254. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  3255. }
  3256. }
  3257. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, node.loc);
  3258. };
  3259. };
  3260. function resolveComponentType(node, context, ssr = false) {
  3261. const { tag } = node;
  3262. // 1. dynamic component
  3263. const isProp = node.tag === 'component' ? findProp(node, 'is') : findDir(node, 'is');
  3264. if (isProp) {
  3265. const exp = isProp.type === 6 /* ATTRIBUTE */
  3266. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  3267. : isProp.exp;
  3268. if (exp) {
  3269. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  3270. exp
  3271. ]);
  3272. }
  3273. }
  3274. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  3275. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  3276. if (builtIn) {
  3277. // built-ins are simply fallthroughs / have special handling during ssr
  3278. // so we don't need to import their runtime equivalents
  3279. if (!ssr)
  3280. context.helper(builtIn);
  3281. return builtIn;
  3282. }
  3283. // 5. user component (resolve)
  3284. context.helper(RESOLVE_COMPONENT);
  3285. context.components.add(tag);
  3286. return toValidAssetId(tag, `component`);
  3287. }
  3288. function buildProps(node, context, props = node.props, ssr = false) {
  3289. const { tag, loc: elementLoc } = node;
  3290. const isComponent = node.tagType === 1 /* COMPONENT */;
  3291. let properties = [];
  3292. const mergeArgs = [];
  3293. const runtimeDirectives = [];
  3294. // patchFlag analysis
  3295. let patchFlag = 0;
  3296. let hasRef = false;
  3297. let hasClassBinding = false;
  3298. let hasStyleBinding = false;
  3299. let hasHydrationEventBinding = false;
  3300. let hasDynamicKeys = false;
  3301. let hasVnodeHook = false;
  3302. const dynamicPropNames = [];
  3303. const analyzePatchFlag = ({ key, value }) => {
  3304. if (isStaticExp(key)) {
  3305. const name = key.content;
  3306. const isEventHandler = isOn(name);
  3307. if (!isComponent &&
  3308. isEventHandler &&
  3309. // omit the flag for click handlers because hydration gives click
  3310. // dedicated fast path.
  3311. name.toLowerCase() !== 'onclick' &&
  3312. // omit v-model handlers
  3313. name !== 'onUpdate:modelValue' &&
  3314. // omit onVnodeXXX hooks
  3315. !isReservedProp(name)) {
  3316. hasHydrationEventBinding = true;
  3317. }
  3318. if (isEventHandler && isReservedProp(name)) {
  3319. hasVnodeHook = true;
  3320. }
  3321. if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
  3322. ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
  3323. value.type === 8 /* COMPOUND_EXPRESSION */) &&
  3324. getConstantType(value, context) > 0)) {
  3325. // skip if the prop is a cached handler or has constant value
  3326. return;
  3327. }
  3328. if (name === 'ref') {
  3329. hasRef = true;
  3330. }
  3331. else if (name === 'class' && !isComponent) {
  3332. hasClassBinding = true;
  3333. }
  3334. else if (name === 'style' && !isComponent) {
  3335. hasStyleBinding = true;
  3336. }
  3337. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  3338. dynamicPropNames.push(name);
  3339. }
  3340. }
  3341. else {
  3342. hasDynamicKeys = true;
  3343. }
  3344. };
  3345. for (let i = 0; i < props.length; i++) {
  3346. // static attribute
  3347. const prop = props[i];
  3348. if (prop.type === 6 /* ATTRIBUTE */) {
  3349. const { loc, name, value } = prop;
  3350. let isStatic = true;
  3351. if (name === 'ref') {
  3352. hasRef = true;
  3353. }
  3354. // skip :is on <component>
  3355. if (name === 'is' && tag === 'component') {
  3356. continue;
  3357. }
  3358. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
  3359. }
  3360. else {
  3361. // directives
  3362. const { name, arg, exp, loc } = prop;
  3363. const isBind = name === 'bind';
  3364. const isOn = name === 'on';
  3365. // skip v-slot - it is handled by its dedicated transform.
  3366. if (name === 'slot') {
  3367. if (!isComponent) {
  3368. context.onError(createCompilerError(39 /* X_V_SLOT_MISPLACED */, loc));
  3369. }
  3370. continue;
  3371. }
  3372. // skip v-once - it is handled by its dedicated transform.
  3373. if (name === 'once') {
  3374. continue;
  3375. }
  3376. // skip v-is and :is on <component>
  3377. if (name === 'is' ||
  3378. (isBind && tag === 'component' && isBindKey(arg, 'is'))) {
  3379. continue;
  3380. }
  3381. // skip v-on in SSR compilation
  3382. if (isOn && ssr) {
  3383. continue;
  3384. }
  3385. // special case for v-bind and v-on with no argument
  3386. if (!arg && (isBind || isOn)) {
  3387. hasDynamicKeys = true;
  3388. if (exp) {
  3389. if (properties.length) {
  3390. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  3391. properties = [];
  3392. }
  3393. if (isBind) {
  3394. mergeArgs.push(exp);
  3395. }
  3396. else {
  3397. // v-on="obj" -> toHandlers(obj)
  3398. mergeArgs.push({
  3399. type: 14 /* JS_CALL_EXPRESSION */,
  3400. loc,
  3401. callee: context.helper(TO_HANDLERS),
  3402. arguments: [exp]
  3403. });
  3404. }
  3405. }
  3406. else {
  3407. context.onError(createCompilerError(isBind
  3408. ? 33 /* X_V_BIND_NO_EXPRESSION */
  3409. : 34 /* X_V_ON_NO_EXPRESSION */, loc));
  3410. }
  3411. continue;
  3412. }
  3413. const directiveTransform = context.directiveTransforms[name];
  3414. if (directiveTransform) {
  3415. // has built-in directive transform.
  3416. const { props, needRuntime } = directiveTransform(prop, node, context);
  3417. !ssr && props.forEach(analyzePatchFlag);
  3418. properties.push(...props);
  3419. if (needRuntime) {
  3420. runtimeDirectives.push(prop);
  3421. if (isSymbol(needRuntime)) {
  3422. directiveImportMap.set(prop, needRuntime);
  3423. }
  3424. }
  3425. }
  3426. else {
  3427. // no built-in transform, this is a user custom directive.
  3428. runtimeDirectives.push(prop);
  3429. }
  3430. }
  3431. }
  3432. let propsExpression = undefined;
  3433. // has v-bind="object" or v-on="object", wrap with mergeProps
  3434. if (mergeArgs.length) {
  3435. if (properties.length) {
  3436. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  3437. }
  3438. if (mergeArgs.length > 1) {
  3439. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  3440. }
  3441. else {
  3442. // single v-bind with nothing else - no need for a mergeProps call
  3443. propsExpression = mergeArgs[0];
  3444. }
  3445. }
  3446. else if (properties.length) {
  3447. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  3448. }
  3449. // patchFlag analysis
  3450. if (hasDynamicKeys) {
  3451. patchFlag |= 16 /* FULL_PROPS */;
  3452. }
  3453. else {
  3454. if (hasClassBinding) {
  3455. patchFlag |= 2 /* CLASS */;
  3456. }
  3457. if (hasStyleBinding) {
  3458. patchFlag |= 4 /* STYLE */;
  3459. }
  3460. if (dynamicPropNames.length) {
  3461. patchFlag |= 8 /* PROPS */;
  3462. }
  3463. if (hasHydrationEventBinding) {
  3464. patchFlag |= 32 /* HYDRATE_EVENTS */;
  3465. }
  3466. }
  3467. if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
  3468. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  3469. patchFlag |= 512 /* NEED_PATCH */;
  3470. }
  3471. return {
  3472. props: propsExpression,
  3473. directives: runtimeDirectives,
  3474. patchFlag,
  3475. dynamicPropNames
  3476. };
  3477. }
  3478. // Dedupe props in an object literal.
  3479. // Literal duplicated attributes would have been warned during the parse phase,
  3480. // however, it's possible to encounter duplicated `onXXX` handlers with different
  3481. // modifiers. We also need to merge static and dynamic class / style attributes.
  3482. // - onXXX handlers / style: merge into array
  3483. // - class: merge into single expression with concatenation
  3484. function dedupeProperties(properties) {
  3485. const knownProps = new Map();
  3486. const deduped = [];
  3487. for (let i = 0; i < properties.length; i++) {
  3488. const prop = properties[i];
  3489. // dynamic keys are always allowed
  3490. if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  3491. deduped.push(prop);
  3492. continue;
  3493. }
  3494. const name = prop.key.content;
  3495. const existing = knownProps.get(name);
  3496. if (existing) {
  3497. if (name === 'style' || name === 'class' || name.startsWith('on')) {
  3498. mergeAsArray(existing, prop);
  3499. }
  3500. // unexpected duplicate, should have emitted error during parse
  3501. }
  3502. else {
  3503. knownProps.set(name, prop);
  3504. deduped.push(prop);
  3505. }
  3506. }
  3507. return deduped;
  3508. }
  3509. function mergeAsArray(existing, incoming) {
  3510. if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
  3511. existing.value.elements.push(incoming.value);
  3512. }
  3513. else {
  3514. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  3515. }
  3516. }
  3517. function buildDirectiveArgs(dir, context) {
  3518. const dirArgs = [];
  3519. const runtime = directiveImportMap.get(dir);
  3520. if (runtime) {
  3521. // built-in directive with runtime
  3522. dirArgs.push(context.helperString(runtime));
  3523. }
  3524. else {
  3525. {
  3526. // inject statement for resolving directive
  3527. context.helper(RESOLVE_DIRECTIVE);
  3528. context.directives.add(dir.name);
  3529. dirArgs.push(toValidAssetId(dir.name, `directive`));
  3530. }
  3531. }
  3532. const { loc } = dir;
  3533. if (dir.exp)
  3534. dirArgs.push(dir.exp);
  3535. if (dir.arg) {
  3536. if (!dir.exp) {
  3537. dirArgs.push(`void 0`);
  3538. }
  3539. dirArgs.push(dir.arg);
  3540. }
  3541. if (Object.keys(dir.modifiers).length) {
  3542. if (!dir.arg) {
  3543. if (!dir.exp) {
  3544. dirArgs.push(`void 0`);
  3545. }
  3546. dirArgs.push(`void 0`);
  3547. }
  3548. const trueExpression = createSimpleExpression(`true`, false, loc);
  3549. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  3550. }
  3551. return createArrayExpression(dirArgs, dir.loc);
  3552. }
  3553. function stringifyDynamicPropNames(props) {
  3554. let propsNamesString = `[`;
  3555. for (let i = 0, l = props.length; i < l; i++) {
  3556. propsNamesString += JSON.stringify(props[i]);
  3557. if (i < l - 1)
  3558. propsNamesString += ', ';
  3559. }
  3560. return propsNamesString + `]`;
  3561. }
  3562. const transformSlotOutlet = (node, context) => {
  3563. if (isSlotOutlet(node)) {
  3564. const { children, loc } = node;
  3565. const { slotName, slotProps } = processSlotOutlet(node, context);
  3566. const slotArgs = [
  3567. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  3568. slotName
  3569. ];
  3570. if (slotProps) {
  3571. slotArgs.push(slotProps);
  3572. }
  3573. if (children.length) {
  3574. if (!slotProps) {
  3575. slotArgs.push(`{}`);
  3576. }
  3577. slotArgs.push(createFunctionExpression([], children, false, false, loc));
  3578. }
  3579. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  3580. }
  3581. };
  3582. function processSlotOutlet(node, context) {
  3583. let slotName = `"default"`;
  3584. let slotProps = undefined;
  3585. const nonNameProps = [];
  3586. for (let i = 0; i < node.props.length; i++) {
  3587. const p = node.props[i];
  3588. if (p.type === 6 /* ATTRIBUTE */) {
  3589. if (p.value) {
  3590. if (p.name === 'name') {
  3591. slotName = JSON.stringify(p.value.content);
  3592. }
  3593. else {
  3594. p.name = camelize(p.name);
  3595. nonNameProps.push(p);
  3596. }
  3597. }
  3598. }
  3599. else {
  3600. if (p.name === 'bind' && isBindKey(p.arg, 'name')) {
  3601. if (p.exp)
  3602. slotName = p.exp;
  3603. }
  3604. else {
  3605. if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
  3606. p.arg.content = camelize(p.arg.content);
  3607. }
  3608. nonNameProps.push(p);
  3609. }
  3610. }
  3611. }
  3612. if (nonNameProps.length > 0) {
  3613. const { props, directives } = buildProps(node, context, nonNameProps);
  3614. slotProps = props;
  3615. if (directives.length) {
  3616. context.onError(createCompilerError(35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  3617. }
  3618. }
  3619. return {
  3620. slotName,
  3621. slotProps
  3622. };
  3623. }
  3624. const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/;
  3625. const transformOn = (dir, node, context, augmentor) => {
  3626. const { loc, modifiers, arg } = dir;
  3627. if (!dir.exp && !modifiers.length) {
  3628. context.onError(createCompilerError(34 /* X_V_ON_NO_EXPRESSION */, loc));
  3629. }
  3630. let eventName;
  3631. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  3632. if (arg.isStatic) {
  3633. const rawName = arg.content;
  3634. // for all event listeners, auto convert it to camelCase. See issue #2249
  3635. eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
  3636. }
  3637. else {
  3638. // #2388
  3639. eventName = createCompoundExpression([
  3640. `${context.helperString(TO_HANDLER_KEY)}(`,
  3641. arg,
  3642. `)`
  3643. ]);
  3644. }
  3645. }
  3646. else {
  3647. // already a compound expression.
  3648. eventName = arg;
  3649. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  3650. eventName.children.push(`)`);
  3651. }
  3652. // handler processing
  3653. let exp = dir.exp;
  3654. if (exp && !exp.content.trim()) {
  3655. exp = undefined;
  3656. }
  3657. let shouldCache = context.cacheHandlers && !exp;
  3658. if (exp) {
  3659. const isMemberExp = isMemberExpression(exp.content);
  3660. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  3661. const hasMultipleStatements = exp.content.includes(`;`);
  3662. {
  3663. validateBrowserExpression(exp, context, false, hasMultipleStatements);
  3664. }
  3665. if (isInlineStatement || (shouldCache && isMemberExp)) {
  3666. // wrap inline statement in a function expression
  3667. exp = createCompoundExpression([
  3668. `${isInlineStatement
  3669. ? `$event`
  3670. : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  3671. exp,
  3672. hasMultipleStatements ? `}` : `)`
  3673. ]);
  3674. }
  3675. }
  3676. let ret = {
  3677. props: [
  3678. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  3679. ]
  3680. };
  3681. // apply extended compiler augmentor
  3682. if (augmentor) {
  3683. ret = augmentor(ret);
  3684. }
  3685. if (shouldCache) {
  3686. // cache handlers so that it's always the same handler being passed down.
  3687. // this avoids unnecessary re-renders when users use inline handlers on
  3688. // components.
  3689. ret.props[0].value = context.cache(ret.props[0].value);
  3690. }
  3691. return ret;
  3692. };
  3693. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  3694. // codegen for the entire props object. This transform here is only for v-bind
  3695. // *with* args.
  3696. const transformBind = (dir, node, context) => {
  3697. const { exp, modifiers, loc } = dir;
  3698. const arg = dir.arg;
  3699. if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
  3700. arg.children.unshift(`(`);
  3701. arg.children.push(`) || ""`);
  3702. }
  3703. else if (!arg.isStatic) {
  3704. arg.content = `${arg.content} || ""`;
  3705. }
  3706. // .prop is no longer necessary due to new patch behavior
  3707. // .sync is replaced by v-model:arg
  3708. if (modifiers.includes('camel')) {
  3709. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  3710. if (arg.isStatic) {
  3711. arg.content = camelize(arg.content);
  3712. }
  3713. else {
  3714. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  3715. }
  3716. }
  3717. else {
  3718. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  3719. arg.children.push(`)`);
  3720. }
  3721. }
  3722. if (!exp ||
  3723. (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  3724. context.onError(createCompilerError(33 /* X_V_BIND_NO_EXPRESSION */, loc));
  3725. return {
  3726. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  3727. };
  3728. }
  3729. return {
  3730. props: [createObjectProperty(arg, exp)]
  3731. };
  3732. };
  3733. // Merge adjacent text nodes and expressions into a single expression
  3734. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  3735. const transformText = (node, context) => {
  3736. if (node.type === 0 /* ROOT */ ||
  3737. node.type === 1 /* ELEMENT */ ||
  3738. node.type === 11 /* FOR */ ||
  3739. node.type === 10 /* IF_BRANCH */) {
  3740. // perform the transform on node exit so that all expressions have already
  3741. // been processed.
  3742. return () => {
  3743. const children = node.children;
  3744. let currentContainer = undefined;
  3745. let hasText = false;
  3746. for (let i = 0; i < children.length; i++) {
  3747. const child = children[i];
  3748. if (isText(child)) {
  3749. hasText = true;
  3750. for (let j = i + 1; j < children.length; j++) {
  3751. const next = children[j];
  3752. if (isText(next)) {
  3753. if (!currentContainer) {
  3754. currentContainer = children[i] = {
  3755. type: 8 /* COMPOUND_EXPRESSION */,
  3756. loc: child.loc,
  3757. children: [child]
  3758. };
  3759. }
  3760. // merge adjacent text node into current
  3761. currentContainer.children.push(` + `, next);
  3762. children.splice(j, 1);
  3763. j--;
  3764. }
  3765. else {
  3766. currentContainer = undefined;
  3767. break;
  3768. }
  3769. }
  3770. }
  3771. }
  3772. if (!hasText ||
  3773. // if this is a plain element with a single text child, leave it
  3774. // as-is since the runtime has dedicated fast path for this by directly
  3775. // setting textContent of the element.
  3776. // for component root it's always normalized anyway.
  3777. (children.length === 1 &&
  3778. (node.type === 0 /* ROOT */ ||
  3779. (node.type === 1 /* ELEMENT */ &&
  3780. node.tagType === 0 /* ELEMENT */)))) {
  3781. return;
  3782. }
  3783. // pre-convert text nodes into createTextVNode(text) calls to avoid
  3784. // runtime normalization.
  3785. for (let i = 0; i < children.length; i++) {
  3786. const child = children[i];
  3787. if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
  3788. const callArgs = [];
  3789. // createTextVNode defaults to single whitespace, so if it is a
  3790. // single space the code could be an empty call to save bytes.
  3791. if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
  3792. callArgs.push(child);
  3793. }
  3794. // mark dynamic text with flag so it gets patched inside a block
  3795. if (!context.ssr &&
  3796. getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
  3797. callArgs.push(1 /* TEXT */ +
  3798. (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
  3799. }
  3800. children[i] = {
  3801. type: 12 /* TEXT_CALL */,
  3802. content: child,
  3803. loc: child.loc,
  3804. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  3805. };
  3806. }
  3807. }
  3808. };
  3809. }
  3810. };
  3811. const seen = new WeakSet();
  3812. const transformOnce = (node, context) => {
  3813. if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
  3814. if (seen.has(node)) {
  3815. return;
  3816. }
  3817. seen.add(node);
  3818. context.helper(SET_BLOCK_TRACKING);
  3819. return () => {
  3820. const cur = context.currentNode;
  3821. if (cur.codegenNode) {
  3822. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  3823. }
  3824. };
  3825. }
  3826. };
  3827. const transformModel = (dir, node, context) => {
  3828. const { exp, arg } = dir;
  3829. if (!exp) {
  3830. context.onError(createCompilerError(40 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
  3831. return createTransformProps();
  3832. }
  3833. const rawExp = exp.loc.source;
  3834. const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
  3835. // im SFC <script setup> inline mode, the exp may have been transformed into
  3836. // _unref(exp)
  3837. context.bindingMetadata[rawExp];
  3838. const maybeRef = !true /* SETUP_CONST */;
  3839. if (!isMemberExpression(expString) && !maybeRef) {
  3840. context.onError(createCompilerError(41 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  3841. return createTransformProps();
  3842. }
  3843. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  3844. const eventName = arg
  3845. ? isStaticExp(arg)
  3846. ? `onUpdate:${arg.content}`
  3847. : createCompoundExpression(['"onUpdate:" + ', arg])
  3848. : `onUpdate:modelValue`;
  3849. let assignmentExp;
  3850. const eventArg = context.isTS ? `($event: any)` : `$event`;
  3851. {
  3852. assignmentExp = createCompoundExpression([
  3853. `${eventArg} => (`,
  3854. exp,
  3855. ` = $event)`
  3856. ]);
  3857. }
  3858. const props = [
  3859. // modelValue: foo
  3860. createObjectProperty(propName, dir.exp),
  3861. // "onUpdate:modelValue": $event => (foo = $event)
  3862. createObjectProperty(eventName, assignmentExp)
  3863. ];
  3864. // modelModifiers: { foo: true, "bar-baz": true }
  3865. if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
  3866. const modifiers = dir.modifiers
  3867. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  3868. .join(`, `);
  3869. const modifiersKey = arg
  3870. ? isStaticExp(arg)
  3871. ? `${arg.content}Modifiers`
  3872. : createCompoundExpression([arg, ' + "Modifiers"'])
  3873. : `modelModifiers`;
  3874. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
  3875. }
  3876. return createTransformProps(props);
  3877. };
  3878. function createTransformProps(props = []) {
  3879. return { props };
  3880. }
  3881. function getBaseTransformPreset(prefixIdentifiers) {
  3882. return [
  3883. [
  3884. transformOnce,
  3885. transformIf,
  3886. transformFor,
  3887. ...([transformExpression]
  3888. ),
  3889. transformSlotOutlet,
  3890. transformElement,
  3891. trackSlotScopes,
  3892. transformText
  3893. ],
  3894. {
  3895. on: transformOn,
  3896. bind: transformBind,
  3897. model: transformModel
  3898. }
  3899. ];
  3900. }
  3901. // we name it `baseCompile` so that higher order compilers like
  3902. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  3903. function baseCompile(template, options = {}) {
  3904. const onError = options.onError || defaultOnError;
  3905. const isModuleMode = options.mode === 'module';
  3906. /* istanbul ignore if */
  3907. {
  3908. if (options.prefixIdentifiers === true) {
  3909. onError(createCompilerError(45 /* X_PREFIX_ID_NOT_SUPPORTED */));
  3910. }
  3911. else if (isModuleMode) {
  3912. onError(createCompilerError(46 /* X_MODULE_MODE_NOT_SUPPORTED */));
  3913. }
  3914. }
  3915. const prefixIdentifiers = !true ;
  3916. if (options.cacheHandlers) {
  3917. onError(createCompilerError(47 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
  3918. }
  3919. if (options.scopeId && !isModuleMode) {
  3920. onError(createCompilerError(48 /* X_SCOPE_ID_NOT_SUPPORTED */));
  3921. }
  3922. const ast = isString(template) ? baseParse(template, options) : template;
  3923. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
  3924. transform(ast, extend({}, options, {
  3925. prefixIdentifiers,
  3926. nodeTransforms: [
  3927. ...nodeTransforms,
  3928. ...(options.nodeTransforms || []) // user transforms
  3929. ],
  3930. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  3931. )
  3932. }));
  3933. return generate(ast, extend({}, options, {
  3934. prefixIdentifiers
  3935. }));
  3936. }
  3937. const noopDirectiveTransform = () => ({ props: [] });
  3938. const V_MODEL_RADIO = Symbol(`vModelRadio` );
  3939. const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
  3940. const V_MODEL_TEXT = Symbol(`vModelText` );
  3941. const V_MODEL_SELECT = Symbol(`vModelSelect` );
  3942. const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
  3943. const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
  3944. const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
  3945. const V_SHOW = Symbol(`vShow` );
  3946. const TRANSITION = Symbol(`Transition` );
  3947. const TRANSITION_GROUP = Symbol(`TransitionGroup` );
  3948. registerRuntimeHelpers({
  3949. [V_MODEL_RADIO]: `vModelRadio`,
  3950. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  3951. [V_MODEL_TEXT]: `vModelText`,
  3952. [V_MODEL_SELECT]: `vModelSelect`,
  3953. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  3954. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  3955. [V_ON_WITH_KEYS]: `withKeys`,
  3956. [V_SHOW]: `vShow`,
  3957. [TRANSITION]: `Transition`,
  3958. [TRANSITION_GROUP]: `TransitionGroup`
  3959. });
  3960. /* eslint-disable no-restricted-globals */
  3961. let decoder;
  3962. function decodeHtmlBrowser(raw) {
  3963. (decoder || (decoder = document.createElement('div'))).innerHTML = raw;
  3964. return decoder.textContent;
  3965. }
  3966. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  3967. const parserOptions = {
  3968. isVoidTag,
  3969. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  3970. isPreTag: tag => tag === 'pre',
  3971. decodeEntities: decodeHtmlBrowser ,
  3972. isBuiltInComponent: (tag) => {
  3973. if (isBuiltInType(tag, `Transition`)) {
  3974. return TRANSITION;
  3975. }
  3976. else if (isBuiltInType(tag, `TransitionGroup`)) {
  3977. return TRANSITION_GROUP;
  3978. }
  3979. },
  3980. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  3981. getNamespace(tag, parent) {
  3982. let ns = parent ? parent.ns : 0 /* HTML */;
  3983. if (parent && ns === 2 /* MATH_ML */) {
  3984. if (parent.tag === 'annotation-xml') {
  3985. if (tag === 'svg') {
  3986. return 1 /* SVG */;
  3987. }
  3988. if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
  3989. a.name === 'encoding' &&
  3990. a.value != null &&
  3991. (a.value.content === 'text/html' ||
  3992. a.value.content === 'application/xhtml+xml'))) {
  3993. ns = 0 /* HTML */;
  3994. }
  3995. }
  3996. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  3997. tag !== 'mglyph' &&
  3998. tag !== 'malignmark') {
  3999. ns = 0 /* HTML */;
  4000. }
  4001. }
  4002. else if (parent && ns === 1 /* SVG */) {
  4003. if (parent.tag === 'foreignObject' ||
  4004. parent.tag === 'desc' ||
  4005. parent.tag === 'title') {
  4006. ns = 0 /* HTML */;
  4007. }
  4008. }
  4009. if (ns === 0 /* HTML */) {
  4010. if (tag === 'svg') {
  4011. return 1 /* SVG */;
  4012. }
  4013. if (tag === 'math') {
  4014. return 2 /* MATH_ML */;
  4015. }
  4016. }
  4017. return ns;
  4018. },
  4019. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  4020. getTextMode({ tag, ns }) {
  4021. if (ns === 0 /* HTML */) {
  4022. if (tag === 'textarea' || tag === 'title') {
  4023. return 1 /* RCDATA */;
  4024. }
  4025. if (isRawTextContainer(tag)) {
  4026. return 2 /* RAWTEXT */;
  4027. }
  4028. }
  4029. return 0 /* DATA */;
  4030. }
  4031. };
  4032. // Parse inline CSS strings for static style attributes into an object.
  4033. // This is a NodeTransform since it works on the static `style` attribute and
  4034. // converts it into a dynamic equivalent:
  4035. // style="color: red" -> :style='{ "color": "red" }'
  4036. // It is then processed by `transformElement` and included in the generated
  4037. // props.
  4038. const transformStyle = node => {
  4039. if (node.type === 1 /* ELEMENT */) {
  4040. node.props.forEach((p, i) => {
  4041. if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
  4042. // replace p with an expression node
  4043. node.props[i] = {
  4044. type: 7 /* DIRECTIVE */,
  4045. name: `bind`,
  4046. arg: createSimpleExpression(`style`, true, p.loc),
  4047. exp: parseInlineCSS(p.value.content, p.loc),
  4048. modifiers: [],
  4049. loc: p.loc
  4050. };
  4051. }
  4052. });
  4053. }
  4054. };
  4055. const parseInlineCSS = (cssText, loc) => {
  4056. const normalized = parseStringStyle(cssText);
  4057. return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
  4058. };
  4059. function createDOMCompilerError(code, loc) {
  4060. return createCompilerError(code, loc, DOMErrorMessages );
  4061. }
  4062. const DOMErrorMessages = {
  4063. [49 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  4064. [50 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  4065. [51 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  4066. [52 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  4067. [53 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  4068. [54 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  4069. [55 /* 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.`,
  4070. [56 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  4071. [57 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  4072. [58 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  4073. [59 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  4074. };
  4075. const transformVHtml = (dir, node, context) => {
  4076. const { exp, loc } = dir;
  4077. if (!exp) {
  4078. context.onError(createDOMCompilerError(49 /* X_V_HTML_NO_EXPRESSION */, loc));
  4079. }
  4080. if (node.children.length) {
  4081. context.onError(createDOMCompilerError(50 /* X_V_HTML_WITH_CHILDREN */, loc));
  4082. node.children.length = 0;
  4083. }
  4084. return {
  4085. props: [
  4086. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  4087. ]
  4088. };
  4089. };
  4090. const transformVText = (dir, node, context) => {
  4091. const { exp, loc } = dir;
  4092. if (!exp) {
  4093. context.onError(createDOMCompilerError(51 /* X_V_TEXT_NO_EXPRESSION */, loc));
  4094. }
  4095. if (node.children.length) {
  4096. context.onError(createDOMCompilerError(52 /* X_V_TEXT_WITH_CHILDREN */, loc));
  4097. node.children.length = 0;
  4098. }
  4099. return {
  4100. props: [
  4101. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  4102. ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  4103. : createSimpleExpression('', true))
  4104. ]
  4105. };
  4106. };
  4107. const transformModel$1 = (dir, node, context) => {
  4108. const baseResult = transformModel(dir, node, context);
  4109. // base transform has errors OR component v-model (only need props)
  4110. if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
  4111. return baseResult;
  4112. }
  4113. if (dir.arg) {
  4114. context.onError(createDOMCompilerError(54 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  4115. }
  4116. function checkDuplicatedValue() {
  4117. const value = findProp(node, 'value');
  4118. if (value) {
  4119. context.onError(createDOMCompilerError(56 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  4120. }
  4121. }
  4122. const { tag } = node;
  4123. const isCustomElement = context.isCustomElement(tag);
  4124. if (tag === 'input' ||
  4125. tag === 'textarea' ||
  4126. tag === 'select' ||
  4127. isCustomElement) {
  4128. let directiveToUse = V_MODEL_TEXT;
  4129. let isInvalidType = false;
  4130. if (tag === 'input' || isCustomElement) {
  4131. const type = findProp(node, `type`);
  4132. if (type) {
  4133. if (type.type === 7 /* DIRECTIVE */) {
  4134. // :type="foo"
  4135. directiveToUse = V_MODEL_DYNAMIC;
  4136. }
  4137. else if (type.value) {
  4138. switch (type.value.content) {
  4139. case 'radio':
  4140. directiveToUse = V_MODEL_RADIO;
  4141. break;
  4142. case 'checkbox':
  4143. directiveToUse = V_MODEL_CHECKBOX;
  4144. break;
  4145. case 'file':
  4146. isInvalidType = true;
  4147. context.onError(createDOMCompilerError(55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  4148. break;
  4149. default:
  4150. // text type
  4151. checkDuplicatedValue();
  4152. break;
  4153. }
  4154. }
  4155. }
  4156. else if (hasDynamicKeyVBind(node)) {
  4157. // element has bindings with dynamic keys, which can possibly contain
  4158. // "type".
  4159. directiveToUse = V_MODEL_DYNAMIC;
  4160. }
  4161. else {
  4162. // text type
  4163. checkDuplicatedValue();
  4164. }
  4165. }
  4166. else if (tag === 'select') {
  4167. directiveToUse = V_MODEL_SELECT;
  4168. }
  4169. else {
  4170. // textarea
  4171. checkDuplicatedValue();
  4172. }
  4173. // inject runtime directive
  4174. // by returning the helper symbol via needRuntime
  4175. // the import will replaced a resolveDirective call.
  4176. if (!isInvalidType) {
  4177. baseResult.needRuntime = context.helper(directiveToUse);
  4178. }
  4179. }
  4180. else {
  4181. context.onError(createDOMCompilerError(53 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  4182. }
  4183. // native vmodel doesn't need the `modelValue` props since they are also
  4184. // passed to the runtime as `binding.value`. removing it reduces code size.
  4185. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  4186. p.key.content === 'modelValue'));
  4187. return baseResult;
  4188. };
  4189. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  4190. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  4191. // event propagation management
  4192. `stop,prevent,self,` +
  4193. // system modifiers + exact
  4194. `ctrl,shift,alt,meta,exact,` +
  4195. // mouse
  4196. `middle`);
  4197. // left & right could be mouse or key modifiers based on event type
  4198. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  4199. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  4200. const resolveModifiers = (key, modifiers) => {
  4201. const keyModifiers = [];
  4202. const nonKeyModifiers = [];
  4203. const eventOptionModifiers = [];
  4204. for (let i = 0; i < modifiers.length; i++) {
  4205. const modifier = modifiers[i];
  4206. if (isEventOptionModifier(modifier)) {
  4207. // eventOptionModifiers: modifiers for addEventListener() options,
  4208. // e.g. .passive & .capture
  4209. eventOptionModifiers.push(modifier);
  4210. }
  4211. else {
  4212. // runtimeModifiers: modifiers that needs runtime guards
  4213. if (maybeKeyModifier(modifier)) {
  4214. if (isStaticExp(key)) {
  4215. if (isKeyboardEvent(key.content)) {
  4216. keyModifiers.push(modifier);
  4217. }
  4218. else {
  4219. nonKeyModifiers.push(modifier);
  4220. }
  4221. }
  4222. else {
  4223. keyModifiers.push(modifier);
  4224. nonKeyModifiers.push(modifier);
  4225. }
  4226. }
  4227. else {
  4228. if (isNonKeyModifier(modifier)) {
  4229. nonKeyModifiers.push(modifier);
  4230. }
  4231. else {
  4232. keyModifiers.push(modifier);
  4233. }
  4234. }
  4235. }
  4236. }
  4237. return {
  4238. keyModifiers,
  4239. nonKeyModifiers,
  4240. eventOptionModifiers
  4241. };
  4242. };
  4243. const transformClick = (key, event) => {
  4244. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  4245. return isStaticClick
  4246. ? createSimpleExpression(event, true)
  4247. : key.type !== 4 /* SIMPLE_EXPRESSION */
  4248. ? createCompoundExpression([
  4249. `(`,
  4250. key,
  4251. `) === "onClick" ? "${event}" : (`,
  4252. key,
  4253. `)`
  4254. ])
  4255. : key;
  4256. };
  4257. const transformOn$1 = (dir, node, context) => {
  4258. return transformOn(dir, node, context, baseResult => {
  4259. const { modifiers } = dir;
  4260. if (!modifiers.length)
  4261. return baseResult;
  4262. let { key, value: handlerExp } = baseResult.props[0];
  4263. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers);
  4264. // normalize click.right and click.middle since they don't actually fire
  4265. if (nonKeyModifiers.includes('right')) {
  4266. key = transformClick(key, `onContextmenu`);
  4267. }
  4268. if (nonKeyModifiers.includes('middle')) {
  4269. key = transformClick(key, `onMouseup`);
  4270. }
  4271. if (nonKeyModifiers.length) {
  4272. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  4273. handlerExp,
  4274. JSON.stringify(nonKeyModifiers)
  4275. ]);
  4276. }
  4277. if (keyModifiers.length &&
  4278. // if event name is dynamic, always wrap with keys guard
  4279. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  4280. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  4281. handlerExp,
  4282. JSON.stringify(keyModifiers)
  4283. ]);
  4284. }
  4285. if (eventOptionModifiers.length) {
  4286. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  4287. key = isStaticExp(key)
  4288. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  4289. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  4290. }
  4291. return {
  4292. props: [createObjectProperty(key, handlerExp)]
  4293. };
  4294. });
  4295. };
  4296. const transformShow = (dir, node, context) => {
  4297. const { exp, loc } = dir;
  4298. if (!exp) {
  4299. context.onError(createDOMCompilerError(57 /* X_V_SHOW_NO_EXPRESSION */, loc));
  4300. }
  4301. return {
  4302. props: [],
  4303. needRuntime: context.helper(V_SHOW)
  4304. };
  4305. };
  4306. const warnTransitionChildren = (node, context) => {
  4307. if (node.type === 1 /* ELEMENT */ &&
  4308. node.tagType === 1 /* COMPONENT */) {
  4309. const component = context.isBuiltInComponent(node.tag);
  4310. if (component === TRANSITION) {
  4311. return () => {
  4312. if (node.children.length && hasMultipleChildren(node)) {
  4313. context.onError(createDOMCompilerError(58 /* X_TRANSITION_INVALID_CHILDREN */, {
  4314. start: node.children[0].loc.start,
  4315. end: node.children[node.children.length - 1].loc.end,
  4316. source: ''
  4317. }));
  4318. }
  4319. };
  4320. }
  4321. }
  4322. };
  4323. function hasMultipleChildren(node) {
  4324. // #1352 filter out potential comment nodes.
  4325. const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */));
  4326. const child = children[0];
  4327. return (children.length !== 1 ||
  4328. child.type === 11 /* FOR */ ||
  4329. (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
  4330. }
  4331. const ignoreSideEffectTags = (node, context) => {
  4332. if (node.type === 1 /* ELEMENT */ &&
  4333. node.tagType === 0 /* ELEMENT */ &&
  4334. (node.tag === 'script' || node.tag === 'style')) {
  4335. context.onError(createDOMCompilerError(59 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  4336. context.removeNode();
  4337. }
  4338. };
  4339. const DOMNodeTransforms = [
  4340. transformStyle,
  4341. ...([warnTransitionChildren] )
  4342. ];
  4343. const DOMDirectiveTransforms = {
  4344. cloak: noopDirectiveTransform,
  4345. html: transformVHtml,
  4346. text: transformVText,
  4347. model: transformModel$1,
  4348. on: transformOn$1,
  4349. show: transformShow
  4350. };
  4351. function compile(template, options = {}) {
  4352. return baseCompile(template, extend({}, parserOptions, options, {
  4353. nodeTransforms: [
  4354. // ignore <script> and <tag>
  4355. // this is not put inside DOMNodeTransforms because that list is used
  4356. // by compiler-ssr to generate vnode fallback branches
  4357. ignoreSideEffectTags,
  4358. ...DOMNodeTransforms,
  4359. ...(options.nodeTransforms || [])
  4360. ],
  4361. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  4362. transformHoist: null
  4363. }));
  4364. }
  4365. function parse(template, options = {}) {
  4366. return baseParse(template, extend({}, parserOptions, options));
  4367. }
  4368. export { BASE_TRANSITION, CAMELIZE, CAPITALIZE, CREATE_BLOCK, CREATE_COMMENT, CREATE_SLOTS, CREATE_STATIC, CREATE_TEXT, CREATE_VNODE, DOMDirectiveTransforms, DOMNodeTransforms, FRAGMENT, IS_REF, KEEP_ALIVE, MERGE_PROPS, OPEN_BLOCK, POP_SCOPE_ID, PUSH_SCOPE_ID, RENDER_LIST, RENDER_SLOT, RESOLVE_COMPONENT, RESOLVE_DIRECTIVE, RESOLVE_DYNAMIC_COMPONENT, SET_BLOCK_TRACKING, SUSPENSE, TELEPORT, TO_DISPLAY_STRING, TO_HANDLERS, TO_HANDLER_KEY, TRANSITION, TRANSITION_GROUP, UNREF, V_MODEL_CHECKBOX, V_MODEL_DYNAMIC, V_MODEL_RADIO, V_MODEL_SELECT, V_MODEL_TEXT, V_ON_WITH_KEYS, V_ON_WITH_MODIFIERS, V_SHOW, WITH_CTX, WITH_DIRECTIVES, WITH_SCOPE_ID, advancePositionWithClone, advancePositionWithMutation, assert, baseCompile, baseParse, buildProps, buildSlots, compile, createArrayExpression, createAssignmentExpression, createBlockStatement, createCacheExpression, createCallExpression, createCompilerError, createCompoundExpression, createConditionalExpression, createDOMCompilerError, createForLoopParams, createFunctionExpression, createIfStatement, createInterpolation, createObjectExpression, createObjectProperty, createReturnStatement, createRoot, createSequenceExpression, createSimpleExpression, createStructuralDirectiveTransform, createTemplateLiteral, createTransformContext, createVNodeCall, findDir, findProp, generate, generateCodeFrame, getBaseTransformPreset, getInnerRange, hasDynamicKeyVBind, hasScopeRef, helperNameMap, injectProp, isBindKey, isBuiltInType, isCoreComponent, isMemberExpression, isSimpleIdentifier, isSlotOutlet, isStaticExp, isTemplateNode, isText, isVSlot, locStub, noopDirectiveTransform, parse, parserOptions, processExpression, processFor, processIf, processSlotOutlet, registerRuntimeHelpers, resolveComponentType, toValidAssetId, trackSlotScopes, trackVForSlotScopes, transform, transformBind, transformElement, transformExpression, transformModel, transformOn, transformStyle, traverseNode };