compiler-core.cjs.prod.js 167 KB

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