compiler-dom.global.js 220 KB

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