compiler-dom.global.js 171 KB

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