compiler-core.cjs.js 218 KB

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