compiler-core.cjs.js 160 KB

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