compiler-dom.esm-browser.js 206 KB

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