compiler-dom.global.js 231 KB

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