compiler-core.cjs.prod.js 210 KB

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