compiler-core.cjs.prod.js 212 KB

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