compiler-dom.esm-browser.js 205 KB

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