compiler-core.cjs.js 217 KB

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