vue.global.js 518 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684
  1. var Vue = (function (exports) {
  2. 'use strict';
  3. /**
  4. * Make a map and return a function for checking if a key
  5. * is in that map.
  6. * IMPORTANT: all calls of this function must be prefixed with
  7. * \/\*#\_\_PURE\_\_\*\/
  8. * So that rollup can tree-shake them if necessary.
  9. */
  10. function makeMap(str, expectsLowerCase) {
  11. const map = Object.create(null);
  12. const list = str.split(',');
  13. for (let i = 0; i < list.length; i++) {
  14. map[list[i]] = true;
  15. }
  16. return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
  17. }
  18. /**
  19. * dev only flag -> name mapping
  20. */
  21. const PatchFlagNames = {
  22. [1 /* TEXT */]: `TEXT`,
  23. [2 /* CLASS */]: `CLASS`,
  24. [4 /* STYLE */]: `STYLE`,
  25. [8 /* PROPS */]: `PROPS`,
  26. [16 /* FULL_PROPS */]: `FULL_PROPS`,
  27. [32 /* HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
  28. [64 /* STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
  29. [128 /* KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
  30. [256 /* UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
  31. [512 /* NEED_PATCH */]: `NEED_PATCH`,
  32. [1024 /* DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
  33. [2048 /* DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
  34. [-1 /* HOISTED */]: `HOISTED`,
  35. [-2 /* BAIL */]: `BAIL`
  36. };
  37. /**
  38. * Dev only
  39. */
  40. const slotFlagsText = {
  41. [1 /* STABLE */]: 'STABLE',
  42. [2 /* DYNAMIC */]: 'DYNAMIC',
  43. [3 /* FORWARDED */]: 'FORWARDED'
  44. };
  45. const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' +
  46. 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
  47. 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt';
  48. const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED);
  49. const range = 2;
  50. function generateCodeFrame(source, start = 0, end = source.length) {
  51. const lines = source.split(/\r?\n/);
  52. let count = 0;
  53. const res = [];
  54. for (let i = 0; i < lines.length; i++) {
  55. count += lines[i].length + 1;
  56. if (count >= start) {
  57. for (let j = i - range; j <= i + range || end > count; j++) {
  58. if (j < 0 || j >= lines.length)
  59. continue;
  60. const line = j + 1;
  61. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  62. const lineLength = lines[j].length;
  63. if (j === i) {
  64. // push underline
  65. const pad = start - (count - lineLength) + 1;
  66. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  67. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  68. }
  69. else if (j > i) {
  70. if (end > count) {
  71. const length = Math.max(Math.min(end - count, lineLength), 1);
  72. res.push(` | ` + '^'.repeat(length));
  73. }
  74. count += lineLength + 1;
  75. }
  76. }
  77. break;
  78. }
  79. }
  80. return res.join('\n');
  81. }
  82. /**
  83. * On the client we only need to offer special cases for boolean attributes that
  84. * have different names from their corresponding dom properties:
  85. * - itemscope -> N/A
  86. * - allowfullscreen -> allowFullscreen
  87. * - formnovalidate -> formNoValidate
  88. * - ismap -> isMap
  89. * - nomodule -> noModule
  90. * - novalidate -> noValidate
  91. * - readonly -> readOnly
  92. */
  93. const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
  94. const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs);
  95. function normalizeStyle(value) {
  96. if (isArray(value)) {
  97. const res = {};
  98. for (let i = 0; i < value.length; i++) {
  99. const item = value[i];
  100. const normalized = normalizeStyle(isString(item) ? parseStringStyle(item) : item);
  101. if (normalized) {
  102. for (const key in normalized) {
  103. res[key] = normalized[key];
  104. }
  105. }
  106. }
  107. return res;
  108. }
  109. else if (isObject(value)) {
  110. return value;
  111. }
  112. }
  113. const listDelimiterRE = /;(?![^(]*\))/g;
  114. const propertyDelimiterRE = /:(.+)/;
  115. function parseStringStyle(cssText) {
  116. const ret = {};
  117. cssText.split(listDelimiterRE).forEach(item => {
  118. if (item) {
  119. const tmp = item.split(propertyDelimiterRE);
  120. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  121. }
  122. });
  123. return ret;
  124. }
  125. function normalizeClass(value) {
  126. let res = '';
  127. if (isString(value)) {
  128. res = value;
  129. }
  130. else if (isArray(value)) {
  131. for (let i = 0; i < value.length; i++) {
  132. const normalized = normalizeClass(value[i]);
  133. if (normalized) {
  134. res += normalized + ' ';
  135. }
  136. }
  137. }
  138. else if (isObject(value)) {
  139. for (const name in value) {
  140. if (value[name]) {
  141. res += name + ' ';
  142. }
  143. }
  144. }
  145. return res.trim();
  146. }
  147. // These tag configs are shared between compiler-dom and runtime-dom, so they
  148. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  149. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  150. 'header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,' +
  151. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  152. 'data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,' +
  153. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  154. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  155. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  156. 'option,output,progress,select,textarea,details,dialog,menu,' +
  157. 'summary,template,blockquote,iframe,tfoot';
  158. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  159. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  160. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  161. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  162. 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  163. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  164. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  165. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  166. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  167. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  168. 'text,textPath,title,tspan,unknown,use,view';
  169. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  170. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  171. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  172. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  173. function looseCompareArrays(a, b) {
  174. if (a.length !== b.length)
  175. return false;
  176. let equal = true;
  177. for (let i = 0; equal && i < a.length; i++) {
  178. equal = looseEqual(a[i], b[i]);
  179. }
  180. return equal;
  181. }
  182. function looseEqual(a, b) {
  183. if (a === b)
  184. return true;
  185. let aValidType = isDate(a);
  186. let bValidType = isDate(b);
  187. if (aValidType || bValidType) {
  188. return aValidType && bValidType ? a.getTime() === b.getTime() : false;
  189. }
  190. aValidType = isArray(a);
  191. bValidType = isArray(b);
  192. if (aValidType || bValidType) {
  193. return aValidType && bValidType ? looseCompareArrays(a, b) : false;
  194. }
  195. aValidType = isObject(a);
  196. bValidType = isObject(b);
  197. if (aValidType || bValidType) {
  198. /* istanbul ignore if: this if will probably never be called */
  199. if (!aValidType || !bValidType) {
  200. return false;
  201. }
  202. const aKeysCount = Object.keys(a).length;
  203. const bKeysCount = Object.keys(b).length;
  204. if (aKeysCount !== bKeysCount) {
  205. return false;
  206. }
  207. for (const key in a) {
  208. const aHasKey = a.hasOwnProperty(key);
  209. const bHasKey = b.hasOwnProperty(key);
  210. if ((aHasKey && !bHasKey) ||
  211. (!aHasKey && bHasKey) ||
  212. !looseEqual(a[key], b[key])) {
  213. return false;
  214. }
  215. }
  216. }
  217. return String(a) === String(b);
  218. }
  219. function looseIndexOf(arr, val) {
  220. return arr.findIndex(item => looseEqual(item, val));
  221. }
  222. /**
  223. * For converting {{ interpolation }} values to displayed strings.
  224. * @private
  225. */
  226. const toDisplayString = (val) => {
  227. return val == null
  228. ? ''
  229. : isObject(val)
  230. ? JSON.stringify(val, replacer, 2)
  231. : String(val);
  232. };
  233. const replacer = (_key, val) => {
  234. if (isMap(val)) {
  235. return {
  236. [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
  237. entries[`${key} =>`] = val;
  238. return entries;
  239. }, {})
  240. };
  241. }
  242. else if (isSet(val)) {
  243. return {
  244. [`Set(${val.size})`]: [...val.values()]
  245. };
  246. }
  247. else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
  248. return String(val);
  249. }
  250. return val;
  251. };
  252. const EMPTY_OBJ = Object.freeze({})
  253. ;
  254. const EMPTY_ARR = Object.freeze([]) ;
  255. const NOOP = () => { };
  256. /**
  257. * Always return false.
  258. */
  259. const NO = () => false;
  260. const onRE = /^on[^a-z]/;
  261. const isOn = (key) => onRE.test(key);
  262. const isModelListener = (key) => key.startsWith('onUpdate:');
  263. const extend = Object.assign;
  264. const remove = (arr, el) => {
  265. const i = arr.indexOf(el);
  266. if (i > -1) {
  267. arr.splice(i, 1);
  268. }
  269. };
  270. const hasOwnProperty = Object.prototype.hasOwnProperty;
  271. const hasOwn = (val, key) => hasOwnProperty.call(val, key);
  272. const isArray = Array.isArray;
  273. const isMap = (val) => toTypeString(val) === '[object Map]';
  274. const isSet = (val) => toTypeString(val) === '[object Set]';
  275. const isDate = (val) => val instanceof Date;
  276. const isFunction = (val) => typeof val === 'function';
  277. const isString = (val) => typeof val === 'string';
  278. const isSymbol = (val) => typeof val === 'symbol';
  279. const isObject = (val) => val !== null && typeof val === 'object';
  280. const isPromise = (val) => {
  281. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  282. };
  283. const objectToString = Object.prototype.toString;
  284. const toTypeString = (value) => objectToString.call(value);
  285. const toRawType = (value) => {
  286. // extract "RawType" from strings like "[object RawType]"
  287. return toTypeString(value).slice(8, -1);
  288. };
  289. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  290. const isIntegerKey = (key) => isString(key) &&
  291. key !== 'NaN' &&
  292. key[0] !== '-' &&
  293. '' + parseInt(key, 10) === key;
  294. const isReservedProp = /*#__PURE__*/ makeMap(
  295. // the leading comma is intentional so empty string "" is also included
  296. ',key,ref,' +
  297. 'onVnodeBeforeMount,onVnodeMounted,' +
  298. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  299. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  300. const cacheStringFunction = (fn) => {
  301. const cache = Object.create(null);
  302. return ((str) => {
  303. const hit = cache[str];
  304. return hit || (cache[str] = fn(str));
  305. });
  306. };
  307. const camelizeRE = /-(\w)/g;
  308. /**
  309. * @private
  310. */
  311. const camelize = cacheStringFunction((str) => {
  312. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  313. });
  314. const hyphenateRE = /\B([A-Z])/g;
  315. /**
  316. * @private
  317. */
  318. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  319. /**
  320. * @private
  321. */
  322. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  323. /**
  324. * @private
  325. */
  326. const toHandlerKey = cacheStringFunction((str) => (str ? `on${capitalize(str)}` : ``));
  327. // compare whether a value has changed, accounting for NaN.
  328. const hasChanged = (value, oldValue) => value !== oldValue && (value === value || oldValue === oldValue);
  329. const invokeArrayFns = (fns, arg) => {
  330. for (let i = 0; i < fns.length; i++) {
  331. fns[i](arg);
  332. }
  333. };
  334. const def = (obj, key, value) => {
  335. Object.defineProperty(obj, key, {
  336. configurable: true,
  337. enumerable: false,
  338. value
  339. });
  340. };
  341. const toNumber = (val) => {
  342. const n = parseFloat(val);
  343. return isNaN(n) ? val : n;
  344. };
  345. let _globalThis;
  346. const getGlobalThis = () => {
  347. return (_globalThis ||
  348. (_globalThis =
  349. typeof globalThis !== 'undefined'
  350. ? globalThis
  351. : typeof self !== 'undefined'
  352. ? self
  353. : typeof window !== 'undefined'
  354. ? window
  355. : typeof global !== 'undefined'
  356. ? global
  357. : {}));
  358. };
  359. const targetMap = new WeakMap();
  360. const effectStack = [];
  361. let activeEffect;
  362. const ITERATE_KEY = Symbol('iterate' );
  363. const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
  364. function isEffect(fn) {
  365. return fn && fn._isEffect === true;
  366. }
  367. function effect(fn, options = EMPTY_OBJ) {
  368. if (isEffect(fn)) {
  369. fn = fn.raw;
  370. }
  371. const effect = createReactiveEffect(fn, options);
  372. if (!options.lazy) {
  373. effect();
  374. }
  375. return effect;
  376. }
  377. function stop(effect) {
  378. if (effect.active) {
  379. cleanup(effect);
  380. if (effect.options.onStop) {
  381. effect.options.onStop();
  382. }
  383. effect.active = false;
  384. }
  385. }
  386. let uid = 0;
  387. function createReactiveEffect(fn, options) {
  388. const effect = function reactiveEffect() {
  389. if (!effect.active) {
  390. return options.scheduler ? undefined : fn();
  391. }
  392. if (!effectStack.includes(effect)) {
  393. cleanup(effect);
  394. try {
  395. enableTracking();
  396. effectStack.push(effect);
  397. activeEffect = effect;
  398. return fn();
  399. }
  400. finally {
  401. effectStack.pop();
  402. resetTracking();
  403. activeEffect = effectStack[effectStack.length - 1];
  404. }
  405. }
  406. };
  407. effect.id = uid++;
  408. effect.allowRecurse = !!options.allowRecurse;
  409. effect._isEffect = true;
  410. effect.active = true;
  411. effect.raw = fn;
  412. effect.deps = [];
  413. effect.options = options;
  414. return effect;
  415. }
  416. function cleanup(effect) {
  417. const { deps } = effect;
  418. if (deps.length) {
  419. for (let i = 0; i < deps.length; i++) {
  420. deps[i].delete(effect);
  421. }
  422. deps.length = 0;
  423. }
  424. }
  425. let shouldTrack = true;
  426. const trackStack = [];
  427. function pauseTracking() {
  428. trackStack.push(shouldTrack);
  429. shouldTrack = false;
  430. }
  431. function enableTracking() {
  432. trackStack.push(shouldTrack);
  433. shouldTrack = true;
  434. }
  435. function resetTracking() {
  436. const last = trackStack.pop();
  437. shouldTrack = last === undefined ? true : last;
  438. }
  439. function track(target, type, key) {
  440. if (!shouldTrack || activeEffect === undefined) {
  441. return;
  442. }
  443. let depsMap = targetMap.get(target);
  444. if (!depsMap) {
  445. targetMap.set(target, (depsMap = new Map()));
  446. }
  447. let dep = depsMap.get(key);
  448. if (!dep) {
  449. depsMap.set(key, (dep = new Set()));
  450. }
  451. if (!dep.has(activeEffect)) {
  452. dep.add(activeEffect);
  453. activeEffect.deps.push(dep);
  454. if (activeEffect.options.onTrack) {
  455. activeEffect.options.onTrack({
  456. effect: activeEffect,
  457. target,
  458. type,
  459. key
  460. });
  461. }
  462. }
  463. }
  464. function trigger(target, type, key, newValue, oldValue, oldTarget) {
  465. const depsMap = targetMap.get(target);
  466. if (!depsMap) {
  467. // never been tracked
  468. return;
  469. }
  470. const effects = new Set();
  471. const add = (effectsToAdd) => {
  472. if (effectsToAdd) {
  473. effectsToAdd.forEach(effect => {
  474. if (effect !== activeEffect || effect.allowRecurse) {
  475. effects.add(effect);
  476. }
  477. });
  478. }
  479. };
  480. if (type === "clear" /* CLEAR */) {
  481. // collection being cleared
  482. // trigger all effects for target
  483. depsMap.forEach(add);
  484. }
  485. else if (key === 'length' && isArray(target)) {
  486. depsMap.forEach((dep, key) => {
  487. if (key === 'length' || key >= newValue) {
  488. add(dep);
  489. }
  490. });
  491. }
  492. else {
  493. // schedule runs for SET | ADD | DELETE
  494. if (key !== void 0) {
  495. add(depsMap.get(key));
  496. }
  497. // also run for iteration key on ADD | DELETE | Map.SET
  498. switch (type) {
  499. case "add" /* ADD */:
  500. if (!isArray(target)) {
  501. add(depsMap.get(ITERATE_KEY));
  502. if (isMap(target)) {
  503. add(depsMap.get(MAP_KEY_ITERATE_KEY));
  504. }
  505. }
  506. else if (isIntegerKey(key)) {
  507. // new index added to array -> length changes
  508. add(depsMap.get('length'));
  509. }
  510. break;
  511. case "delete" /* DELETE */:
  512. if (!isArray(target)) {
  513. add(depsMap.get(ITERATE_KEY));
  514. if (isMap(target)) {
  515. add(depsMap.get(MAP_KEY_ITERATE_KEY));
  516. }
  517. }
  518. break;
  519. case "set" /* SET */:
  520. if (isMap(target)) {
  521. add(depsMap.get(ITERATE_KEY));
  522. }
  523. break;
  524. }
  525. }
  526. const run = (effect) => {
  527. if (effect.options.onTrigger) {
  528. effect.options.onTrigger({
  529. effect,
  530. target,
  531. key,
  532. type,
  533. newValue,
  534. oldValue,
  535. oldTarget
  536. });
  537. }
  538. if (effect.options.scheduler) {
  539. effect.options.scheduler(effect);
  540. }
  541. else {
  542. effect();
  543. }
  544. };
  545. effects.forEach(run);
  546. }
  547. const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
  548. const builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol)
  549. .map(key => Symbol[key])
  550. .filter(isSymbol));
  551. const get = /*#__PURE__*/ createGetter();
  552. const shallowGet = /*#__PURE__*/ createGetter(false, true);
  553. const readonlyGet = /*#__PURE__*/ createGetter(true);
  554. const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
  555. const arrayInstrumentations = {};
  556. ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
  557. const method = Array.prototype[key];
  558. arrayInstrumentations[key] = function (...args) {
  559. const arr = toRaw(this);
  560. for (let i = 0, l = this.length; i < l; i++) {
  561. track(arr, "get" /* GET */, i + '');
  562. }
  563. // we run the method using the original args first (which may be reactive)
  564. const res = method.apply(arr, args);
  565. if (res === -1 || res === false) {
  566. // if that didn't work, run it again using raw values.
  567. return method.apply(arr, args.map(toRaw));
  568. }
  569. else {
  570. return res;
  571. }
  572. };
  573. });
  574. ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
  575. const method = Array.prototype[key];
  576. arrayInstrumentations[key] = function (...args) {
  577. pauseTracking();
  578. const res = method.apply(this, args);
  579. resetTracking();
  580. return res;
  581. };
  582. });
  583. function createGetter(isReadonly = false, shallow = false) {
  584. return function get(target, key, receiver) {
  585. if (key === "__v_isReactive" /* IS_REACTIVE */) {
  586. return !isReadonly;
  587. }
  588. else if (key === "__v_isReadonly" /* IS_READONLY */) {
  589. return isReadonly;
  590. }
  591. else if (key === "__v_raw" /* RAW */ &&
  592. receiver === (isReadonly ? readonlyMap : reactiveMap).get(target)) {
  593. return target;
  594. }
  595. const targetIsArray = isArray(target);
  596. if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
  597. return Reflect.get(arrayInstrumentations, key, receiver);
  598. }
  599. const res = Reflect.get(target, key, receiver);
  600. if (isSymbol(key)
  601. ? builtInSymbols.has(key)
  602. : isNonTrackableKeys(key)) {
  603. return res;
  604. }
  605. if (!isReadonly) {
  606. track(target, "get" /* GET */, key);
  607. }
  608. if (shallow) {
  609. return res;
  610. }
  611. if (isRef(res)) {
  612. // ref unwrapping - does not apply for Array + integer key.
  613. const shouldUnwrap = !targetIsArray || !isIntegerKey(key);
  614. return shouldUnwrap ? res.value : res;
  615. }
  616. if (isObject(res)) {
  617. // Convert returned value into a proxy as well. we do the isObject check
  618. // here to avoid invalid value warning. Also need to lazy access readonly
  619. // and reactive here to avoid circular dependency.
  620. return isReadonly ? readonly(res) : reactive(res);
  621. }
  622. return res;
  623. };
  624. }
  625. const set = /*#__PURE__*/ createSetter();
  626. const shallowSet = /*#__PURE__*/ createSetter(true);
  627. function createSetter(shallow = false) {
  628. return function set(target, key, value, receiver) {
  629. const oldValue = target[key];
  630. if (!shallow) {
  631. value = toRaw(value);
  632. if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
  633. oldValue.value = value;
  634. return true;
  635. }
  636. }
  637. const hadKey = isArray(target) && isIntegerKey(key)
  638. ? Number(key) < target.length
  639. : hasOwn(target, key);
  640. const result = Reflect.set(target, key, value, receiver);
  641. // don't trigger if target is something up in the prototype chain of original
  642. if (target === toRaw(receiver)) {
  643. if (!hadKey) {
  644. trigger(target, "add" /* ADD */, key, value);
  645. }
  646. else if (hasChanged(value, oldValue)) {
  647. trigger(target, "set" /* SET */, key, value, oldValue);
  648. }
  649. }
  650. return result;
  651. };
  652. }
  653. function deleteProperty(target, key) {
  654. const hadKey = hasOwn(target, key);
  655. const oldValue = target[key];
  656. const result = Reflect.deleteProperty(target, key);
  657. if (result && hadKey) {
  658. trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
  659. }
  660. return result;
  661. }
  662. function has(target, key) {
  663. const result = Reflect.has(target, key);
  664. if (!isSymbol(key) || !builtInSymbols.has(key)) {
  665. track(target, "has" /* HAS */, key);
  666. }
  667. return result;
  668. }
  669. function ownKeys(target) {
  670. track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
  671. return Reflect.ownKeys(target);
  672. }
  673. const mutableHandlers = {
  674. get,
  675. set,
  676. deleteProperty,
  677. has,
  678. ownKeys
  679. };
  680. const readonlyHandlers = {
  681. get: readonlyGet,
  682. set(target, key) {
  683. {
  684. console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
  685. }
  686. return true;
  687. },
  688. deleteProperty(target, key) {
  689. {
  690. console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
  691. }
  692. return true;
  693. }
  694. };
  695. const shallowReactiveHandlers = extend({}, mutableHandlers, {
  696. get: shallowGet,
  697. set: shallowSet
  698. });
  699. // Props handlers are special in the sense that it should not unwrap top-level
  700. // refs (in order to allow refs to be explicitly passed down), but should
  701. // retain the reactivity of the normal readonly object.
  702. const shallowReadonlyHandlers = extend({}, readonlyHandlers, {
  703. get: shallowReadonlyGet
  704. });
  705. const toReactive = (value) => isObject(value) ? reactive(value) : value;
  706. const toReadonly = (value) => isObject(value) ? readonly(value) : value;
  707. const toShallow = (value) => value;
  708. const getProto = (v) => Reflect.getPrototypeOf(v);
  709. function get$1(target, key, isReadonly = false, isShallow = false) {
  710. // #1772: readonly(reactive(Map)) should return readonly + reactive version
  711. // of the value
  712. target = target["__v_raw" /* RAW */];
  713. const rawTarget = toRaw(target);
  714. const rawKey = toRaw(key);
  715. if (key !== rawKey) {
  716. !isReadonly && track(rawTarget, "get" /* GET */, key);
  717. }
  718. !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
  719. const { has } = getProto(rawTarget);
  720. const wrap = isReadonly ? toReadonly : isShallow ? toShallow : toReactive;
  721. if (has.call(rawTarget, key)) {
  722. return wrap(target.get(key));
  723. }
  724. else if (has.call(rawTarget, rawKey)) {
  725. return wrap(target.get(rawKey));
  726. }
  727. }
  728. function has$1(key, isReadonly = false) {
  729. const target = this["__v_raw" /* RAW */];
  730. const rawTarget = toRaw(target);
  731. const rawKey = toRaw(key);
  732. if (key !== rawKey) {
  733. !isReadonly && track(rawTarget, "has" /* HAS */, key);
  734. }
  735. !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
  736. return key === rawKey
  737. ? target.has(key)
  738. : target.has(key) || target.has(rawKey);
  739. }
  740. function size(target, isReadonly = false) {
  741. target = target["__v_raw" /* RAW */];
  742. !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
  743. return Reflect.get(target, 'size', target);
  744. }
  745. function add(value) {
  746. value = toRaw(value);
  747. const target = toRaw(this);
  748. const proto = getProto(target);
  749. const hadKey = proto.has.call(target, value);
  750. target.add(value);
  751. if (!hadKey) {
  752. trigger(target, "add" /* ADD */, value, value);
  753. }
  754. return this;
  755. }
  756. function set$1(key, value) {
  757. value = toRaw(value);
  758. const target = toRaw(this);
  759. const { has, get } = getProto(target);
  760. let hadKey = has.call(target, key);
  761. if (!hadKey) {
  762. key = toRaw(key);
  763. hadKey = has.call(target, key);
  764. }
  765. else {
  766. checkIdentityKeys(target, has, key);
  767. }
  768. const oldValue = get.call(target, key);
  769. target.set(key, value);
  770. if (!hadKey) {
  771. trigger(target, "add" /* ADD */, key, value);
  772. }
  773. else if (hasChanged(value, oldValue)) {
  774. trigger(target, "set" /* SET */, key, value, oldValue);
  775. }
  776. return this;
  777. }
  778. function deleteEntry(key) {
  779. const target = toRaw(this);
  780. const { has, get } = getProto(target);
  781. let hadKey = has.call(target, key);
  782. if (!hadKey) {
  783. key = toRaw(key);
  784. hadKey = has.call(target, key);
  785. }
  786. else {
  787. checkIdentityKeys(target, has, key);
  788. }
  789. const oldValue = get ? get.call(target, key) : undefined;
  790. // forward the operation before queueing reactions
  791. const result = target.delete(key);
  792. if (hadKey) {
  793. trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
  794. }
  795. return result;
  796. }
  797. function clear() {
  798. const target = toRaw(this);
  799. const hadItems = target.size !== 0;
  800. const oldTarget = isMap(target)
  801. ? new Map(target)
  802. : new Set(target)
  803. ;
  804. // forward the operation before queueing reactions
  805. const result = target.clear();
  806. if (hadItems) {
  807. trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
  808. }
  809. return result;
  810. }
  811. function createForEach(isReadonly, isShallow) {
  812. return function forEach(callback, thisArg) {
  813. const observed = this;
  814. const target = observed["__v_raw" /* RAW */];
  815. const rawTarget = toRaw(target);
  816. const wrap = isReadonly ? toReadonly : isShallow ? toShallow : toReactive;
  817. !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
  818. return target.forEach((value, key) => {
  819. // important: make sure the callback is
  820. // 1. invoked with the reactive map as `this` and 3rd arg
  821. // 2. the value received should be a corresponding reactive/readonly.
  822. return callback.call(thisArg, wrap(value), wrap(key), observed);
  823. });
  824. };
  825. }
  826. function createIterableMethod(method, isReadonly, isShallow) {
  827. return function (...args) {
  828. const target = this["__v_raw" /* RAW */];
  829. const rawTarget = toRaw(target);
  830. const targetIsMap = isMap(rawTarget);
  831. const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
  832. const isKeyOnly = method === 'keys' && targetIsMap;
  833. const innerIterator = target[method](...args);
  834. const wrap = isReadonly ? toReadonly : isShallow ? toShallow : toReactive;
  835. !isReadonly &&
  836. track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
  837. // return a wrapped iterator which returns observed versions of the
  838. // values emitted from the real iterator
  839. return {
  840. // iterator protocol
  841. next() {
  842. const { value, done } = innerIterator.next();
  843. return done
  844. ? { value, done }
  845. : {
  846. value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
  847. done
  848. };
  849. },
  850. // iterable protocol
  851. [Symbol.iterator]() {
  852. return this;
  853. }
  854. };
  855. };
  856. }
  857. function createReadonlyMethod(type) {
  858. return function (...args) {
  859. {
  860. const key = args[0] ? `on key "${args[0]}" ` : ``;
  861. console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
  862. }
  863. return type === "delete" /* DELETE */ ? false : this;
  864. };
  865. }
  866. const mutableInstrumentations = {
  867. get(key) {
  868. return get$1(this, key);
  869. },
  870. get size() {
  871. return size(this);
  872. },
  873. has: has$1,
  874. add,
  875. set: set$1,
  876. delete: deleteEntry,
  877. clear,
  878. forEach: createForEach(false, false)
  879. };
  880. const shallowInstrumentations = {
  881. get(key) {
  882. return get$1(this, key, false, true);
  883. },
  884. get size() {
  885. return size(this);
  886. },
  887. has: has$1,
  888. add,
  889. set: set$1,
  890. delete: deleteEntry,
  891. clear,
  892. forEach: createForEach(false, true)
  893. };
  894. const readonlyInstrumentations = {
  895. get(key) {
  896. return get$1(this, key, true);
  897. },
  898. get size() {
  899. return size(this, true);
  900. },
  901. has(key) {
  902. return has$1.call(this, key, true);
  903. },
  904. add: createReadonlyMethod("add" /* ADD */),
  905. set: createReadonlyMethod("set" /* SET */),
  906. delete: createReadonlyMethod("delete" /* DELETE */),
  907. clear: createReadonlyMethod("clear" /* CLEAR */),
  908. forEach: createForEach(true, false)
  909. };
  910. const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
  911. iteratorMethods.forEach(method => {
  912. mutableInstrumentations[method] = createIterableMethod(method, false, false);
  913. readonlyInstrumentations[method] = createIterableMethod(method, true, false);
  914. shallowInstrumentations[method] = createIterableMethod(method, false, true);
  915. });
  916. function createInstrumentationGetter(isReadonly, shallow) {
  917. const instrumentations = shallow
  918. ? shallowInstrumentations
  919. : isReadonly
  920. ? readonlyInstrumentations
  921. : mutableInstrumentations;
  922. return (target, key, receiver) => {
  923. if (key === "__v_isReactive" /* IS_REACTIVE */) {
  924. return !isReadonly;
  925. }
  926. else if (key === "__v_isReadonly" /* IS_READONLY */) {
  927. return isReadonly;
  928. }
  929. else if (key === "__v_raw" /* RAW */) {
  930. return target;
  931. }
  932. return Reflect.get(hasOwn(instrumentations, key) && key in target
  933. ? instrumentations
  934. : target, key, receiver);
  935. };
  936. }
  937. const mutableCollectionHandlers = {
  938. get: createInstrumentationGetter(false, false)
  939. };
  940. const shallowCollectionHandlers = {
  941. get: createInstrumentationGetter(false, true)
  942. };
  943. const readonlyCollectionHandlers = {
  944. get: createInstrumentationGetter(true, false)
  945. };
  946. function checkIdentityKeys(target, has, key) {
  947. const rawKey = toRaw(key);
  948. if (rawKey !== key && has.call(target, rawKey)) {
  949. const type = toRawType(target);
  950. console.warn(`Reactive ${type} contains both the raw and reactive ` +
  951. `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
  952. `which can lead to inconsistencies. ` +
  953. `Avoid differentiating between the raw and reactive versions ` +
  954. `of an object and only use the reactive version if possible.`);
  955. }
  956. }
  957. const reactiveMap = new WeakMap();
  958. const readonlyMap = new WeakMap();
  959. function targetTypeMap(rawType) {
  960. switch (rawType) {
  961. case 'Object':
  962. case 'Array':
  963. return 1 /* COMMON */;
  964. case 'Map':
  965. case 'Set':
  966. case 'WeakMap':
  967. case 'WeakSet':
  968. return 2 /* COLLECTION */;
  969. default:
  970. return 0 /* INVALID */;
  971. }
  972. }
  973. function getTargetType(value) {
  974. return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
  975. ? 0 /* INVALID */
  976. : targetTypeMap(toRawType(value));
  977. }
  978. function reactive(target) {
  979. // if trying to observe a readonly proxy, return the readonly version.
  980. if (target && target["__v_isReadonly" /* IS_READONLY */]) {
  981. return target;
  982. }
  983. return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers);
  984. }
  985. /**
  986. * Return a shallowly-reactive copy of the original object, where only the root
  987. * level properties are reactive. It also does not auto-unwrap refs (even at the
  988. * root level).
  989. */
  990. function shallowReactive(target) {
  991. return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers);
  992. }
  993. /**
  994. * Creates a readonly copy of the original object. Note the returned copy is not
  995. * made reactive, but `readonly` can be called on an already reactive object.
  996. */
  997. function readonly(target) {
  998. return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers);
  999. }
  1000. /**
  1001. * Returns a reactive-copy of the original object, where only the root level
  1002. * properties are readonly, and does NOT unwrap refs nor recursively convert
  1003. * returned properties.
  1004. * This is used for creating the props proxy object for stateful components.
  1005. */
  1006. function shallowReadonly(target) {
  1007. return createReactiveObject(target, true, shallowReadonlyHandlers, readonlyCollectionHandlers);
  1008. }
  1009. function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers) {
  1010. if (!isObject(target)) {
  1011. {
  1012. console.warn(`value cannot be made reactive: ${String(target)}`);
  1013. }
  1014. return target;
  1015. }
  1016. // target is already a Proxy, return it.
  1017. // exception: calling readonly() on a reactive object
  1018. if (target["__v_raw" /* RAW */] &&
  1019. !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
  1020. return target;
  1021. }
  1022. // target already has corresponding Proxy
  1023. const proxyMap = isReadonly ? readonlyMap : reactiveMap;
  1024. const existingProxy = proxyMap.get(target);
  1025. if (existingProxy) {
  1026. return existingProxy;
  1027. }
  1028. // only a whitelist of value types can be observed.
  1029. const targetType = getTargetType(target);
  1030. if (targetType === 0 /* INVALID */) {
  1031. return target;
  1032. }
  1033. const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
  1034. proxyMap.set(target, proxy);
  1035. return proxy;
  1036. }
  1037. function isReactive(value) {
  1038. if (isReadonly(value)) {
  1039. return isReactive(value["__v_raw" /* RAW */]);
  1040. }
  1041. return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
  1042. }
  1043. function isReadonly(value) {
  1044. return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
  1045. }
  1046. function isProxy(value) {
  1047. return isReactive(value) || isReadonly(value);
  1048. }
  1049. function toRaw(observed) {
  1050. return ((observed && toRaw(observed["__v_raw" /* RAW */])) || observed);
  1051. }
  1052. function markRaw(value) {
  1053. def(value, "__v_skip" /* SKIP */, true);
  1054. return value;
  1055. }
  1056. const convert = (val) => isObject(val) ? reactive(val) : val;
  1057. function isRef(r) {
  1058. return Boolean(r && r.__v_isRef === true);
  1059. }
  1060. function ref(value) {
  1061. return createRef(value);
  1062. }
  1063. function shallowRef(value) {
  1064. return createRef(value, true);
  1065. }
  1066. class RefImpl {
  1067. constructor(_rawValue, _shallow = false) {
  1068. this._rawValue = _rawValue;
  1069. this._shallow = _shallow;
  1070. this.__v_isRef = true;
  1071. this._value = _shallow ? _rawValue : convert(_rawValue);
  1072. }
  1073. get value() {
  1074. track(toRaw(this), "get" /* GET */, 'value');
  1075. return this._value;
  1076. }
  1077. set value(newVal) {
  1078. if (hasChanged(toRaw(newVal), this._rawValue)) {
  1079. this._rawValue = newVal;
  1080. this._value = this._shallow ? newVal : convert(newVal);
  1081. trigger(toRaw(this), "set" /* SET */, 'value', newVal);
  1082. }
  1083. }
  1084. }
  1085. function createRef(rawValue, shallow = false) {
  1086. if (isRef(rawValue)) {
  1087. return rawValue;
  1088. }
  1089. return new RefImpl(rawValue, shallow);
  1090. }
  1091. function triggerRef(ref) {
  1092. trigger(toRaw(ref), "set" /* SET */, 'value', ref.value );
  1093. }
  1094. function unref(ref) {
  1095. return isRef(ref) ? ref.value : ref;
  1096. }
  1097. const shallowUnwrapHandlers = {
  1098. get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
  1099. set: (target, key, value, receiver) => {
  1100. const oldValue = target[key];
  1101. if (isRef(oldValue) && !isRef(value)) {
  1102. oldValue.value = value;
  1103. return true;
  1104. }
  1105. else {
  1106. return Reflect.set(target, key, value, receiver);
  1107. }
  1108. }
  1109. };
  1110. function proxyRefs(objectWithRefs) {
  1111. return isReactive(objectWithRefs)
  1112. ? objectWithRefs
  1113. : new Proxy(objectWithRefs, shallowUnwrapHandlers);
  1114. }
  1115. class CustomRefImpl {
  1116. constructor(factory) {
  1117. this.__v_isRef = true;
  1118. const { get, set } = factory(() => track(this, "get" /* GET */, 'value'), () => trigger(this, "set" /* SET */, 'value'));
  1119. this._get = get;
  1120. this._set = set;
  1121. }
  1122. get value() {
  1123. return this._get();
  1124. }
  1125. set value(newVal) {
  1126. this._set(newVal);
  1127. }
  1128. }
  1129. function customRef(factory) {
  1130. return new CustomRefImpl(factory);
  1131. }
  1132. function toRefs(object) {
  1133. if (!isProxy(object)) {
  1134. console.warn(`toRefs() expects a reactive object but received a plain one.`);
  1135. }
  1136. const ret = isArray(object) ? new Array(object.length) : {};
  1137. for (const key in object) {
  1138. ret[key] = toRef(object, key);
  1139. }
  1140. return ret;
  1141. }
  1142. class ObjectRefImpl {
  1143. constructor(_object, _key) {
  1144. this._object = _object;
  1145. this._key = _key;
  1146. this.__v_isRef = true;
  1147. }
  1148. get value() {
  1149. return this._object[this._key];
  1150. }
  1151. set value(newVal) {
  1152. this._object[this._key] = newVal;
  1153. }
  1154. }
  1155. function toRef(object, key) {
  1156. return isRef(object[key])
  1157. ? object[key]
  1158. : new ObjectRefImpl(object, key);
  1159. }
  1160. class ComputedRefImpl {
  1161. constructor(getter, _setter, isReadonly) {
  1162. this._setter = _setter;
  1163. this._dirty = true;
  1164. this.__v_isRef = true;
  1165. this.effect = effect(getter, {
  1166. lazy: true,
  1167. scheduler: () => {
  1168. if (!this._dirty) {
  1169. this._dirty = true;
  1170. trigger(toRaw(this), "set" /* SET */, 'value');
  1171. }
  1172. }
  1173. });
  1174. this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
  1175. }
  1176. get value() {
  1177. if (this._dirty) {
  1178. this._value = this.effect();
  1179. this._dirty = false;
  1180. }
  1181. track(toRaw(this), "get" /* GET */, 'value');
  1182. return this._value;
  1183. }
  1184. set value(newValue) {
  1185. this._setter(newValue);
  1186. }
  1187. }
  1188. function computed(getterOrOptions) {
  1189. let getter;
  1190. let setter;
  1191. if (isFunction(getterOrOptions)) {
  1192. getter = getterOrOptions;
  1193. setter = () => {
  1194. console.warn('Write operation failed: computed value is readonly');
  1195. }
  1196. ;
  1197. }
  1198. else {
  1199. getter = getterOrOptions.get;
  1200. setter = getterOrOptions.set;
  1201. }
  1202. return new ComputedRefImpl(getter, setter, isFunction(getterOrOptions) || !getterOrOptions.set);
  1203. }
  1204. const stack = [];
  1205. function pushWarningContext(vnode) {
  1206. stack.push(vnode);
  1207. }
  1208. function popWarningContext() {
  1209. stack.pop();
  1210. }
  1211. function warn(msg, ...args) {
  1212. // avoid props formatting or warn handler tracking deps that might be mutated
  1213. // during patch, leading to infinite recursion.
  1214. pauseTracking();
  1215. const instance = stack.length ? stack[stack.length - 1].component : null;
  1216. const appWarnHandler = instance && instance.appContext.config.warnHandler;
  1217. const trace = getComponentTrace();
  1218. if (appWarnHandler) {
  1219. callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
  1220. msg + args.join(''),
  1221. instance && instance.proxy,
  1222. trace
  1223. .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
  1224. .join('\n'),
  1225. trace
  1226. ]);
  1227. }
  1228. else {
  1229. const warnArgs = [`[Vue warn]: ${msg}`, ...args];
  1230. /* istanbul ignore if */
  1231. if (trace.length &&
  1232. // avoid spamming console during tests
  1233. !false) {
  1234. warnArgs.push(`\n`, ...formatTrace(trace));
  1235. }
  1236. console.warn(...warnArgs);
  1237. }
  1238. resetTracking();
  1239. }
  1240. function getComponentTrace() {
  1241. let currentVNode = stack[stack.length - 1];
  1242. if (!currentVNode) {
  1243. return [];
  1244. }
  1245. // we can't just use the stack because it will be incomplete during updates
  1246. // that did not start from the root. Re-construct the parent chain using
  1247. // instance parent pointers.
  1248. const normalizedStack = [];
  1249. while (currentVNode) {
  1250. const last = normalizedStack[0];
  1251. if (last && last.vnode === currentVNode) {
  1252. last.recurseCount++;
  1253. }
  1254. else {
  1255. normalizedStack.push({
  1256. vnode: currentVNode,
  1257. recurseCount: 0
  1258. });
  1259. }
  1260. const parentInstance = currentVNode.component && currentVNode.component.parent;
  1261. currentVNode = parentInstance && parentInstance.vnode;
  1262. }
  1263. return normalizedStack;
  1264. }
  1265. /* istanbul ignore next */
  1266. function formatTrace(trace) {
  1267. const logs = [];
  1268. trace.forEach((entry, i) => {
  1269. logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
  1270. });
  1271. return logs;
  1272. }
  1273. function formatTraceEntry({ vnode, recurseCount }) {
  1274. const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
  1275. const isRoot = vnode.component ? vnode.component.parent == null : false;
  1276. const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
  1277. const close = `>` + postfix;
  1278. return vnode.props
  1279. ? [open, ...formatProps(vnode.props), close]
  1280. : [open + close];
  1281. }
  1282. /* istanbul ignore next */
  1283. function formatProps(props) {
  1284. const res = [];
  1285. const keys = Object.keys(props);
  1286. keys.slice(0, 3).forEach(key => {
  1287. res.push(...formatProp(key, props[key]));
  1288. });
  1289. if (keys.length > 3) {
  1290. res.push(` ...`);
  1291. }
  1292. return res;
  1293. }
  1294. /* istanbul ignore next */
  1295. function formatProp(key, value, raw) {
  1296. if (isString(value)) {
  1297. value = JSON.stringify(value);
  1298. return raw ? value : [`${key}=${value}`];
  1299. }
  1300. else if (typeof value === 'number' ||
  1301. typeof value === 'boolean' ||
  1302. value == null) {
  1303. return raw ? value : [`${key}=${value}`];
  1304. }
  1305. else if (isRef(value)) {
  1306. value = formatProp(key, toRaw(value.value), true);
  1307. return raw ? value : [`${key}=Ref<`, value, `>`];
  1308. }
  1309. else if (isFunction(value)) {
  1310. return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
  1311. }
  1312. else {
  1313. value = toRaw(value);
  1314. return raw ? value : [`${key}=`, value];
  1315. }
  1316. }
  1317. const ErrorTypeStrings = {
  1318. ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
  1319. ["c" /* CREATED */]: 'created hook',
  1320. ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
  1321. ["m" /* MOUNTED */]: 'mounted hook',
  1322. ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
  1323. ["u" /* UPDATED */]: 'updated',
  1324. ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
  1325. ["um" /* UNMOUNTED */]: 'unmounted hook',
  1326. ["a" /* ACTIVATED */]: 'activated hook',
  1327. ["da" /* DEACTIVATED */]: 'deactivated hook',
  1328. ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
  1329. ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
  1330. ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
  1331. [0 /* SETUP_FUNCTION */]: 'setup function',
  1332. [1 /* RENDER_FUNCTION */]: 'render function',
  1333. [2 /* WATCH_GETTER */]: 'watcher getter',
  1334. [3 /* WATCH_CALLBACK */]: 'watcher callback',
  1335. [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
  1336. [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
  1337. [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
  1338. [7 /* VNODE_HOOK */]: 'vnode hook',
  1339. [8 /* DIRECTIVE_HOOK */]: 'directive hook',
  1340. [9 /* TRANSITION_HOOK */]: 'transition hook',
  1341. [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
  1342. [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
  1343. [12 /* FUNCTION_REF */]: 'ref function',
  1344. [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
  1345. [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
  1346. 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next'
  1347. };
  1348. function callWithErrorHandling(fn, instance, type, args) {
  1349. let res;
  1350. try {
  1351. res = args ? fn(...args) : fn();
  1352. }
  1353. catch (err) {
  1354. handleError(err, instance, type);
  1355. }
  1356. return res;
  1357. }
  1358. function callWithAsyncErrorHandling(fn, instance, type, args) {
  1359. if (isFunction(fn)) {
  1360. const res = callWithErrorHandling(fn, instance, type, args);
  1361. if (res && isPromise(res)) {
  1362. res.catch(err => {
  1363. handleError(err, instance, type);
  1364. });
  1365. }
  1366. return res;
  1367. }
  1368. const values = [];
  1369. for (let i = 0; i < fn.length; i++) {
  1370. values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
  1371. }
  1372. return values;
  1373. }
  1374. function handleError(err, instance, type, throwInDev = true) {
  1375. const contextVNode = instance ? instance.vnode : null;
  1376. if (instance) {
  1377. let cur = instance.parent;
  1378. // the exposed instance is the render proxy to keep it consistent with 2.x
  1379. const exposedInstance = instance.proxy;
  1380. // in production the hook receives only the error code
  1381. const errorInfo = ErrorTypeStrings[type] ;
  1382. while (cur) {
  1383. const errorCapturedHooks = cur.ec;
  1384. if (errorCapturedHooks) {
  1385. for (let i = 0; i < errorCapturedHooks.length; i++) {
  1386. if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
  1387. return;
  1388. }
  1389. }
  1390. }
  1391. cur = cur.parent;
  1392. }
  1393. // app-level handling
  1394. const appErrorHandler = instance.appContext.config.errorHandler;
  1395. if (appErrorHandler) {
  1396. callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
  1397. return;
  1398. }
  1399. }
  1400. logError(err, type, contextVNode, throwInDev);
  1401. }
  1402. function logError(err, type, contextVNode, throwInDev = true) {
  1403. {
  1404. const info = ErrorTypeStrings[type];
  1405. if (contextVNode) {
  1406. pushWarningContext(contextVNode);
  1407. }
  1408. warn(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
  1409. if (contextVNode) {
  1410. popWarningContext();
  1411. }
  1412. // crash in dev by default so it's more noticeable
  1413. if (throwInDev) {
  1414. throw err;
  1415. }
  1416. else {
  1417. console.error(err);
  1418. }
  1419. }
  1420. }
  1421. let isFlushing = false;
  1422. let isFlushPending = false;
  1423. const queue = [];
  1424. let flushIndex = 0;
  1425. const pendingPreFlushCbs = [];
  1426. let activePreFlushCbs = null;
  1427. let preFlushIndex = 0;
  1428. const pendingPostFlushCbs = [];
  1429. let activePostFlushCbs = null;
  1430. let postFlushIndex = 0;
  1431. const resolvedPromise = Promise.resolve();
  1432. let currentFlushPromise = null;
  1433. let currentPreFlushParentJob = null;
  1434. const RECURSION_LIMIT = 100;
  1435. function nextTick(fn) {
  1436. const p = currentFlushPromise || resolvedPromise;
  1437. return fn ? p.then(this ? fn.bind(this) : fn) : p;
  1438. }
  1439. function queueJob(job) {
  1440. // the dedupe search uses the startIndex argument of Array.includes()
  1441. // by default the search index includes the current job that is being run
  1442. // so it cannot recursively trigger itself again.
  1443. // if the job is a watch() callback, the search will start with a +1 index to
  1444. // allow it recursively trigger itself - it is the user's responsibility to
  1445. // ensure it doesn't end up in an infinite loop.
  1446. if ((!queue.length ||
  1447. !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
  1448. job !== currentPreFlushParentJob) {
  1449. queue.push(job);
  1450. queueFlush();
  1451. }
  1452. }
  1453. function queueFlush() {
  1454. if (!isFlushing && !isFlushPending) {
  1455. isFlushPending = true;
  1456. currentFlushPromise = resolvedPromise.then(flushJobs);
  1457. }
  1458. }
  1459. function invalidateJob(job) {
  1460. const i = queue.indexOf(job);
  1461. if (i > -1) {
  1462. queue.splice(i, 1);
  1463. }
  1464. }
  1465. function queueCb(cb, activeQueue, pendingQueue, index) {
  1466. if (!isArray(cb)) {
  1467. if (!activeQueue ||
  1468. !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
  1469. pendingQueue.push(cb);
  1470. }
  1471. }
  1472. else {
  1473. // if cb is an array, it is a component lifecycle hook which can only be
  1474. // triggered by a job, which is already deduped in the main queue, so
  1475. // we can skip duplicate check here to improve perf
  1476. pendingQueue.push(...cb);
  1477. }
  1478. queueFlush();
  1479. }
  1480. function queuePreFlushCb(cb) {
  1481. queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
  1482. }
  1483. function queuePostFlushCb(cb) {
  1484. queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
  1485. }
  1486. function flushPreFlushCbs(seen, parentJob = null) {
  1487. if (pendingPreFlushCbs.length) {
  1488. currentPreFlushParentJob = parentJob;
  1489. activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
  1490. pendingPreFlushCbs.length = 0;
  1491. {
  1492. seen = seen || new Map();
  1493. }
  1494. for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
  1495. {
  1496. checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex]);
  1497. }
  1498. activePreFlushCbs[preFlushIndex]();
  1499. }
  1500. activePreFlushCbs = null;
  1501. preFlushIndex = 0;
  1502. currentPreFlushParentJob = null;
  1503. // recursively flush until it drains
  1504. flushPreFlushCbs(seen, parentJob);
  1505. }
  1506. }
  1507. function flushPostFlushCbs(seen) {
  1508. if (pendingPostFlushCbs.length) {
  1509. const deduped = [...new Set(pendingPostFlushCbs)];
  1510. pendingPostFlushCbs.length = 0;
  1511. // #1947 already has active queue, nested flushPostFlushCbs call
  1512. if (activePostFlushCbs) {
  1513. activePostFlushCbs.push(...deduped);
  1514. return;
  1515. }
  1516. activePostFlushCbs = deduped;
  1517. {
  1518. seen = seen || new Map();
  1519. }
  1520. activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
  1521. for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
  1522. {
  1523. checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex]);
  1524. }
  1525. activePostFlushCbs[postFlushIndex]();
  1526. }
  1527. activePostFlushCbs = null;
  1528. postFlushIndex = 0;
  1529. }
  1530. }
  1531. const getId = (job) => job.id == null ? Infinity : job.id;
  1532. function flushJobs(seen) {
  1533. isFlushPending = false;
  1534. isFlushing = true;
  1535. {
  1536. seen = seen || new Map();
  1537. }
  1538. flushPreFlushCbs(seen);
  1539. // Sort queue before flush.
  1540. // This ensures that:
  1541. // 1. Components are updated from parent to child. (because parent is always
  1542. // created before the child so its render effect will have smaller
  1543. // priority number)
  1544. // 2. If a component is unmounted during a parent component's update,
  1545. // its update can be skipped.
  1546. queue.sort((a, b) => getId(a) - getId(b));
  1547. try {
  1548. for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
  1549. const job = queue[flushIndex];
  1550. if (job) {
  1551. if (true) {
  1552. checkRecursiveUpdates(seen, job);
  1553. }
  1554. callWithErrorHandling(job, null, 14 /* SCHEDULER */);
  1555. }
  1556. }
  1557. }
  1558. finally {
  1559. flushIndex = 0;
  1560. queue.length = 0;
  1561. flushPostFlushCbs(seen);
  1562. isFlushing = false;
  1563. currentFlushPromise = null;
  1564. // some postFlushCb queued jobs!
  1565. // keep flushing until it drains.
  1566. if (queue.length || pendingPostFlushCbs.length) {
  1567. flushJobs(seen);
  1568. }
  1569. }
  1570. }
  1571. function checkRecursiveUpdates(seen, fn) {
  1572. if (!seen.has(fn)) {
  1573. seen.set(fn, 1);
  1574. }
  1575. else {
  1576. const count = seen.get(fn);
  1577. if (count > RECURSION_LIMIT) {
  1578. throw new Error(`Maximum recursive updates exceeded. ` +
  1579. `This means you have a reactive effect that is mutating its own ` +
  1580. `dependencies and thus recursively triggering itself. Possible sources ` +
  1581. `include component template, render function, updated hook or ` +
  1582. `watcher source function.`);
  1583. }
  1584. else {
  1585. seen.set(fn, count + 1);
  1586. }
  1587. }
  1588. }
  1589. /* eslint-disable no-restricted-globals */
  1590. let isHmrUpdating = false;
  1591. const hmrDirtyComponents = new Set();
  1592. // Expose the HMR runtime on the global object
  1593. // This makes it entirely tree-shakable without polluting the exports and makes
  1594. // it easier to be used in toolings like vue-loader
  1595. // Note: for a component to be eligible for HMR it also needs the __hmrId option
  1596. // to be set so that its instances can be registered / removed.
  1597. {
  1598. const globalObject = typeof global !== 'undefined'
  1599. ? global
  1600. : typeof self !== 'undefined'
  1601. ? self
  1602. : typeof window !== 'undefined'
  1603. ? window
  1604. : {};
  1605. globalObject.__VUE_HMR_RUNTIME__ = {
  1606. createRecord: tryWrap(createRecord),
  1607. rerender: tryWrap(rerender),
  1608. reload: tryWrap(reload)
  1609. };
  1610. }
  1611. const map = new Map();
  1612. function registerHMR(instance) {
  1613. const id = instance.type.__hmrId;
  1614. let record = map.get(id);
  1615. if (!record) {
  1616. createRecord(id, instance.type);
  1617. record = map.get(id);
  1618. }
  1619. record.instances.add(instance);
  1620. }
  1621. function unregisterHMR(instance) {
  1622. map.get(instance.type.__hmrId).instances.delete(instance);
  1623. }
  1624. function createRecord(id, component) {
  1625. if (!component) {
  1626. warn(`HMR API usage is out of date.\n` +
  1627. `Please upgrade vue-loader/vite/rollup-plugin-vue or other relevant ` +
  1628. `dependency that handles Vue SFC compilation.`);
  1629. component = {};
  1630. }
  1631. if (map.has(id)) {
  1632. return false;
  1633. }
  1634. map.set(id, {
  1635. component: isClassComponent(component) ? component.__vccOpts : component,
  1636. instances: new Set()
  1637. });
  1638. return true;
  1639. }
  1640. function rerender(id, newRender) {
  1641. const record = map.get(id);
  1642. if (!record)
  1643. return;
  1644. if (newRender)
  1645. record.component.render = newRender;
  1646. // Array.from creates a snapshot which avoids the set being mutated during
  1647. // updates
  1648. Array.from(record.instances).forEach(instance => {
  1649. if (newRender) {
  1650. instance.render = newRender;
  1651. }
  1652. instance.renderCache = [];
  1653. // this flag forces child components with slot content to update
  1654. isHmrUpdating = true;
  1655. instance.update();
  1656. isHmrUpdating = false;
  1657. });
  1658. }
  1659. function reload(id, newComp) {
  1660. const record = map.get(id);
  1661. if (!record)
  1662. return;
  1663. // Array.from creates a snapshot which avoids the set being mutated during
  1664. // updates
  1665. const { component, instances } = record;
  1666. if (!hmrDirtyComponents.has(component)) {
  1667. // 1. Update existing comp definition to match new one
  1668. newComp = isClassComponent(newComp) ? newComp.__vccOpts : newComp;
  1669. extend(component, newComp);
  1670. for (const key in component) {
  1671. if (!(key in newComp)) {
  1672. delete component[key];
  1673. }
  1674. }
  1675. // 2. Mark component dirty. This forces the renderer to replace the component
  1676. // on patch.
  1677. hmrDirtyComponents.add(component);
  1678. // 3. Make sure to unmark the component after the reload.
  1679. queuePostFlushCb(() => {
  1680. hmrDirtyComponents.delete(component);
  1681. });
  1682. }
  1683. Array.from(instances).forEach(instance => {
  1684. if (instance.parent) {
  1685. // 4. Force the parent instance to re-render. This will cause all updated
  1686. // components to be unmounted and re-mounted. Queue the update so that we
  1687. // don't end up forcing the same parent to re-render multiple times.
  1688. queueJob(instance.parent.update);
  1689. }
  1690. else if (instance.appContext.reload) {
  1691. // root instance mounted via createApp() has a reload method
  1692. instance.appContext.reload();
  1693. }
  1694. else if (typeof window !== 'undefined') {
  1695. // root instance inside tree created via raw render(). Force reload.
  1696. window.location.reload();
  1697. }
  1698. else {
  1699. console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
  1700. }
  1701. });
  1702. }
  1703. function tryWrap(fn) {
  1704. return (id, arg) => {
  1705. try {
  1706. return fn(id, arg);
  1707. }
  1708. catch (e) {
  1709. console.error(e);
  1710. console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
  1711. `Full reload required.`);
  1712. }
  1713. };
  1714. }
  1715. exports.devtools = void 0;
  1716. function setDevtoolsHook(hook) {
  1717. exports.devtools = hook;
  1718. }
  1719. function devtoolsInitApp(app, version) {
  1720. // TODO queue if devtools is undefined
  1721. if (!exports.devtools)
  1722. return;
  1723. exports.devtools.emit("app:init" /* APP_INIT */, app, version, {
  1724. Fragment,
  1725. Text,
  1726. Comment,
  1727. Static
  1728. });
  1729. }
  1730. function devtoolsUnmountApp(app) {
  1731. if (!exports.devtools)
  1732. return;
  1733. exports.devtools.emit("app:unmount" /* APP_UNMOUNT */, app);
  1734. }
  1735. const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
  1736. const devtoolsComponentUpdated = /*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
  1737. const devtoolsComponentRemoved = /*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
  1738. function createDevtoolsComponentHook(hook) {
  1739. return (component) => {
  1740. if (!exports.devtools)
  1741. return;
  1742. exports.devtools.emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
  1743. };
  1744. }
  1745. function devtoolsComponentEmit(component, event, params) {
  1746. if (!exports.devtools)
  1747. return;
  1748. exports.devtools.emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
  1749. }
  1750. function emit(instance, event, ...rawArgs) {
  1751. const props = instance.vnode.props || EMPTY_OBJ;
  1752. {
  1753. const { emitsOptions, propsOptions: [propsOptions] } = instance;
  1754. if (emitsOptions) {
  1755. if (!(event in emitsOptions)) {
  1756. if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
  1757. warn(`Component emitted event "${event}" but it is neither declared in ` +
  1758. `the emits option nor as an "${toHandlerKey(event)}" prop.`);
  1759. }
  1760. }
  1761. else {
  1762. const validator = emitsOptions[event];
  1763. if (isFunction(validator)) {
  1764. const isValid = validator(...rawArgs);
  1765. if (!isValid) {
  1766. warn(`Invalid event arguments: event validation failed for event "${event}".`);
  1767. }
  1768. }
  1769. }
  1770. }
  1771. }
  1772. let args = rawArgs;
  1773. const isModelListener = event.startsWith('update:');
  1774. // for v-model update:xxx events, apply modifiers on args
  1775. const modelArg = isModelListener && event.slice(7);
  1776. if (modelArg && modelArg in props) {
  1777. const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
  1778. const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
  1779. if (trim) {
  1780. args = rawArgs.map(a => a.trim());
  1781. }
  1782. else if (number) {
  1783. args = rawArgs.map(toNumber);
  1784. }
  1785. }
  1786. {
  1787. devtoolsComponentEmit(instance, event, args);
  1788. }
  1789. {
  1790. const lowerCaseEvent = event.toLowerCase();
  1791. if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
  1792. warn(`Event "${lowerCaseEvent}" is emitted in component ` +
  1793. `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
  1794. `Note that HTML attributes are case-insensitive and you cannot use ` +
  1795. `v-on to listen to camelCase events when using in-DOM templates. ` +
  1796. `You should probably use "${hyphenate(event)}" instead of "${event}".`);
  1797. }
  1798. }
  1799. // convert handler name to camelCase. See issue #2249
  1800. let handlerName = toHandlerKey(camelize(event));
  1801. let handler = props[handlerName];
  1802. // for v-model update:xxx events, also trigger kebab-case equivalent
  1803. // for props passed via kebab-case
  1804. if (!handler && isModelListener) {
  1805. handlerName = toHandlerKey(hyphenate(event));
  1806. handler = props[handlerName];
  1807. }
  1808. if (handler) {
  1809. callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
  1810. }
  1811. const onceHandler = props[handlerName + `Once`];
  1812. if (onceHandler) {
  1813. if (!instance.emitted) {
  1814. (instance.emitted = {})[handlerName] = true;
  1815. }
  1816. else if (instance.emitted[handlerName]) {
  1817. return;
  1818. }
  1819. callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
  1820. }
  1821. }
  1822. function normalizeEmitsOptions(comp, appContext, asMixin = false) {
  1823. if (!appContext.deopt && comp.__emits !== undefined) {
  1824. return comp.__emits;
  1825. }
  1826. const raw = comp.emits;
  1827. let normalized = {};
  1828. // apply mixin/extends props
  1829. let hasExtends = false;
  1830. if (!isFunction(comp)) {
  1831. const extendEmits = (raw) => {
  1832. hasExtends = true;
  1833. extend(normalized, normalizeEmitsOptions(raw, appContext, true));
  1834. };
  1835. if (!asMixin && appContext.mixins.length) {
  1836. appContext.mixins.forEach(extendEmits);
  1837. }
  1838. if (comp.extends) {
  1839. extendEmits(comp.extends);
  1840. }
  1841. if (comp.mixins) {
  1842. comp.mixins.forEach(extendEmits);
  1843. }
  1844. }
  1845. if (!raw && !hasExtends) {
  1846. return (comp.__emits = null);
  1847. }
  1848. if (isArray(raw)) {
  1849. raw.forEach(key => (normalized[key] = null));
  1850. }
  1851. else {
  1852. extend(normalized, raw);
  1853. }
  1854. return (comp.__emits = normalized);
  1855. }
  1856. // Check if an incoming prop key is a declared emit event listener.
  1857. // e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
  1858. // both considered matched listeners.
  1859. function isEmitListener(options, key) {
  1860. if (!options || !isOn(key)) {
  1861. return false;
  1862. }
  1863. key = key.slice(2).replace(/Once$/, '');
  1864. return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
  1865. hasOwn(options, hyphenate(key)) ||
  1866. hasOwn(options, key));
  1867. }
  1868. /**
  1869. * mark the current rendering instance for asset resolution (e.g.
  1870. * resolveComponent, resolveDirective) during render
  1871. */
  1872. let currentRenderingInstance = null;
  1873. function setCurrentRenderingInstance(instance) {
  1874. currentRenderingInstance = instance;
  1875. }
  1876. /**
  1877. * dev only flag to track whether $attrs was used during render.
  1878. * If $attrs was used during render then the warning for failed attrs
  1879. * fallthrough can be suppressed.
  1880. */
  1881. let accessedAttrs = false;
  1882. function markAttrsAccessed() {
  1883. accessedAttrs = true;
  1884. }
  1885. function renderComponentRoot(instance) {
  1886. const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx } = instance;
  1887. let result;
  1888. currentRenderingInstance = instance;
  1889. {
  1890. accessedAttrs = false;
  1891. }
  1892. try {
  1893. let fallthroughAttrs;
  1894. if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
  1895. // withProxy is a proxy with a different `has` trap only for
  1896. // runtime-compiled render functions using `with` block.
  1897. const proxyToUse = withProxy || proxy;
  1898. result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
  1899. fallthroughAttrs = attrs;
  1900. }
  1901. else {
  1902. // functional
  1903. const render = Component;
  1904. // in dev, mark attrs accessed if optional props (attrs === props)
  1905. if (true && attrs === props) {
  1906. markAttrsAccessed();
  1907. }
  1908. result = normalizeVNode(render.length > 1
  1909. ? render(props, true
  1910. ? {
  1911. get attrs() {
  1912. markAttrsAccessed();
  1913. return attrs;
  1914. },
  1915. slots,
  1916. emit
  1917. }
  1918. : { attrs, slots, emit })
  1919. : render(props, null /* we know it doesn't need it */));
  1920. fallthroughAttrs = Component.props
  1921. ? attrs
  1922. : getFunctionalFallthrough(attrs);
  1923. }
  1924. // attr merging
  1925. // in dev mode, comments are preserved, and it's possible for a template
  1926. // to have comments along side the root element which makes it a fragment
  1927. let root = result;
  1928. let setRoot = undefined;
  1929. if (true &&
  1930. result.patchFlag > 0 &&
  1931. result.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
  1932. ;
  1933. [root, setRoot] = getChildRoot(result);
  1934. }
  1935. if (Component.inheritAttrs !== false && fallthroughAttrs) {
  1936. const keys = Object.keys(fallthroughAttrs);
  1937. const { shapeFlag } = root;
  1938. if (keys.length) {
  1939. if (shapeFlag & 1 /* ELEMENT */ ||
  1940. shapeFlag & 6 /* COMPONENT */) {
  1941. if (propsOptions && keys.some(isModelListener)) {
  1942. // If a v-model listener (onUpdate:xxx) has a corresponding declared
  1943. // prop, it indicates this component expects to handle v-model and
  1944. // it should not fallthrough.
  1945. // related: #1543, #1643, #1989
  1946. fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
  1947. }
  1948. root = cloneVNode(root, fallthroughAttrs);
  1949. }
  1950. else if (true && !accessedAttrs && root.type !== Comment) {
  1951. const allAttrs = Object.keys(attrs);
  1952. const eventAttrs = [];
  1953. const extraAttrs = [];
  1954. for (let i = 0, l = allAttrs.length; i < l; i++) {
  1955. const key = allAttrs[i];
  1956. if (isOn(key)) {
  1957. // ignore v-model handlers when they fail to fallthrough
  1958. if (!isModelListener(key)) {
  1959. // remove `on`, lowercase first letter to reflect event casing
  1960. // accurately
  1961. eventAttrs.push(key[2].toLowerCase() + key.slice(3));
  1962. }
  1963. }
  1964. else {
  1965. extraAttrs.push(key);
  1966. }
  1967. }
  1968. if (extraAttrs.length) {
  1969. warn(`Extraneous non-props attributes (` +
  1970. `${extraAttrs.join(', ')}) ` +
  1971. `were passed to component but could not be automatically inherited ` +
  1972. `because component renders fragment or text root nodes.`);
  1973. }
  1974. if (eventAttrs.length) {
  1975. warn(`Extraneous non-emits event listeners (` +
  1976. `${eventAttrs.join(', ')}) ` +
  1977. `were passed to component but could not be automatically inherited ` +
  1978. `because component renders fragment or text root nodes. ` +
  1979. `If the listener is intended to be a component custom event listener only, ` +
  1980. `declare it using the "emits" option.`);
  1981. }
  1982. }
  1983. }
  1984. }
  1985. // inherit directives
  1986. if (vnode.dirs) {
  1987. if (true && !isElementRoot(root)) {
  1988. warn(`Runtime directive used on component with non-element root node. ` +
  1989. `The directives will not function as intended.`);
  1990. }
  1991. root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
  1992. }
  1993. // inherit transition data
  1994. if (vnode.transition) {
  1995. if (true && !isElementRoot(root)) {
  1996. warn(`Component inside <Transition> renders non-element root node ` +
  1997. `that cannot be animated.`);
  1998. }
  1999. root.transition = vnode.transition;
  2000. }
  2001. if (true && setRoot) {
  2002. setRoot(root);
  2003. }
  2004. else {
  2005. result = root;
  2006. }
  2007. }
  2008. catch (err) {
  2009. handleError(err, instance, 1 /* RENDER_FUNCTION */);
  2010. result = createVNode(Comment);
  2011. }
  2012. currentRenderingInstance = null;
  2013. return result;
  2014. }
  2015. /**
  2016. * dev only
  2017. * In dev mode, template root level comments are rendered, which turns the
  2018. * template into a fragment root, but we need to locate the single element
  2019. * root for attrs and scope id processing.
  2020. */
  2021. const getChildRoot = (vnode) => {
  2022. const rawChildren = vnode.children;
  2023. const dynamicChildren = vnode.dynamicChildren;
  2024. const childRoot = filterSingleRoot(rawChildren);
  2025. if (!childRoot) {
  2026. return [vnode, undefined];
  2027. }
  2028. const index = rawChildren.indexOf(childRoot);
  2029. const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
  2030. const setRoot = (updatedRoot) => {
  2031. rawChildren[index] = updatedRoot;
  2032. if (dynamicChildren) {
  2033. if (dynamicIndex > -1) {
  2034. dynamicChildren[dynamicIndex] = updatedRoot;
  2035. }
  2036. else if (updatedRoot.patchFlag > 0) {
  2037. vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
  2038. }
  2039. }
  2040. };
  2041. return [normalizeVNode(childRoot), setRoot];
  2042. };
  2043. function filterSingleRoot(children) {
  2044. let singleRoot;
  2045. for (let i = 0; i < children.length; i++) {
  2046. const child = children[i];
  2047. if (isVNode(child)) {
  2048. // ignore user comment
  2049. if (child.type !== Comment || child.children === 'v-if') {
  2050. if (singleRoot) {
  2051. // has more than 1 non-comment child, return now
  2052. return;
  2053. }
  2054. else {
  2055. singleRoot = child;
  2056. }
  2057. }
  2058. }
  2059. else {
  2060. return;
  2061. }
  2062. }
  2063. return singleRoot;
  2064. }
  2065. const getFunctionalFallthrough = (attrs) => {
  2066. let res;
  2067. for (const key in attrs) {
  2068. if (key === 'class' || key === 'style' || isOn(key)) {
  2069. (res || (res = {}))[key] = attrs[key];
  2070. }
  2071. }
  2072. return res;
  2073. };
  2074. const filterModelListeners = (attrs, props) => {
  2075. const res = {};
  2076. for (const key in attrs) {
  2077. if (!isModelListener(key) || !(key.slice(9) in props)) {
  2078. res[key] = attrs[key];
  2079. }
  2080. }
  2081. return res;
  2082. };
  2083. const isElementRoot = (vnode) => {
  2084. return (vnode.shapeFlag & 6 /* COMPONENT */ ||
  2085. vnode.shapeFlag & 1 /* ELEMENT */ ||
  2086. vnode.type === Comment // potential v-if branch switch
  2087. );
  2088. };
  2089. function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
  2090. const { props: prevProps, children: prevChildren, component } = prevVNode;
  2091. const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
  2092. const emits = component.emitsOptions;
  2093. // Parent component's render function was hot-updated. Since this may have
  2094. // caused the child component's slots content to have changed, we need to
  2095. // force the child to update as well.
  2096. if ((prevChildren || nextChildren) && isHmrUpdating) {
  2097. return true;
  2098. }
  2099. // force child update for runtime directive or transition on component vnode.
  2100. if (nextVNode.dirs || nextVNode.transition) {
  2101. return true;
  2102. }
  2103. if (optimized && patchFlag >= 0) {
  2104. if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
  2105. // slot content that references values that might have changed,
  2106. // e.g. in a v-for
  2107. return true;
  2108. }
  2109. if (patchFlag & 16 /* FULL_PROPS */) {
  2110. if (!prevProps) {
  2111. return !!nextProps;
  2112. }
  2113. // presence of this flag indicates props are always non-null
  2114. return hasPropsChanged(prevProps, nextProps, emits);
  2115. }
  2116. else if (patchFlag & 8 /* PROPS */) {
  2117. const dynamicProps = nextVNode.dynamicProps;
  2118. for (let i = 0; i < dynamicProps.length; i++) {
  2119. const key = dynamicProps[i];
  2120. if (nextProps[key] !== prevProps[key] &&
  2121. !isEmitListener(emits, key)) {
  2122. return true;
  2123. }
  2124. }
  2125. }
  2126. }
  2127. else {
  2128. // this path is only taken by manually written render functions
  2129. // so presence of any children leads to a forced update
  2130. if (prevChildren || nextChildren) {
  2131. if (!nextChildren || !nextChildren.$stable) {
  2132. return true;
  2133. }
  2134. }
  2135. if (prevProps === nextProps) {
  2136. return false;
  2137. }
  2138. if (!prevProps) {
  2139. return !!nextProps;
  2140. }
  2141. if (!nextProps) {
  2142. return true;
  2143. }
  2144. return hasPropsChanged(prevProps, nextProps, emits);
  2145. }
  2146. return false;
  2147. }
  2148. function hasPropsChanged(prevProps, nextProps, emitsOptions) {
  2149. const nextKeys = Object.keys(nextProps);
  2150. if (nextKeys.length !== Object.keys(prevProps).length) {
  2151. return true;
  2152. }
  2153. for (let i = 0; i < nextKeys.length; i++) {
  2154. const key = nextKeys[i];
  2155. if (nextProps[key] !== prevProps[key] &&
  2156. !isEmitListener(emitsOptions, key)) {
  2157. return true;
  2158. }
  2159. }
  2160. return false;
  2161. }
  2162. function updateHOCHostEl({ vnode, parent }, el // HostNode
  2163. ) {
  2164. while (parent && parent.subTree === vnode) {
  2165. (vnode = parent.vnode).el = el;
  2166. parent = parent.parent;
  2167. }
  2168. }
  2169. const isSuspense = (type) => type.__isSuspense;
  2170. // Suspense exposes a component-like API, and is treated like a component
  2171. // in the compiler, but internally it's a special built-in type that hooks
  2172. // directly into the renderer.
  2173. const SuspenseImpl = {
  2174. // In order to make Suspense tree-shakable, we need to avoid importing it
  2175. // directly in the renderer. The renderer checks for the __isSuspense flag
  2176. // on a vnode's type and calls the `process` method, passing in renderer
  2177. // internals.
  2178. __isSuspense: true,
  2179. process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized,
  2180. // platform-specific impl passed from renderer
  2181. rendererInternals) {
  2182. if (n1 == null) {
  2183. mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, rendererInternals);
  2184. }
  2185. else {
  2186. patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, rendererInternals);
  2187. }
  2188. },
  2189. hydrate: hydrateSuspense,
  2190. create: createSuspenseBoundary
  2191. };
  2192. // Force-casted public typing for h and TSX props inference
  2193. const Suspense = (SuspenseImpl
  2194. );
  2195. function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, optimized, rendererInternals) {
  2196. const { p: patch, o: { createElement } } = rendererInternals;
  2197. const hiddenContainer = createElement('div');
  2198. const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, optimized, rendererInternals));
  2199. // start mounting the content subtree in an off-dom container
  2200. patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG);
  2201. // now check if we have encountered any async deps
  2202. if (suspense.deps > 0) {
  2203. // has async
  2204. // mount the fallback tree
  2205. patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2206. isSVG);
  2207. setActiveBranch(suspense, vnode.ssFallback);
  2208. }
  2209. else {
  2210. // Suspense has no async deps. Just resolve.
  2211. suspense.resolve();
  2212. }
  2213. }
  2214. function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, { p: patch, um: unmount, o: { createElement } }) {
  2215. const suspense = (n2.suspense = n1.suspense);
  2216. suspense.vnode = n2;
  2217. n2.el = n1.el;
  2218. const newBranch = n2.ssContent;
  2219. const newFallback = n2.ssFallback;
  2220. const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
  2221. if (pendingBranch) {
  2222. suspense.pendingBranch = newBranch;
  2223. if (isSameVNodeType(newBranch, pendingBranch)) {
  2224. // same root type but content may have changed.
  2225. patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG);
  2226. if (suspense.deps <= 0) {
  2227. suspense.resolve();
  2228. }
  2229. else if (isInFallback) {
  2230. patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2231. isSVG);
  2232. setActiveBranch(suspense, newFallback);
  2233. }
  2234. }
  2235. else {
  2236. // toggled before pending tree is resolved
  2237. suspense.pendingId++;
  2238. if (isHydrating) {
  2239. // if toggled before hydration is finished, the current DOM tree is
  2240. // no longer valid. set it as the active branch so it will be unmounted
  2241. // when resolved
  2242. suspense.isHydrating = false;
  2243. suspense.activeBranch = pendingBranch;
  2244. }
  2245. else {
  2246. unmount(pendingBranch, parentComponent, suspense);
  2247. }
  2248. // increment pending ID. this is used to invalidate async callbacks
  2249. // reset suspense state
  2250. suspense.deps = 0;
  2251. // discard effects from pending branch
  2252. suspense.effects.length = 0;
  2253. // discard previous container
  2254. suspense.hiddenContainer = createElement('div');
  2255. if (isInFallback) {
  2256. // already in fallback state
  2257. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG);
  2258. if (suspense.deps <= 0) {
  2259. suspense.resolve();
  2260. }
  2261. else {
  2262. patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2263. isSVG);
  2264. setActiveBranch(suspense, newFallback);
  2265. }
  2266. }
  2267. else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
  2268. // toggled "back" to current active branch
  2269. patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG);
  2270. // force resolve
  2271. suspense.resolve(true);
  2272. }
  2273. else {
  2274. // switched to a 3rd branch
  2275. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG);
  2276. if (suspense.deps <= 0) {
  2277. suspense.resolve();
  2278. }
  2279. }
  2280. }
  2281. }
  2282. else {
  2283. if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
  2284. // root did not change, just normal patch
  2285. patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG);
  2286. setActiveBranch(suspense, newBranch);
  2287. }
  2288. else {
  2289. // root node toggled
  2290. // invoke @pending event
  2291. const onPending = n2.props && n2.props.onPending;
  2292. if (isFunction(onPending)) {
  2293. onPending();
  2294. }
  2295. // mount pending branch in off-dom container
  2296. suspense.pendingBranch = newBranch;
  2297. suspense.pendingId++;
  2298. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG);
  2299. if (suspense.deps <= 0) {
  2300. // incoming branch has no async deps, resolve now.
  2301. suspense.resolve();
  2302. }
  2303. else {
  2304. const { timeout, pendingId } = suspense;
  2305. if (timeout > 0) {
  2306. setTimeout(() => {
  2307. if (suspense.pendingId === pendingId) {
  2308. suspense.fallback(newFallback);
  2309. }
  2310. }, timeout);
  2311. }
  2312. else if (timeout === 0) {
  2313. suspense.fallback(newFallback);
  2314. }
  2315. }
  2316. }
  2317. }
  2318. }
  2319. let hasWarned = false;
  2320. function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, optimized, rendererInternals, isHydrating = false) {
  2321. /* istanbul ignore if */
  2322. if (!hasWarned) {
  2323. hasWarned = true;
  2324. // @ts-ignore `console.info` cannot be null error
  2325. console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
  2326. }
  2327. const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
  2328. const timeout = toNumber(vnode.props && vnode.props.timeout);
  2329. const suspense = {
  2330. vnode,
  2331. parent,
  2332. parentComponent,
  2333. isSVG,
  2334. container,
  2335. hiddenContainer,
  2336. anchor,
  2337. deps: 0,
  2338. pendingId: 0,
  2339. timeout: typeof timeout === 'number' ? timeout : -1,
  2340. activeBranch: null,
  2341. pendingBranch: null,
  2342. isInFallback: true,
  2343. isHydrating,
  2344. isUnmounted: false,
  2345. effects: [],
  2346. resolve(resume = false) {
  2347. {
  2348. if (!resume && !suspense.pendingBranch) {
  2349. throw new Error(`suspense.resolve() is called without a pending branch.`);
  2350. }
  2351. if (suspense.isUnmounted) {
  2352. throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
  2353. }
  2354. }
  2355. const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
  2356. if (suspense.isHydrating) {
  2357. suspense.isHydrating = false;
  2358. }
  2359. else if (!resume) {
  2360. const delayEnter = activeBranch &&
  2361. pendingBranch.transition &&
  2362. pendingBranch.transition.mode === 'out-in';
  2363. if (delayEnter) {
  2364. activeBranch.transition.afterLeave = () => {
  2365. if (pendingId === suspense.pendingId) {
  2366. move(pendingBranch, container, anchor, 0 /* ENTER */);
  2367. }
  2368. };
  2369. }
  2370. // this is initial anchor on mount
  2371. let { anchor } = suspense;
  2372. // unmount current active tree
  2373. if (activeBranch) {
  2374. // if the fallback tree was mounted, it may have been moved
  2375. // as part of a parent suspense. get the latest anchor for insertion
  2376. anchor = next(activeBranch);
  2377. unmount(activeBranch, parentComponent, suspense, true);
  2378. }
  2379. if (!delayEnter) {
  2380. // move content from off-dom container to actual container
  2381. move(pendingBranch, container, anchor, 0 /* ENTER */);
  2382. }
  2383. }
  2384. setActiveBranch(suspense, pendingBranch);
  2385. suspense.pendingBranch = null;
  2386. suspense.isInFallback = false;
  2387. // flush buffered effects
  2388. // check if there is a pending parent suspense
  2389. let parent = suspense.parent;
  2390. let hasUnresolvedAncestor = false;
  2391. while (parent) {
  2392. if (parent.pendingBranch) {
  2393. // found a pending parent suspense, merge buffered post jobs
  2394. // into that parent
  2395. parent.effects.push(...effects);
  2396. hasUnresolvedAncestor = true;
  2397. break;
  2398. }
  2399. parent = parent.parent;
  2400. }
  2401. // no pending parent suspense, flush all jobs
  2402. if (!hasUnresolvedAncestor) {
  2403. queuePostFlushCb(effects);
  2404. }
  2405. suspense.effects = [];
  2406. // invoke @resolve event
  2407. const onResolve = vnode.props && vnode.props.onResolve;
  2408. if (isFunction(onResolve)) {
  2409. onResolve();
  2410. }
  2411. },
  2412. fallback(fallbackVNode) {
  2413. if (!suspense.pendingBranch) {
  2414. return;
  2415. }
  2416. const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
  2417. // invoke @fallback event
  2418. const onFallback = vnode.props && vnode.props.onFallback;
  2419. if (isFunction(onFallback)) {
  2420. onFallback();
  2421. }
  2422. const anchor = next(activeBranch);
  2423. const mountFallback = () => {
  2424. if (!suspense.isInFallback) {
  2425. return;
  2426. }
  2427. // mount the fallback tree
  2428. patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2429. isSVG);
  2430. setActiveBranch(suspense, fallbackVNode);
  2431. };
  2432. const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
  2433. if (delayEnter) {
  2434. activeBranch.transition.afterLeave = mountFallback;
  2435. }
  2436. // unmount current active branch
  2437. unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
  2438. true // shouldRemove
  2439. );
  2440. suspense.isInFallback = true;
  2441. if (!delayEnter) {
  2442. mountFallback();
  2443. }
  2444. },
  2445. move(container, anchor, type) {
  2446. suspense.activeBranch &&
  2447. move(suspense.activeBranch, container, anchor, type);
  2448. suspense.container = container;
  2449. },
  2450. next() {
  2451. return suspense.activeBranch && next(suspense.activeBranch);
  2452. },
  2453. registerDep(instance, setupRenderEffect) {
  2454. const isInPendingSuspense = !!suspense.pendingBranch;
  2455. if (isInPendingSuspense) {
  2456. suspense.deps++;
  2457. }
  2458. const hydratedEl = instance.vnode.el;
  2459. instance
  2460. .asyncDep.catch(err => {
  2461. handleError(err, instance, 0 /* SETUP_FUNCTION */);
  2462. })
  2463. .then(asyncSetupResult => {
  2464. // retry when the setup() promise resolves.
  2465. // component may have been unmounted before resolve.
  2466. if (instance.isUnmounted ||
  2467. suspense.isUnmounted ||
  2468. suspense.pendingId !== instance.suspenseId) {
  2469. return;
  2470. }
  2471. // retry from this component
  2472. instance.asyncResolved = true;
  2473. const { vnode } = instance;
  2474. {
  2475. pushWarningContext(vnode);
  2476. }
  2477. handleSetupResult(instance, asyncSetupResult);
  2478. if (hydratedEl) {
  2479. // vnode may have been replaced if an update happened before the
  2480. // async dep is resolved.
  2481. vnode.el = hydratedEl;
  2482. }
  2483. const placeholder = !hydratedEl && instance.subTree.el;
  2484. setupRenderEffect(instance, vnode,
  2485. // component may have been moved before resolve.
  2486. // if this is not a hydration, instance.subTree will be the comment
  2487. // placeholder.
  2488. parentNode(hydratedEl || instance.subTree.el),
  2489. // anchor will not be used if this is hydration, so only need to
  2490. // consider the comment placeholder case.
  2491. hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
  2492. if (placeholder) {
  2493. remove(placeholder);
  2494. }
  2495. updateHOCHostEl(instance, vnode.el);
  2496. {
  2497. popWarningContext();
  2498. }
  2499. // only decrease deps count if suspense is not already resolved
  2500. if (isInPendingSuspense && --suspense.deps === 0) {
  2501. suspense.resolve();
  2502. }
  2503. });
  2504. },
  2505. unmount(parentSuspense, doRemove) {
  2506. suspense.isUnmounted = true;
  2507. if (suspense.activeBranch) {
  2508. unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
  2509. }
  2510. if (suspense.pendingBranch) {
  2511. unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
  2512. }
  2513. }
  2514. };
  2515. return suspense;
  2516. }
  2517. function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, optimized, rendererInternals, hydrateNode) {
  2518. /* eslint-disable no-restricted-globals */
  2519. const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, optimized, rendererInternals, true /* hydrating */));
  2520. // there are two possible scenarios for server-rendered suspense:
  2521. // - success: ssr content should be fully resolved
  2522. // - failure: ssr content should be the fallback branch.
  2523. // however, on the client we don't really know if it has failed or not
  2524. // attempt to hydrate the DOM assuming it has succeeded, but we still
  2525. // need to construct a suspense boundary first
  2526. const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, optimized);
  2527. if (suspense.deps === 0) {
  2528. suspense.resolve();
  2529. }
  2530. return result;
  2531. /* eslint-enable no-restricted-globals */
  2532. }
  2533. function normalizeSuspenseChildren(vnode) {
  2534. const { shapeFlag, children } = vnode;
  2535. let content;
  2536. let fallback;
  2537. if (shapeFlag & 32 /* SLOTS_CHILDREN */) {
  2538. content = normalizeSuspenseSlot(children.default);
  2539. fallback = normalizeSuspenseSlot(children.fallback);
  2540. }
  2541. else {
  2542. content = normalizeSuspenseSlot(children);
  2543. fallback = normalizeVNode(null);
  2544. }
  2545. return {
  2546. content,
  2547. fallback
  2548. };
  2549. }
  2550. function normalizeSuspenseSlot(s) {
  2551. if (isFunction(s)) {
  2552. s = s();
  2553. }
  2554. if (isArray(s)) {
  2555. const singleChild = filterSingleRoot(s);
  2556. if (!singleChild) {
  2557. warn(`<Suspense> slots expect a single root node.`);
  2558. }
  2559. s = singleChild;
  2560. }
  2561. return normalizeVNode(s);
  2562. }
  2563. function queueEffectWithSuspense(fn, suspense) {
  2564. if (suspense && suspense.pendingBranch) {
  2565. if (isArray(fn)) {
  2566. suspense.effects.push(...fn);
  2567. }
  2568. else {
  2569. suspense.effects.push(fn);
  2570. }
  2571. }
  2572. else {
  2573. queuePostFlushCb(fn);
  2574. }
  2575. }
  2576. function setActiveBranch(suspense, branch) {
  2577. suspense.activeBranch = branch;
  2578. const { vnode, parentComponent } = suspense;
  2579. const el = (vnode.el = branch.el);
  2580. // in case suspense is the root node of a component,
  2581. // recursively update the HOC el
  2582. if (parentComponent && parentComponent.subTree === vnode) {
  2583. parentComponent.vnode.el = el;
  2584. updateHOCHostEl(parentComponent, el);
  2585. }
  2586. }
  2587. let isRenderingCompiledSlot = 0;
  2588. const setCompiledSlotRendering = (n) => (isRenderingCompiledSlot += n);
  2589. /**
  2590. * Compiler runtime helper for rendering `<slot/>`
  2591. * @private
  2592. */
  2593. function renderSlot(slots, name, props = {},
  2594. // this is not a user-facing function, so the fallback is always generated by
  2595. // the compiler and guaranteed to be a function returning an array
  2596. fallback) {
  2597. let slot = slots[name];
  2598. if (slot && slot.length > 1) {
  2599. warn(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
  2600. `function. You need to mark this component with $dynamic-slots in the ` +
  2601. `parent template.`);
  2602. slot = () => [];
  2603. }
  2604. // a compiled slot disables block tracking by default to avoid manual
  2605. // invocation interfering with template-based block tracking, but in
  2606. // `renderSlot` we can be sure that it's template-based so we can force
  2607. // enable it.
  2608. isRenderingCompiledSlot++;
  2609. openBlock();
  2610. const validSlotContent = slot && ensureValidVNode(slot(props));
  2611. const rendered = createBlock(Fragment, { key: props.key || `_${name}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* STABLE */
  2612. ? 64 /* STABLE_FRAGMENT */
  2613. : -2 /* BAIL */);
  2614. isRenderingCompiledSlot--;
  2615. return rendered;
  2616. }
  2617. function ensureValidVNode(vnodes) {
  2618. return vnodes.some(child => {
  2619. if (!isVNode(child))
  2620. return true;
  2621. if (child.type === Comment)
  2622. return false;
  2623. if (child.type === Fragment &&
  2624. !ensureValidVNode(child.children))
  2625. return false;
  2626. return true;
  2627. })
  2628. ? vnodes
  2629. : null;
  2630. }
  2631. /**
  2632. * Wrap a slot function to memoize current rendering instance
  2633. * @private
  2634. */
  2635. function withCtx(fn, ctx = currentRenderingInstance) {
  2636. if (!ctx)
  2637. return fn;
  2638. const renderFnWithContext = (...args) => {
  2639. // If a user calls a compiled slot inside a template expression (#1745), it
  2640. // can mess up block tracking, so by default we need to push a null block to
  2641. // avoid that. This isn't necessary if rendering a compiled `<slot>`.
  2642. if (!isRenderingCompiledSlot) {
  2643. openBlock(true /* null block that disables tracking */);
  2644. }
  2645. const owner = currentRenderingInstance;
  2646. setCurrentRenderingInstance(ctx);
  2647. const res = fn(...args);
  2648. setCurrentRenderingInstance(owner);
  2649. if (!isRenderingCompiledSlot) {
  2650. closeBlock();
  2651. }
  2652. return res;
  2653. };
  2654. renderFnWithContext._c = true;
  2655. return renderFnWithContext;
  2656. }
  2657. // SFC scoped style ID management.
  2658. let currentScopeId = null;
  2659. const scopeIdStack = [];
  2660. /**
  2661. * @private
  2662. */
  2663. function pushScopeId(id) {
  2664. scopeIdStack.push((currentScopeId = id));
  2665. }
  2666. /**
  2667. * @private
  2668. */
  2669. function popScopeId() {
  2670. scopeIdStack.pop();
  2671. currentScopeId = scopeIdStack[scopeIdStack.length - 1] || null;
  2672. }
  2673. /**
  2674. * @private
  2675. */
  2676. function withScopeId(id) {
  2677. return ((fn) => withCtx(function () {
  2678. pushScopeId(id);
  2679. const res = fn.apply(this, arguments);
  2680. popScopeId();
  2681. return res;
  2682. }));
  2683. }
  2684. function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
  2685. isSSR = false) {
  2686. const props = {};
  2687. const attrs = {};
  2688. def(attrs, InternalObjectKey, 1);
  2689. setFullProps(instance, rawProps, props, attrs);
  2690. // validation
  2691. {
  2692. validateProps(props, instance);
  2693. }
  2694. if (isStateful) {
  2695. // stateful
  2696. instance.props = isSSR ? props : shallowReactive(props);
  2697. }
  2698. else {
  2699. if (!instance.type.props) {
  2700. // functional w/ optional props, props === attrs
  2701. instance.props = attrs;
  2702. }
  2703. else {
  2704. // functional w/ declared props
  2705. instance.props = props;
  2706. }
  2707. }
  2708. instance.attrs = attrs;
  2709. }
  2710. function updateProps(instance, rawProps, rawPrevProps, optimized) {
  2711. const { props, attrs, vnode: { patchFlag } } = instance;
  2712. const rawCurrentProps = toRaw(props);
  2713. const [options] = instance.propsOptions;
  2714. if (
  2715. // always force full diff in dev
  2716. // - #1942 if hmr is enabled with sfc component
  2717. // - vite#872 non-sfc component used by sfc component
  2718. !((instance.type.__hmrId ||
  2719. (instance.parent && instance.parent.type.__hmrId))) &&
  2720. (optimized || patchFlag > 0) &&
  2721. !(patchFlag & 16 /* FULL_PROPS */)) {
  2722. if (patchFlag & 8 /* PROPS */) {
  2723. // Compiler-generated props & no keys change, just set the updated
  2724. // the props.
  2725. const propsToUpdate = instance.vnode.dynamicProps;
  2726. for (let i = 0; i < propsToUpdate.length; i++) {
  2727. const key = propsToUpdate[i];
  2728. // PROPS flag guarantees rawProps to be non-null
  2729. const value = rawProps[key];
  2730. if (options) {
  2731. // attr / props separation was done on init and will be consistent
  2732. // in this code path, so just check if attrs have it.
  2733. if (hasOwn(attrs, key)) {
  2734. attrs[key] = value;
  2735. }
  2736. else {
  2737. const camelizedKey = camelize(key);
  2738. props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance);
  2739. }
  2740. }
  2741. else {
  2742. attrs[key] = value;
  2743. }
  2744. }
  2745. }
  2746. }
  2747. else {
  2748. // full props update.
  2749. setFullProps(instance, rawProps, props, attrs);
  2750. // in case of dynamic props, check if we need to delete keys from
  2751. // the props object
  2752. let kebabKey;
  2753. for (const key in rawCurrentProps) {
  2754. if (!rawProps ||
  2755. // for camelCase
  2756. (!hasOwn(rawProps, key) &&
  2757. // it's possible the original props was passed in as kebab-case
  2758. // and converted to camelCase (#955)
  2759. ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
  2760. if (options) {
  2761. if (rawPrevProps &&
  2762. // for camelCase
  2763. (rawPrevProps[key] !== undefined ||
  2764. // for kebab-case
  2765. rawPrevProps[kebabKey] !== undefined)) {
  2766. props[key] = resolvePropValue(options, rawProps || EMPTY_OBJ, key, undefined, instance);
  2767. }
  2768. }
  2769. else {
  2770. delete props[key];
  2771. }
  2772. }
  2773. }
  2774. // in the case of functional component w/o props declaration, props and
  2775. // attrs point to the same object so it should already have been updated.
  2776. if (attrs !== rawCurrentProps) {
  2777. for (const key in attrs) {
  2778. if (!rawProps || !hasOwn(rawProps, key)) {
  2779. delete attrs[key];
  2780. }
  2781. }
  2782. }
  2783. }
  2784. // trigger updates for $attrs in case it's used in component slots
  2785. trigger(instance, "set" /* SET */, '$attrs');
  2786. if (rawProps) {
  2787. validateProps(props, instance);
  2788. }
  2789. }
  2790. function setFullProps(instance, rawProps, props, attrs) {
  2791. const [options, needCastKeys] = instance.propsOptions;
  2792. if (rawProps) {
  2793. for (const key in rawProps) {
  2794. const value = rawProps[key];
  2795. // key, ref are reserved and never passed down
  2796. if (isReservedProp(key)) {
  2797. continue;
  2798. }
  2799. // prop option names are camelized during normalization, so to support
  2800. // kebab -> camel conversion here we need to camelize the key.
  2801. let camelKey;
  2802. if (options && hasOwn(options, (camelKey = camelize(key)))) {
  2803. props[camelKey] = value;
  2804. }
  2805. else if (!isEmitListener(instance.emitsOptions, key)) {
  2806. // Any non-declared (either as a prop or an emitted event) props are put
  2807. // into a separate `attrs` object for spreading. Make sure to preserve
  2808. // original key casing
  2809. attrs[key] = value;
  2810. }
  2811. }
  2812. }
  2813. if (needCastKeys) {
  2814. const rawCurrentProps = toRaw(props);
  2815. for (let i = 0; i < needCastKeys.length; i++) {
  2816. const key = needCastKeys[i];
  2817. props[key] = resolvePropValue(options, rawCurrentProps, key, rawCurrentProps[key], instance);
  2818. }
  2819. }
  2820. }
  2821. function resolvePropValue(options, props, key, value, instance) {
  2822. const opt = options[key];
  2823. if (opt != null) {
  2824. const hasDefault = hasOwn(opt, 'default');
  2825. // default values
  2826. if (hasDefault && value === undefined) {
  2827. const defaultValue = opt.default;
  2828. if (opt.type !== Function && isFunction(defaultValue)) {
  2829. setCurrentInstance(instance);
  2830. value = defaultValue(props);
  2831. setCurrentInstance(null);
  2832. }
  2833. else {
  2834. value = defaultValue;
  2835. }
  2836. }
  2837. // boolean casting
  2838. if (opt[0 /* shouldCast */]) {
  2839. if (!hasOwn(props, key) && !hasDefault) {
  2840. value = false;
  2841. }
  2842. else if (opt[1 /* shouldCastTrue */] &&
  2843. (value === '' || value === hyphenate(key))) {
  2844. value = true;
  2845. }
  2846. }
  2847. }
  2848. return value;
  2849. }
  2850. function normalizePropsOptions(comp, appContext, asMixin = false) {
  2851. if (!appContext.deopt && comp.__props) {
  2852. return comp.__props;
  2853. }
  2854. const raw = comp.props;
  2855. const normalized = {};
  2856. const needCastKeys = [];
  2857. // apply mixin/extends props
  2858. let hasExtends = false;
  2859. if (!isFunction(comp)) {
  2860. const extendProps = (raw) => {
  2861. hasExtends = true;
  2862. const [props, keys] = normalizePropsOptions(raw, appContext, true);
  2863. extend(normalized, props);
  2864. if (keys)
  2865. needCastKeys.push(...keys);
  2866. };
  2867. if (!asMixin && appContext.mixins.length) {
  2868. appContext.mixins.forEach(extendProps);
  2869. }
  2870. if (comp.extends) {
  2871. extendProps(comp.extends);
  2872. }
  2873. if (comp.mixins) {
  2874. comp.mixins.forEach(extendProps);
  2875. }
  2876. }
  2877. if (!raw && !hasExtends) {
  2878. return (comp.__props = EMPTY_ARR);
  2879. }
  2880. if (isArray(raw)) {
  2881. for (let i = 0; i < raw.length; i++) {
  2882. if (!isString(raw[i])) {
  2883. warn(`props must be strings when using array syntax.`, raw[i]);
  2884. }
  2885. const normalizedKey = camelize(raw[i]);
  2886. if (validatePropName(normalizedKey)) {
  2887. normalized[normalizedKey] = EMPTY_OBJ;
  2888. }
  2889. }
  2890. }
  2891. else if (raw) {
  2892. if (!isObject(raw)) {
  2893. warn(`invalid props options`, raw);
  2894. }
  2895. for (const key in raw) {
  2896. const normalizedKey = camelize(key);
  2897. if (validatePropName(normalizedKey)) {
  2898. const opt = raw[key];
  2899. const prop = (normalized[normalizedKey] =
  2900. isArray(opt) || isFunction(opt) ? { type: opt } : opt);
  2901. if (prop) {
  2902. const booleanIndex = getTypeIndex(Boolean, prop.type);
  2903. const stringIndex = getTypeIndex(String, prop.type);
  2904. prop[0 /* shouldCast */] = booleanIndex > -1;
  2905. prop[1 /* shouldCastTrue */] =
  2906. stringIndex < 0 || booleanIndex < stringIndex;
  2907. // if the prop needs boolean casting or default value
  2908. if (booleanIndex > -1 || hasOwn(prop, 'default')) {
  2909. needCastKeys.push(normalizedKey);
  2910. }
  2911. }
  2912. }
  2913. }
  2914. }
  2915. return (comp.__props = [normalized, needCastKeys]);
  2916. }
  2917. function validatePropName(key) {
  2918. if (key[0] !== '$') {
  2919. return true;
  2920. }
  2921. else {
  2922. warn(`Invalid prop name: "${key}" is a reserved property.`);
  2923. }
  2924. return false;
  2925. }
  2926. // use function string name to check type constructors
  2927. // so that it works across vms / iframes.
  2928. function getType(ctor) {
  2929. const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
  2930. return match ? match[1] : '';
  2931. }
  2932. function isSameType(a, b) {
  2933. return getType(a) === getType(b);
  2934. }
  2935. function getTypeIndex(type, expectedTypes) {
  2936. if (isArray(expectedTypes)) {
  2937. for (let i = 0, len = expectedTypes.length; i < len; i++) {
  2938. if (isSameType(expectedTypes[i], type)) {
  2939. return i;
  2940. }
  2941. }
  2942. }
  2943. else if (isFunction(expectedTypes)) {
  2944. return isSameType(expectedTypes, type) ? 0 : -1;
  2945. }
  2946. return -1;
  2947. }
  2948. /**
  2949. * dev only
  2950. */
  2951. function validateProps(props, instance) {
  2952. const rawValues = toRaw(props);
  2953. const options = instance.propsOptions[0];
  2954. for (const key in options) {
  2955. let opt = options[key];
  2956. if (opt == null)
  2957. continue;
  2958. validateProp(key, rawValues[key], opt, !hasOwn(rawValues, key));
  2959. }
  2960. }
  2961. /**
  2962. * dev only
  2963. */
  2964. function validateProp(name, value, prop, isAbsent) {
  2965. const { type, required, validator } = prop;
  2966. // required!
  2967. if (required && isAbsent) {
  2968. warn('Missing required prop: "' + name + '"');
  2969. return;
  2970. }
  2971. // missing but optional
  2972. if (value == null && !prop.required) {
  2973. return;
  2974. }
  2975. // type check
  2976. if (type != null && type !== true) {
  2977. let isValid = false;
  2978. const types = isArray(type) ? type : [type];
  2979. const expectedTypes = [];
  2980. // value is valid as long as one of the specified types match
  2981. for (let i = 0; i < types.length && !isValid; i++) {
  2982. const { valid, expectedType } = assertType(value, types[i]);
  2983. expectedTypes.push(expectedType || '');
  2984. isValid = valid;
  2985. }
  2986. if (!isValid) {
  2987. warn(getInvalidTypeMessage(name, value, expectedTypes));
  2988. return;
  2989. }
  2990. }
  2991. // custom validator
  2992. if (validator && !validator(value)) {
  2993. warn('Invalid prop: custom validator check failed for prop "' + name + '".');
  2994. }
  2995. }
  2996. const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
  2997. /**
  2998. * dev only
  2999. */
  3000. function assertType(value, type) {
  3001. let valid;
  3002. const expectedType = getType(type);
  3003. if (isSimpleType(expectedType)) {
  3004. const t = typeof value;
  3005. valid = t === expectedType.toLowerCase();
  3006. // for primitive wrapper objects
  3007. if (!valid && t === 'object') {
  3008. valid = value instanceof type;
  3009. }
  3010. }
  3011. else if (expectedType === 'Object') {
  3012. valid = isObject(value);
  3013. }
  3014. else if (expectedType === 'Array') {
  3015. valid = isArray(value);
  3016. }
  3017. else {
  3018. valid = value instanceof type;
  3019. }
  3020. return {
  3021. valid,
  3022. expectedType
  3023. };
  3024. }
  3025. /**
  3026. * dev only
  3027. */
  3028. function getInvalidTypeMessage(name, value, expectedTypes) {
  3029. let message = `Invalid prop: type check failed for prop "${name}".` +
  3030. ` Expected ${expectedTypes.map(capitalize).join(', ')}`;
  3031. const expectedType = expectedTypes[0];
  3032. const receivedType = toRawType(value);
  3033. const expectedValue = styleValue(value, expectedType);
  3034. const receivedValue = styleValue(value, receivedType);
  3035. // check if we need to specify expected value
  3036. if (expectedTypes.length === 1 &&
  3037. isExplicable(expectedType) &&
  3038. !isBoolean(expectedType, receivedType)) {
  3039. message += ` with value ${expectedValue}`;
  3040. }
  3041. message += `, got ${receivedType} `;
  3042. // check if we need to specify received value
  3043. if (isExplicable(receivedType)) {
  3044. message += `with value ${receivedValue}.`;
  3045. }
  3046. return message;
  3047. }
  3048. /**
  3049. * dev only
  3050. */
  3051. function styleValue(value, type) {
  3052. if (type === 'String') {
  3053. return `"${value}"`;
  3054. }
  3055. else if (type === 'Number') {
  3056. return `${Number(value)}`;
  3057. }
  3058. else {
  3059. return `${value}`;
  3060. }
  3061. }
  3062. /**
  3063. * dev only
  3064. */
  3065. function isExplicable(type) {
  3066. const explicitTypes = ['string', 'number', 'boolean'];
  3067. return explicitTypes.some(elem => type.toLowerCase() === elem);
  3068. }
  3069. /**
  3070. * dev only
  3071. */
  3072. function isBoolean(...args) {
  3073. return args.some(elem => elem.toLowerCase() === 'boolean');
  3074. }
  3075. function injectHook(type, hook, target = currentInstance, prepend = false) {
  3076. if (target) {
  3077. const hooks = target[type] || (target[type] = []);
  3078. // cache the error handling wrapper for injected hooks so the same hook
  3079. // can be properly deduped by the scheduler. "__weh" stands for "with error
  3080. // handling".
  3081. const wrappedHook = hook.__weh ||
  3082. (hook.__weh = (...args) => {
  3083. if (target.isUnmounted) {
  3084. return;
  3085. }
  3086. // disable tracking inside all lifecycle hooks
  3087. // since they can potentially be called inside effects.
  3088. pauseTracking();
  3089. // Set currentInstance during hook invocation.
  3090. // This assumes the hook does not synchronously trigger other hooks, which
  3091. // can only be false when the user does something really funky.
  3092. setCurrentInstance(target);
  3093. const res = callWithAsyncErrorHandling(hook, target, type, args);
  3094. setCurrentInstance(null);
  3095. resetTracking();
  3096. return res;
  3097. });
  3098. if (prepend) {
  3099. hooks.unshift(wrappedHook);
  3100. }
  3101. else {
  3102. hooks.push(wrappedHook);
  3103. }
  3104. return wrappedHook;
  3105. }
  3106. else {
  3107. const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
  3108. warn(`${apiName} is called when there is no active component instance to be ` +
  3109. `associated with. ` +
  3110. `Lifecycle injection APIs can only be used during execution of setup().` +
  3111. (` If you are using async setup(), make sure to register lifecycle ` +
  3112. `hooks before the first await statement.`
  3113. ));
  3114. }
  3115. }
  3116. const createHook = (lifecycle) => (hook, target = currentInstance) =>
  3117. // post-create lifecycle registrations are noops during SSR
  3118. !isInSSRComponentSetup && injectHook(lifecycle, hook, target);
  3119. const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
  3120. const onMounted = createHook("m" /* MOUNTED */);
  3121. const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
  3122. const onUpdated = createHook("u" /* UPDATED */);
  3123. const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
  3124. const onUnmounted = createHook("um" /* UNMOUNTED */);
  3125. const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
  3126. const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
  3127. const onErrorCaptured = (hook, target = currentInstance) => {
  3128. injectHook("ec" /* ERROR_CAPTURED */, hook, target);
  3129. };
  3130. // Simple effect.
  3131. function watchEffect(effect, options) {
  3132. return doWatch(effect, null, options);
  3133. }
  3134. // initial value for watchers to trigger on undefined initial values
  3135. const INITIAL_WATCHER_VALUE = {};
  3136. // implementation
  3137. function watch(source, cb, options) {
  3138. if (!isFunction(cb)) {
  3139. warn(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
  3140. `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
  3141. `supports \`watch(source, cb, options?) signature.`);
  3142. }
  3143. return doWatch(source, cb, options);
  3144. }
  3145. function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ, instance = currentInstance) {
  3146. if (!cb) {
  3147. if (immediate !== undefined) {
  3148. warn(`watch() "immediate" option is only respected when using the ` +
  3149. `watch(source, callback, options?) signature.`);
  3150. }
  3151. if (deep !== undefined) {
  3152. warn(`watch() "deep" option is only respected when using the ` +
  3153. `watch(source, callback, options?) signature.`);
  3154. }
  3155. }
  3156. const warnInvalidSource = (s) => {
  3157. warn(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
  3158. `a reactive object, or an array of these types.`);
  3159. };
  3160. let getter;
  3161. let forceTrigger = false;
  3162. if (isRef(source)) {
  3163. getter = () => source.value;
  3164. forceTrigger = !!source._shallow;
  3165. }
  3166. else if (isReactive(source)) {
  3167. getter = () => source;
  3168. deep = true;
  3169. }
  3170. else if (isArray(source)) {
  3171. getter = () => source.map(s => {
  3172. if (isRef(s)) {
  3173. return s.value;
  3174. }
  3175. else if (isReactive(s)) {
  3176. return traverse(s);
  3177. }
  3178. else if (isFunction(s)) {
  3179. return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */, [
  3180. instance && instance.proxy
  3181. ]);
  3182. }
  3183. else {
  3184. warnInvalidSource(s);
  3185. }
  3186. });
  3187. }
  3188. else if (isFunction(source)) {
  3189. if (cb) {
  3190. // getter with cb
  3191. getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */, [
  3192. instance && instance.proxy
  3193. ]);
  3194. }
  3195. else {
  3196. // no cb -> simple effect
  3197. getter = () => {
  3198. if (instance && instance.isUnmounted) {
  3199. return;
  3200. }
  3201. if (cleanup) {
  3202. cleanup();
  3203. }
  3204. return callWithErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onInvalidate]);
  3205. };
  3206. }
  3207. }
  3208. else {
  3209. getter = NOOP;
  3210. warnInvalidSource(source);
  3211. }
  3212. if (cb && deep) {
  3213. const baseGetter = getter;
  3214. getter = () => traverse(baseGetter());
  3215. }
  3216. let cleanup;
  3217. const onInvalidate = (fn) => {
  3218. cleanup = runner.options.onStop = () => {
  3219. callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
  3220. };
  3221. };
  3222. let oldValue = isArray(source) ? [] : INITIAL_WATCHER_VALUE;
  3223. const job = () => {
  3224. if (!runner.active) {
  3225. return;
  3226. }
  3227. if (cb) {
  3228. // watch(source, cb)
  3229. const newValue = runner();
  3230. if (deep || forceTrigger || hasChanged(newValue, oldValue)) {
  3231. // cleanup before running cb again
  3232. if (cleanup) {
  3233. cleanup();
  3234. }
  3235. callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
  3236. newValue,
  3237. // pass undefined as the old value when it's changed for the first time
  3238. oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
  3239. onInvalidate
  3240. ]);
  3241. oldValue = newValue;
  3242. }
  3243. }
  3244. else {
  3245. // watchEffect
  3246. runner();
  3247. }
  3248. };
  3249. // important: mark the job as a watcher callback so that scheduler knows
  3250. // it is allowed to self-trigger (#1727)
  3251. job.allowRecurse = !!cb;
  3252. let scheduler;
  3253. if (flush === 'sync') {
  3254. scheduler = job;
  3255. }
  3256. else if (flush === 'post') {
  3257. scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
  3258. }
  3259. else {
  3260. // default: 'pre'
  3261. scheduler = () => {
  3262. if (!instance || instance.isMounted) {
  3263. queuePreFlushCb(job);
  3264. }
  3265. else {
  3266. // with 'pre' option, the first call must happen before
  3267. // the component is mounted so it is called synchronously.
  3268. job();
  3269. }
  3270. };
  3271. }
  3272. const runner = effect(getter, {
  3273. lazy: true,
  3274. onTrack,
  3275. onTrigger,
  3276. scheduler
  3277. });
  3278. recordInstanceBoundEffect(runner, instance);
  3279. // initial run
  3280. if (cb) {
  3281. if (immediate) {
  3282. job();
  3283. }
  3284. else {
  3285. oldValue = runner();
  3286. }
  3287. }
  3288. else if (flush === 'post') {
  3289. queuePostRenderEffect(runner, instance && instance.suspense);
  3290. }
  3291. else {
  3292. runner();
  3293. }
  3294. return () => {
  3295. stop(runner);
  3296. if (instance) {
  3297. remove(instance.effects, runner);
  3298. }
  3299. };
  3300. }
  3301. // this.$watch
  3302. function instanceWatch(source, cb, options) {
  3303. const publicThis = this.proxy;
  3304. const getter = isString(source)
  3305. ? () => publicThis[source]
  3306. : source.bind(publicThis);
  3307. return doWatch(getter, cb.bind(publicThis), options, this);
  3308. }
  3309. function traverse(value, seen = new Set()) {
  3310. if (!isObject(value) || seen.has(value)) {
  3311. return value;
  3312. }
  3313. seen.add(value);
  3314. if (isRef(value)) {
  3315. traverse(value.value, seen);
  3316. }
  3317. else if (isArray(value)) {
  3318. for (let i = 0; i < value.length; i++) {
  3319. traverse(value[i], seen);
  3320. }
  3321. }
  3322. else if (isSet(value) || isMap(value)) {
  3323. value.forEach((v) => {
  3324. traverse(v, seen);
  3325. });
  3326. }
  3327. else {
  3328. for (const key in value) {
  3329. traverse(value[key], seen);
  3330. }
  3331. }
  3332. return value;
  3333. }
  3334. function useTransitionState() {
  3335. const state = {
  3336. isMounted: false,
  3337. isLeaving: false,
  3338. isUnmounting: false,
  3339. leavingVNodes: new Map()
  3340. };
  3341. onMounted(() => {
  3342. state.isMounted = true;
  3343. });
  3344. onBeforeUnmount(() => {
  3345. state.isUnmounting = true;
  3346. });
  3347. return state;
  3348. }
  3349. const TransitionHookValidator = [Function, Array];
  3350. const BaseTransitionImpl = {
  3351. name: `BaseTransition`,
  3352. props: {
  3353. mode: String,
  3354. appear: Boolean,
  3355. persisted: Boolean,
  3356. // enter
  3357. onBeforeEnter: TransitionHookValidator,
  3358. onEnter: TransitionHookValidator,
  3359. onAfterEnter: TransitionHookValidator,
  3360. onEnterCancelled: TransitionHookValidator,
  3361. // leave
  3362. onBeforeLeave: TransitionHookValidator,
  3363. onLeave: TransitionHookValidator,
  3364. onAfterLeave: TransitionHookValidator,
  3365. onLeaveCancelled: TransitionHookValidator,
  3366. // appear
  3367. onBeforeAppear: TransitionHookValidator,
  3368. onAppear: TransitionHookValidator,
  3369. onAfterAppear: TransitionHookValidator,
  3370. onAppearCancelled: TransitionHookValidator
  3371. },
  3372. setup(props, { slots }) {
  3373. const instance = getCurrentInstance();
  3374. const state = useTransitionState();
  3375. let prevTransitionKey;
  3376. return () => {
  3377. const children = slots.default && getTransitionRawChildren(slots.default(), true);
  3378. if (!children || !children.length) {
  3379. return;
  3380. }
  3381. // warn multiple elements
  3382. if (children.length > 1) {
  3383. warn('<transition> can only be used on a single element or component. Use ' +
  3384. '<transition-group> for lists.');
  3385. }
  3386. // there's no need to track reactivity for these props so use the raw
  3387. // props for a bit better perf
  3388. const rawProps = toRaw(props);
  3389. const { mode } = rawProps;
  3390. // check mode
  3391. if (mode && !['in-out', 'out-in', 'default'].includes(mode)) {
  3392. warn(`invalid <transition> mode: ${mode}`);
  3393. }
  3394. // at this point children has a guaranteed length of 1.
  3395. const child = children[0];
  3396. if (state.isLeaving) {
  3397. return emptyPlaceholder(child);
  3398. }
  3399. // in the case of <transition><keep-alive/></transition>, we need to
  3400. // compare the type of the kept-alive children.
  3401. const innerChild = getKeepAliveChild(child);
  3402. if (!innerChild) {
  3403. return emptyPlaceholder(child);
  3404. }
  3405. const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
  3406. setTransitionHooks(innerChild, enterHooks);
  3407. const oldChild = instance.subTree;
  3408. const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
  3409. let transitionKeyChanged = false;
  3410. const { getTransitionKey } = innerChild.type;
  3411. if (getTransitionKey) {
  3412. const key = getTransitionKey();
  3413. if (prevTransitionKey === undefined) {
  3414. prevTransitionKey = key;
  3415. }
  3416. else if (key !== prevTransitionKey) {
  3417. prevTransitionKey = key;
  3418. transitionKeyChanged = true;
  3419. }
  3420. }
  3421. // handle mode
  3422. if (oldInnerChild &&
  3423. oldInnerChild.type !== Comment &&
  3424. (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
  3425. const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
  3426. // update old tree's hooks in case of dynamic transition
  3427. setTransitionHooks(oldInnerChild, leavingHooks);
  3428. // switching between different views
  3429. if (mode === 'out-in') {
  3430. state.isLeaving = true;
  3431. // return placeholder node and queue update when leave finishes
  3432. leavingHooks.afterLeave = () => {
  3433. state.isLeaving = false;
  3434. instance.update();
  3435. };
  3436. return emptyPlaceholder(child);
  3437. }
  3438. else if (mode === 'in-out') {
  3439. leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
  3440. const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
  3441. leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
  3442. // early removal callback
  3443. el._leaveCb = () => {
  3444. earlyRemove();
  3445. el._leaveCb = undefined;
  3446. delete enterHooks.delayedLeave;
  3447. };
  3448. enterHooks.delayedLeave = delayedLeave;
  3449. };
  3450. }
  3451. }
  3452. return child;
  3453. };
  3454. }
  3455. };
  3456. // export the public type for h/tsx inference
  3457. // also to avoid inline import() in generated d.ts files
  3458. const BaseTransition = BaseTransitionImpl;
  3459. function getLeavingNodesForType(state, vnode) {
  3460. const { leavingVNodes } = state;
  3461. let leavingVNodesCache = leavingVNodes.get(vnode.type);
  3462. if (!leavingVNodesCache) {
  3463. leavingVNodesCache = Object.create(null);
  3464. leavingVNodes.set(vnode.type, leavingVNodesCache);
  3465. }
  3466. return leavingVNodesCache;
  3467. }
  3468. // The transition hooks are attached to the vnode as vnode.transition
  3469. // and will be called at appropriate timing in the renderer.
  3470. function resolveTransitionHooks(vnode, props, state, instance) {
  3471. const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
  3472. const key = String(vnode.key);
  3473. const leavingVNodesCache = getLeavingNodesForType(state, vnode);
  3474. const callHook = (hook, args) => {
  3475. hook &&
  3476. callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
  3477. };
  3478. const hooks = {
  3479. mode,
  3480. persisted,
  3481. beforeEnter(el) {
  3482. let hook = onBeforeEnter;
  3483. if (!state.isMounted) {
  3484. if (appear) {
  3485. hook = onBeforeAppear || onBeforeEnter;
  3486. }
  3487. else {
  3488. return;
  3489. }
  3490. }
  3491. // for same element (v-show)
  3492. if (el._leaveCb) {
  3493. el._leaveCb(true /* cancelled */);
  3494. }
  3495. // for toggled element with same key (v-if)
  3496. const leavingVNode = leavingVNodesCache[key];
  3497. if (leavingVNode &&
  3498. isSameVNodeType(vnode, leavingVNode) &&
  3499. leavingVNode.el._leaveCb) {
  3500. // force early removal (not cancelled)
  3501. leavingVNode.el._leaveCb();
  3502. }
  3503. callHook(hook, [el]);
  3504. },
  3505. enter(el) {
  3506. let hook = onEnter;
  3507. let afterHook = onAfterEnter;
  3508. let cancelHook = onEnterCancelled;
  3509. if (!state.isMounted) {
  3510. if (appear) {
  3511. hook = onAppear || onEnter;
  3512. afterHook = onAfterAppear || onAfterEnter;
  3513. cancelHook = onAppearCancelled || onEnterCancelled;
  3514. }
  3515. else {
  3516. return;
  3517. }
  3518. }
  3519. let called = false;
  3520. const done = (el._enterCb = (cancelled) => {
  3521. if (called)
  3522. return;
  3523. called = true;
  3524. if (cancelled) {
  3525. callHook(cancelHook, [el]);
  3526. }
  3527. else {
  3528. callHook(afterHook, [el]);
  3529. }
  3530. if (hooks.delayedLeave) {
  3531. hooks.delayedLeave();
  3532. }
  3533. el._enterCb = undefined;
  3534. });
  3535. if (hook) {
  3536. hook(el, done);
  3537. if (hook.length <= 1) {
  3538. done();
  3539. }
  3540. }
  3541. else {
  3542. done();
  3543. }
  3544. },
  3545. leave(el, remove) {
  3546. const key = String(vnode.key);
  3547. if (el._enterCb) {
  3548. el._enterCb(true /* cancelled */);
  3549. }
  3550. if (state.isUnmounting) {
  3551. return remove();
  3552. }
  3553. callHook(onBeforeLeave, [el]);
  3554. let called = false;
  3555. const done = (el._leaveCb = (cancelled) => {
  3556. if (called)
  3557. return;
  3558. called = true;
  3559. remove();
  3560. if (cancelled) {
  3561. callHook(onLeaveCancelled, [el]);
  3562. }
  3563. else {
  3564. callHook(onAfterLeave, [el]);
  3565. }
  3566. el._leaveCb = undefined;
  3567. if (leavingVNodesCache[key] === vnode) {
  3568. delete leavingVNodesCache[key];
  3569. }
  3570. });
  3571. leavingVNodesCache[key] = vnode;
  3572. if (onLeave) {
  3573. onLeave(el, done);
  3574. if (onLeave.length <= 1) {
  3575. done();
  3576. }
  3577. }
  3578. else {
  3579. done();
  3580. }
  3581. },
  3582. clone(vnode) {
  3583. return resolveTransitionHooks(vnode, props, state, instance);
  3584. }
  3585. };
  3586. return hooks;
  3587. }
  3588. // the placeholder really only handles one special case: KeepAlive
  3589. // in the case of a KeepAlive in a leave phase we need to return a KeepAlive
  3590. // placeholder with empty content to avoid the KeepAlive instance from being
  3591. // unmounted.
  3592. function emptyPlaceholder(vnode) {
  3593. if (isKeepAlive(vnode)) {
  3594. vnode = cloneVNode(vnode);
  3595. vnode.children = null;
  3596. return vnode;
  3597. }
  3598. }
  3599. function getKeepAliveChild(vnode) {
  3600. return isKeepAlive(vnode)
  3601. ? vnode.children
  3602. ? vnode.children[0]
  3603. : undefined
  3604. : vnode;
  3605. }
  3606. function setTransitionHooks(vnode, hooks) {
  3607. if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
  3608. setTransitionHooks(vnode.component.subTree, hooks);
  3609. }
  3610. else if (vnode.shapeFlag & 128 /* SUSPENSE */) {
  3611. vnode.ssContent.transition = hooks.clone(vnode.ssContent);
  3612. vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
  3613. }
  3614. else {
  3615. vnode.transition = hooks;
  3616. }
  3617. }
  3618. function getTransitionRawChildren(children, keepComment = false) {
  3619. let ret = [];
  3620. let keyedFragmentCount = 0;
  3621. for (let i = 0; i < children.length; i++) {
  3622. const child = children[i];
  3623. // handle fragment children case, e.g. v-for
  3624. if (child.type === Fragment) {
  3625. if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
  3626. keyedFragmentCount++;
  3627. ret = ret.concat(getTransitionRawChildren(child.children, keepComment));
  3628. }
  3629. // comment placeholders should be skipped, e.g. v-if
  3630. else if (keepComment || child.type !== Comment) {
  3631. ret.push(child);
  3632. }
  3633. }
  3634. // #1126 if a transition children list contains multiple sub fragments, these
  3635. // fragments will be merged into a flat children array. Since each v-for
  3636. // fragment may contain different static bindings inside, we need to de-op
  3637. // these children to force full diffs to ensure correct behavior.
  3638. if (keyedFragmentCount > 1) {
  3639. for (let i = 0; i < ret.length; i++) {
  3640. ret[i].patchFlag = -2 /* BAIL */;
  3641. }
  3642. }
  3643. return ret;
  3644. }
  3645. const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
  3646. const KeepAliveImpl = {
  3647. name: `KeepAlive`,
  3648. // Marker for special handling inside the renderer. We are not using a ===
  3649. // check directly on KeepAlive in the renderer, because importing it directly
  3650. // would prevent it from being tree-shaken.
  3651. __isKeepAlive: true,
  3652. props: {
  3653. include: [String, RegExp, Array],
  3654. exclude: [String, RegExp, Array],
  3655. max: [String, Number]
  3656. },
  3657. setup(props, { slots }) {
  3658. const cache = new Map();
  3659. const keys = new Set();
  3660. let current = null;
  3661. const instance = getCurrentInstance();
  3662. const parentSuspense = instance.suspense;
  3663. // KeepAlive communicates with the instantiated renderer via the
  3664. // ctx where the renderer passes in its internals,
  3665. // and the KeepAlive instance exposes activate/deactivate implementations.
  3666. // The whole point of this is to avoid importing KeepAlive directly in the
  3667. // renderer to facilitate tree-shaking.
  3668. const sharedContext = instance.ctx;
  3669. const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
  3670. const storageContainer = createElement('div');
  3671. sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
  3672. const instance = vnode.component;
  3673. move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
  3674. // in case props have changed
  3675. patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, optimized);
  3676. queuePostRenderEffect(() => {
  3677. instance.isDeactivated = false;
  3678. if (instance.a) {
  3679. invokeArrayFns(instance.a);
  3680. }
  3681. const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
  3682. if (vnodeHook) {
  3683. invokeVNodeHook(vnodeHook, instance.parent, vnode);
  3684. }
  3685. }, parentSuspense);
  3686. };
  3687. sharedContext.deactivate = (vnode) => {
  3688. const instance = vnode.component;
  3689. move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
  3690. queuePostRenderEffect(() => {
  3691. if (instance.da) {
  3692. invokeArrayFns(instance.da);
  3693. }
  3694. const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
  3695. if (vnodeHook) {
  3696. invokeVNodeHook(vnodeHook, instance.parent, vnode);
  3697. }
  3698. instance.isDeactivated = true;
  3699. }, parentSuspense);
  3700. };
  3701. function unmount(vnode) {
  3702. // reset the shapeFlag so it can be properly unmounted
  3703. resetShapeFlag(vnode);
  3704. _unmount(vnode, instance, parentSuspense);
  3705. }
  3706. function pruneCache(filter) {
  3707. cache.forEach((vnode, key) => {
  3708. const name = getComponentName(vnode.type);
  3709. if (name && (!filter || !filter(name))) {
  3710. pruneCacheEntry(key);
  3711. }
  3712. });
  3713. }
  3714. function pruneCacheEntry(key) {
  3715. const cached = cache.get(key);
  3716. if (!current || cached.type !== current.type) {
  3717. unmount(cached);
  3718. }
  3719. else if (current) {
  3720. // current active instance should no longer be kept-alive.
  3721. // we can't unmount it now but it might be later, so reset its flag now.
  3722. resetShapeFlag(current);
  3723. }
  3724. cache.delete(key);
  3725. keys.delete(key);
  3726. }
  3727. // prune cache on include/exclude prop change
  3728. watch(() => [props.include, props.exclude], ([include, exclude]) => {
  3729. include && pruneCache(name => matches(include, name));
  3730. exclude && pruneCache(name => !matches(exclude, name));
  3731. },
  3732. // prune post-render after `current` has been updated
  3733. { flush: 'post', deep: true });
  3734. // cache sub tree after render
  3735. let pendingCacheKey = null;
  3736. const cacheSubtree = () => {
  3737. // fix #1621, the pendingCacheKey could be 0
  3738. if (pendingCacheKey != null) {
  3739. cache.set(pendingCacheKey, getInnerChild(instance.subTree));
  3740. }
  3741. };
  3742. onMounted(cacheSubtree);
  3743. onUpdated(cacheSubtree);
  3744. onBeforeUnmount(() => {
  3745. cache.forEach(cached => {
  3746. const { subTree, suspense } = instance;
  3747. const vnode = getInnerChild(subTree);
  3748. if (cached.type === vnode.type) {
  3749. // current instance will be unmounted as part of keep-alive's unmount
  3750. resetShapeFlag(vnode);
  3751. // but invoke its deactivated hook here
  3752. const da = vnode.component.da;
  3753. da && queuePostRenderEffect(da, suspense);
  3754. return;
  3755. }
  3756. unmount(cached);
  3757. });
  3758. });
  3759. return () => {
  3760. pendingCacheKey = null;
  3761. if (!slots.default) {
  3762. return null;
  3763. }
  3764. const children = slots.default();
  3765. const rawVNode = children[0];
  3766. if (children.length > 1) {
  3767. {
  3768. warn(`KeepAlive should contain exactly one component child.`);
  3769. }
  3770. current = null;
  3771. return children;
  3772. }
  3773. else if (!isVNode(rawVNode) ||
  3774. (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
  3775. !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
  3776. current = null;
  3777. return rawVNode;
  3778. }
  3779. let vnode = getInnerChild(rawVNode);
  3780. const comp = vnode.type;
  3781. const name = getComponentName(comp);
  3782. const { include, exclude, max } = props;
  3783. if ((include && (!name || !matches(include, name))) ||
  3784. (exclude && name && matches(exclude, name))) {
  3785. current = vnode;
  3786. return rawVNode;
  3787. }
  3788. const key = vnode.key == null ? comp : vnode.key;
  3789. const cachedVNode = cache.get(key);
  3790. // clone vnode if it's reused because we are going to mutate it
  3791. if (vnode.el) {
  3792. vnode = cloneVNode(vnode);
  3793. if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
  3794. rawVNode.ssContent = vnode;
  3795. }
  3796. }
  3797. // #1513 it's possible for the returned vnode to be cloned due to attr
  3798. // fallthrough or scopeId, so the vnode here may not be the final vnode
  3799. // that is mounted. Instead of caching it directly, we store the pending
  3800. // key and cache `instance.subTree` (the normalized vnode) in
  3801. // beforeMount/beforeUpdate hooks.
  3802. pendingCacheKey = key;
  3803. if (cachedVNode) {
  3804. // copy over mounted state
  3805. vnode.el = cachedVNode.el;
  3806. vnode.component = cachedVNode.component;
  3807. if (vnode.transition) {
  3808. // recursively update transition hooks on subTree
  3809. setTransitionHooks(vnode, vnode.transition);
  3810. }
  3811. // avoid vnode being mounted as fresh
  3812. vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
  3813. // make this key the freshest
  3814. keys.delete(key);
  3815. keys.add(key);
  3816. }
  3817. else {
  3818. keys.add(key);
  3819. // prune oldest entry
  3820. if (max && keys.size > parseInt(max, 10)) {
  3821. pruneCacheEntry(keys.values().next().value);
  3822. }
  3823. }
  3824. // avoid vnode being unmounted
  3825. vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
  3826. current = vnode;
  3827. return rawVNode;
  3828. };
  3829. }
  3830. };
  3831. // export the public type for h/tsx inference
  3832. // also to avoid inline import() in generated d.ts files
  3833. const KeepAlive = KeepAliveImpl;
  3834. function matches(pattern, name) {
  3835. if (isArray(pattern)) {
  3836. return pattern.some((p) => matches(p, name));
  3837. }
  3838. else if (isString(pattern)) {
  3839. return pattern.split(',').indexOf(name) > -1;
  3840. }
  3841. else if (pattern.test) {
  3842. return pattern.test(name);
  3843. }
  3844. /* istanbul ignore next */
  3845. return false;
  3846. }
  3847. function onActivated(hook, target) {
  3848. registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
  3849. }
  3850. function onDeactivated(hook, target) {
  3851. registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
  3852. }
  3853. function registerKeepAliveHook(hook, type, target = currentInstance) {
  3854. // cache the deactivate branch check wrapper for injected hooks so the same
  3855. // hook can be properly deduped by the scheduler. "__wdc" stands for "with
  3856. // deactivation check".
  3857. const wrappedHook = hook.__wdc ||
  3858. (hook.__wdc = () => {
  3859. // only fire the hook if the target instance is NOT in a deactivated branch.
  3860. let current = target;
  3861. while (current) {
  3862. if (current.isDeactivated) {
  3863. return;
  3864. }
  3865. current = current.parent;
  3866. }
  3867. hook();
  3868. });
  3869. injectHook(type, wrappedHook, target);
  3870. // In addition to registering it on the target instance, we walk up the parent
  3871. // chain and register it on all ancestor instances that are keep-alive roots.
  3872. // This avoids the need to walk the entire component tree when invoking these
  3873. // hooks, and more importantly, avoids the need to track child components in
  3874. // arrays.
  3875. if (target) {
  3876. let current = target.parent;
  3877. while (current && current.parent) {
  3878. if (isKeepAlive(current.parent.vnode)) {
  3879. injectToKeepAliveRoot(wrappedHook, type, target, current);
  3880. }
  3881. current = current.parent;
  3882. }
  3883. }
  3884. }
  3885. function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
  3886. // injectHook wraps the original for error handling, so make sure to remove
  3887. // the wrapped version.
  3888. const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
  3889. onUnmounted(() => {
  3890. remove(keepAliveRoot[type], injected);
  3891. }, target);
  3892. }
  3893. function resetShapeFlag(vnode) {
  3894. let shapeFlag = vnode.shapeFlag;
  3895. if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
  3896. shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
  3897. }
  3898. if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
  3899. shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
  3900. }
  3901. vnode.shapeFlag = shapeFlag;
  3902. }
  3903. function getInnerChild(vnode) {
  3904. return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
  3905. }
  3906. const isInternalKey = (key) => key[0] === '_' || key === '$stable';
  3907. const normalizeSlotValue = (value) => isArray(value)
  3908. ? value.map(normalizeVNode)
  3909. : [normalizeVNode(value)];
  3910. const normalizeSlot = (key, rawSlot, ctx) => withCtx((props) => {
  3911. if (currentInstance) {
  3912. warn(`Slot "${key}" invoked outside of the render function: ` +
  3913. `this will not track dependencies used in the slot. ` +
  3914. `Invoke the slot function inside the render function instead.`);
  3915. }
  3916. return normalizeSlotValue(rawSlot(props));
  3917. }, ctx);
  3918. const normalizeObjectSlots = (rawSlots, slots) => {
  3919. const ctx = rawSlots._ctx;
  3920. for (const key in rawSlots) {
  3921. if (isInternalKey(key))
  3922. continue;
  3923. const value = rawSlots[key];
  3924. if (isFunction(value)) {
  3925. slots[key] = normalizeSlot(key, value, ctx);
  3926. }
  3927. else if (value != null) {
  3928. {
  3929. warn(`Non-function value encountered for slot "${key}". ` +
  3930. `Prefer function slots for better performance.`);
  3931. }
  3932. const normalized = normalizeSlotValue(value);
  3933. slots[key] = () => normalized;
  3934. }
  3935. }
  3936. };
  3937. const normalizeVNodeSlots = (instance, children) => {
  3938. if (!isKeepAlive(instance.vnode)) {
  3939. warn(`Non-function value encountered for default slot. ` +
  3940. `Prefer function slots for better performance.`);
  3941. }
  3942. const normalized = normalizeSlotValue(children);
  3943. instance.slots.default = () => normalized;
  3944. };
  3945. const initSlots = (instance, children) => {
  3946. if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
  3947. const type = children._;
  3948. if (type) {
  3949. instance.slots = children;
  3950. // make compiler marker non-enumerable
  3951. def(children, '_', type);
  3952. }
  3953. else {
  3954. normalizeObjectSlots(children, (instance.slots = {}));
  3955. }
  3956. }
  3957. else {
  3958. instance.slots = {};
  3959. if (children) {
  3960. normalizeVNodeSlots(instance, children);
  3961. }
  3962. }
  3963. def(instance.slots, InternalObjectKey, 1);
  3964. };
  3965. const updateSlots = (instance, children) => {
  3966. const { vnode, slots } = instance;
  3967. let needDeletionCheck = true;
  3968. let deletionComparisonTarget = EMPTY_OBJ;
  3969. if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
  3970. const type = children._;
  3971. if (type) {
  3972. // compiled slots.
  3973. if (isHmrUpdating) {
  3974. // Parent was HMR updated so slot content may have changed.
  3975. // force update slots and mark instance for hmr as well
  3976. extend(slots, children);
  3977. }
  3978. else if (type === 1 /* STABLE */) {
  3979. // compiled AND stable.
  3980. // no need to update, and skip stale slots removal.
  3981. needDeletionCheck = false;
  3982. }
  3983. else {
  3984. // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
  3985. // normalization.
  3986. extend(slots, children);
  3987. }
  3988. }
  3989. else {
  3990. needDeletionCheck = !children.$stable;
  3991. normalizeObjectSlots(children, slots);
  3992. }
  3993. deletionComparisonTarget = children;
  3994. }
  3995. else if (children) {
  3996. // non slot object children (direct value) passed to a component
  3997. normalizeVNodeSlots(instance, children);
  3998. deletionComparisonTarget = { default: 1 };
  3999. }
  4000. // delete stale slots
  4001. if (needDeletionCheck) {
  4002. for (const key in slots) {
  4003. if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
  4004. delete slots[key];
  4005. }
  4006. }
  4007. }
  4008. };
  4009. /**
  4010. Runtime helper for applying directives to a vnode. Example usage:
  4011. const comp = resolveComponent('comp')
  4012. const foo = resolveDirective('foo')
  4013. const bar = resolveDirective('bar')
  4014. return withDirectives(h(comp), [
  4015. [foo, this.x],
  4016. [bar, this.y]
  4017. ])
  4018. */
  4019. const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text');
  4020. function validateDirectiveName(name) {
  4021. if (isBuiltInDirective(name)) {
  4022. warn('Do not use built-in directive ids as custom directive id: ' + name);
  4023. }
  4024. }
  4025. /**
  4026. * Adds directives to a VNode.
  4027. */
  4028. function withDirectives(vnode, directives) {
  4029. const internalInstance = currentRenderingInstance;
  4030. if (internalInstance === null) {
  4031. warn(`withDirectives can only be used inside render functions.`);
  4032. return vnode;
  4033. }
  4034. const instance = internalInstance.proxy;
  4035. const bindings = vnode.dirs || (vnode.dirs = []);
  4036. for (let i = 0; i < directives.length; i++) {
  4037. let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
  4038. if (isFunction(dir)) {
  4039. dir = {
  4040. mounted: dir,
  4041. updated: dir
  4042. };
  4043. }
  4044. bindings.push({
  4045. dir,
  4046. instance,
  4047. value,
  4048. oldValue: void 0,
  4049. arg,
  4050. modifiers
  4051. });
  4052. }
  4053. return vnode;
  4054. }
  4055. function invokeDirectiveHook(vnode, prevVNode, instance, name) {
  4056. const bindings = vnode.dirs;
  4057. const oldBindings = prevVNode && prevVNode.dirs;
  4058. for (let i = 0; i < bindings.length; i++) {
  4059. const binding = bindings[i];
  4060. if (oldBindings) {
  4061. binding.oldValue = oldBindings[i].value;
  4062. }
  4063. const hook = binding.dir[name];
  4064. if (hook) {
  4065. callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
  4066. vnode.el,
  4067. binding,
  4068. vnode,
  4069. prevVNode
  4070. ]);
  4071. }
  4072. }
  4073. }
  4074. function createAppContext() {
  4075. return {
  4076. app: null,
  4077. config: {
  4078. isNativeTag: NO,
  4079. performance: false,
  4080. globalProperties: {},
  4081. optionMergeStrategies: {},
  4082. isCustomElement: NO,
  4083. errorHandler: undefined,
  4084. warnHandler: undefined
  4085. },
  4086. mixins: [],
  4087. components: {},
  4088. directives: {},
  4089. provides: Object.create(null)
  4090. };
  4091. }
  4092. let uid$1 = 0;
  4093. function createAppAPI(render, hydrate) {
  4094. return function createApp(rootComponent, rootProps = null) {
  4095. if (rootProps != null && !isObject(rootProps)) {
  4096. warn(`root props passed to app.mount() must be an object.`);
  4097. rootProps = null;
  4098. }
  4099. const context = createAppContext();
  4100. const installedPlugins = new Set();
  4101. let isMounted = false;
  4102. const app = (context.app = {
  4103. _uid: uid$1++,
  4104. _component: rootComponent,
  4105. _props: rootProps,
  4106. _container: null,
  4107. _context: context,
  4108. version,
  4109. get config() {
  4110. return context.config;
  4111. },
  4112. set config(v) {
  4113. {
  4114. warn(`app.config cannot be replaced. Modify individual options instead.`);
  4115. }
  4116. },
  4117. use(plugin, ...options) {
  4118. if (installedPlugins.has(plugin)) {
  4119. warn(`Plugin has already been applied to target app.`);
  4120. }
  4121. else if (plugin && isFunction(plugin.install)) {
  4122. installedPlugins.add(plugin);
  4123. plugin.install(app, ...options);
  4124. }
  4125. else if (isFunction(plugin)) {
  4126. installedPlugins.add(plugin);
  4127. plugin(app, ...options);
  4128. }
  4129. else {
  4130. warn(`A plugin must either be a function or an object with an "install" ` +
  4131. `function.`);
  4132. }
  4133. return app;
  4134. },
  4135. mixin(mixin) {
  4136. {
  4137. if (!context.mixins.includes(mixin)) {
  4138. context.mixins.push(mixin);
  4139. // global mixin with props/emits de-optimizes props/emits
  4140. // normalization caching.
  4141. if (mixin.props || mixin.emits) {
  4142. context.deopt = true;
  4143. }
  4144. }
  4145. else {
  4146. warn('Mixin has already been applied to target app' +
  4147. (mixin.name ? `: ${mixin.name}` : ''));
  4148. }
  4149. }
  4150. return app;
  4151. },
  4152. component(name, component) {
  4153. {
  4154. validateComponentName(name, context.config);
  4155. }
  4156. if (!component) {
  4157. return context.components[name];
  4158. }
  4159. if (context.components[name]) {
  4160. warn(`Component "${name}" has already been registered in target app.`);
  4161. }
  4162. context.components[name] = component;
  4163. return app;
  4164. },
  4165. directive(name, directive) {
  4166. {
  4167. validateDirectiveName(name);
  4168. }
  4169. if (!directive) {
  4170. return context.directives[name];
  4171. }
  4172. if (context.directives[name]) {
  4173. warn(`Directive "${name}" has already been registered in target app.`);
  4174. }
  4175. context.directives[name] = directive;
  4176. return app;
  4177. },
  4178. mount(rootContainer, isHydrate) {
  4179. if (!isMounted) {
  4180. const vnode = createVNode(rootComponent, rootProps);
  4181. // store app context on the root VNode.
  4182. // this will be set on the root instance on initial mount.
  4183. vnode.appContext = context;
  4184. // HMR root reload
  4185. {
  4186. context.reload = () => {
  4187. render(cloneVNode(vnode), rootContainer);
  4188. };
  4189. }
  4190. if (isHydrate && hydrate) {
  4191. hydrate(vnode, rootContainer);
  4192. }
  4193. else {
  4194. render(vnode, rootContainer);
  4195. }
  4196. isMounted = true;
  4197. app._container = rootContainer;
  4198. rootContainer.__vue_app__ = app;
  4199. {
  4200. devtoolsInitApp(app, version);
  4201. }
  4202. return vnode.component.proxy;
  4203. }
  4204. else {
  4205. warn(`App has already been mounted.\n` +
  4206. `If you want to remount the same app, move your app creation logic ` +
  4207. `into a factory function and create fresh app instances for each ` +
  4208. `mount - e.g. \`const createMyApp = () => createApp(App)\``);
  4209. }
  4210. },
  4211. unmount() {
  4212. if (isMounted) {
  4213. render(null, app._container);
  4214. {
  4215. devtoolsUnmountApp(app);
  4216. }
  4217. delete app._container.__vue_app__;
  4218. }
  4219. else {
  4220. warn(`Cannot unmount an app that is not mounted.`);
  4221. }
  4222. },
  4223. provide(key, value) {
  4224. if (key in context.provides) {
  4225. warn(`App already provides property with key "${String(key)}". ` +
  4226. `It will be overwritten with the new value.`);
  4227. }
  4228. // TypeScript doesn't allow symbols as index type
  4229. // https://github.com/Microsoft/TypeScript/issues/24587
  4230. context.provides[key] = value;
  4231. return app;
  4232. }
  4233. });
  4234. return app;
  4235. };
  4236. }
  4237. let hasMismatch = false;
  4238. const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
  4239. const isComment = (node) => node.nodeType === 8 /* COMMENT */;
  4240. // Note: hydration is DOM-specific
  4241. // But we have to place it in core due to tight coupling with core - splitting
  4242. // it out creates a ton of unnecessary complexity.
  4243. // Hydration also depends on some renderer internal logic which needs to be
  4244. // passed in via arguments.
  4245. function createHydrationFunctions(rendererInternals) {
  4246. const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
  4247. const hydrate = (vnode, container) => {
  4248. if (!container.hasChildNodes()) {
  4249. warn(`Attempting to hydrate existing markup but container is empty. ` +
  4250. `Performing full mount instead.`);
  4251. patch(null, vnode, container);
  4252. return;
  4253. }
  4254. hasMismatch = false;
  4255. hydrateNode(container.firstChild, vnode, null, null);
  4256. flushPostFlushCbs();
  4257. if (hasMismatch && !false) {
  4258. // this error should show up in production
  4259. console.error(`Hydration completed but contains mismatches.`);
  4260. }
  4261. };
  4262. const hydrateNode = (node, vnode, parentComponent, parentSuspense, optimized = false) => {
  4263. const isFragmentStart = isComment(node) && node.data === '[';
  4264. const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, isFragmentStart);
  4265. const { type, ref, shapeFlag } = vnode;
  4266. const domType = node.nodeType;
  4267. vnode.el = node;
  4268. let nextNode = null;
  4269. switch (type) {
  4270. case Text:
  4271. if (domType !== 3 /* TEXT */) {
  4272. nextNode = onMismatch();
  4273. }
  4274. else {
  4275. if (node.data !== vnode.children) {
  4276. hasMismatch = true;
  4277. warn(`Hydration text mismatch:` +
  4278. `\n- Client: ${JSON.stringify(node.data)}` +
  4279. `\n- Server: ${JSON.stringify(vnode.children)}`);
  4280. node.data = vnode.children;
  4281. }
  4282. nextNode = nextSibling(node);
  4283. }
  4284. break;
  4285. case Comment:
  4286. if (domType !== 8 /* COMMENT */ || isFragmentStart) {
  4287. nextNode = onMismatch();
  4288. }
  4289. else {
  4290. nextNode = nextSibling(node);
  4291. }
  4292. break;
  4293. case Static:
  4294. if (domType !== 1 /* ELEMENT */) {
  4295. nextNode = onMismatch();
  4296. }
  4297. else {
  4298. // determine anchor, adopt content
  4299. nextNode = node;
  4300. // if the static vnode has its content stripped during build,
  4301. // adopt it from the server-rendered HTML.
  4302. const needToAdoptContent = !vnode.children.length;
  4303. for (let i = 0; i < vnode.staticCount; i++) {
  4304. if (needToAdoptContent)
  4305. vnode.children += nextNode.outerHTML;
  4306. if (i === vnode.staticCount - 1) {
  4307. vnode.anchor = nextNode;
  4308. }
  4309. nextNode = nextSibling(nextNode);
  4310. }
  4311. return nextNode;
  4312. }
  4313. break;
  4314. case Fragment:
  4315. if (!isFragmentStart) {
  4316. nextNode = onMismatch();
  4317. }
  4318. else {
  4319. nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, optimized);
  4320. }
  4321. break;
  4322. default:
  4323. if (shapeFlag & 1 /* ELEMENT */) {
  4324. if (domType !== 1 /* ELEMENT */ ||
  4325. vnode.type !== node.tagName.toLowerCase()) {
  4326. nextNode = onMismatch();
  4327. }
  4328. else {
  4329. nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, optimized);
  4330. }
  4331. }
  4332. else if (shapeFlag & 6 /* COMPONENT */) {
  4333. // when setting up the render effect, if the initial vnode already
  4334. // has .el set, the component will perform hydration instead of mount
  4335. // on its sub-tree.
  4336. const container = parentNode(node);
  4337. const hydrateComponent = () => {
  4338. mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
  4339. };
  4340. // async component
  4341. const loadAsync = vnode.type.__asyncLoader;
  4342. if (loadAsync) {
  4343. loadAsync().then(hydrateComponent);
  4344. }
  4345. else {
  4346. hydrateComponent();
  4347. }
  4348. // component may be async, so in the case of fragments we cannot rely
  4349. // on component's rendered output to determine the end of the fragment
  4350. // instead, we do a lookahead to find the end anchor node.
  4351. nextNode = isFragmentStart
  4352. ? locateClosingAsyncAnchor(node)
  4353. : nextSibling(node);
  4354. }
  4355. else if (shapeFlag & 64 /* TELEPORT */) {
  4356. if (domType !== 8 /* COMMENT */) {
  4357. nextNode = onMismatch();
  4358. }
  4359. else {
  4360. nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, optimized, rendererInternals, hydrateChildren);
  4361. }
  4362. }
  4363. else if (shapeFlag & 128 /* SUSPENSE */) {
  4364. nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), optimized, rendererInternals, hydrateNode);
  4365. }
  4366. else {
  4367. warn('Invalid HostVNode type:', type, `(${typeof type})`);
  4368. }
  4369. }
  4370. if (ref != null) {
  4371. setRef(ref, null, parentSuspense, vnode);
  4372. }
  4373. return nextNode;
  4374. };
  4375. const hydrateElement = (el, vnode, parentComponent, parentSuspense, optimized) => {
  4376. optimized = optimized || !!vnode.dynamicChildren;
  4377. const { props, patchFlag, shapeFlag, dirs } = vnode;
  4378. // skip props & children if this is hoisted static nodes
  4379. if (patchFlag !== -1 /* HOISTED */) {
  4380. if (dirs) {
  4381. invokeDirectiveHook(vnode, null, parentComponent, 'created');
  4382. }
  4383. // props
  4384. if (props) {
  4385. if (!optimized ||
  4386. (patchFlag & 16 /* FULL_PROPS */ ||
  4387. patchFlag & 32 /* HYDRATE_EVENTS */)) {
  4388. for (const key in props) {
  4389. if (!isReservedProp(key) && isOn(key)) {
  4390. patchProp(el, key, null, props[key]);
  4391. }
  4392. }
  4393. }
  4394. else if (props.onClick) {
  4395. // Fast path for click listeners (which is most often) to avoid
  4396. // iterating through props.
  4397. patchProp(el, 'onClick', null, props.onClick);
  4398. }
  4399. }
  4400. // vnode / directive hooks
  4401. let vnodeHooks;
  4402. if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
  4403. invokeVNodeHook(vnodeHooks, parentComponent, vnode);
  4404. }
  4405. if (dirs) {
  4406. invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
  4407. }
  4408. if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
  4409. queueEffectWithSuspense(() => {
  4410. vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
  4411. dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
  4412. }, parentSuspense);
  4413. }
  4414. // children
  4415. if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
  4416. // skip if element has innerHTML / textContent
  4417. !(props && (props.innerHTML || props.textContent))) {
  4418. let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, optimized);
  4419. let hasWarned = false;
  4420. while (next) {
  4421. hasMismatch = true;
  4422. if (!hasWarned) {
  4423. warn(`Hydration children mismatch in <${vnode.type}>: ` +
  4424. `server rendered element contains more child nodes than client vdom.`);
  4425. hasWarned = true;
  4426. }
  4427. // The SSRed DOM contains more nodes than it should. Remove them.
  4428. const cur = next;
  4429. next = next.nextSibling;
  4430. remove(cur);
  4431. }
  4432. }
  4433. else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
  4434. if (el.textContent !== vnode.children) {
  4435. hasMismatch = true;
  4436. warn(`Hydration text content mismatch in <${vnode.type}>:\n` +
  4437. `- Client: ${el.textContent}\n` +
  4438. `- Server: ${vnode.children}`);
  4439. el.textContent = vnode.children;
  4440. }
  4441. }
  4442. }
  4443. return el.nextSibling;
  4444. };
  4445. const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, optimized) => {
  4446. optimized = optimized || !!parentVNode.dynamicChildren;
  4447. const children = parentVNode.children;
  4448. const l = children.length;
  4449. let hasWarned = false;
  4450. for (let i = 0; i < l; i++) {
  4451. const vnode = optimized
  4452. ? children[i]
  4453. : (children[i] = normalizeVNode(children[i]));
  4454. if (node) {
  4455. node = hydrateNode(node, vnode, parentComponent, parentSuspense, optimized);
  4456. }
  4457. else {
  4458. hasMismatch = true;
  4459. if (!hasWarned) {
  4460. warn(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
  4461. `server rendered element contains fewer child nodes than client vdom.`);
  4462. hasWarned = true;
  4463. }
  4464. // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
  4465. patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container));
  4466. }
  4467. }
  4468. return node;
  4469. };
  4470. const hydrateFragment = (node, vnode, parentComponent, parentSuspense, optimized) => {
  4471. const container = parentNode(node);
  4472. const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, optimized);
  4473. if (next && isComment(next) && next.data === ']') {
  4474. return nextSibling((vnode.anchor = next));
  4475. }
  4476. else {
  4477. // fragment didn't hydrate successfully, since we didn't get a end anchor
  4478. // back. This should have led to node/children mismatch warnings.
  4479. hasMismatch = true;
  4480. // since the anchor is missing, we need to create one and insert it
  4481. insert((vnode.anchor = createComment(`]`)), container, next);
  4482. return next;
  4483. }
  4484. };
  4485. const handleMismatch = (node, vnode, parentComponent, parentSuspense, isFragment) => {
  4486. hasMismatch = true;
  4487. warn(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
  4488. ? `(text)`
  4489. : isComment(node) && node.data === '['
  4490. ? `(start of fragment)`
  4491. : ``);
  4492. vnode.el = null;
  4493. if (isFragment) {
  4494. // remove excessive fragment nodes
  4495. const end = locateClosingAsyncAnchor(node);
  4496. while (true) {
  4497. const next = nextSibling(node);
  4498. if (next && next !== end) {
  4499. remove(next);
  4500. }
  4501. else {
  4502. break;
  4503. }
  4504. }
  4505. }
  4506. const next = nextSibling(node);
  4507. const container = parentNode(node);
  4508. remove(node);
  4509. patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container));
  4510. return next;
  4511. };
  4512. const locateClosingAsyncAnchor = (node) => {
  4513. let match = 0;
  4514. while (node) {
  4515. node = nextSibling(node);
  4516. if (node && isComment(node)) {
  4517. if (node.data === '[')
  4518. match++;
  4519. if (node.data === ']') {
  4520. if (match === 0) {
  4521. return nextSibling(node);
  4522. }
  4523. else {
  4524. match--;
  4525. }
  4526. }
  4527. }
  4528. }
  4529. return node;
  4530. };
  4531. return [hydrate, hydrateNode];
  4532. }
  4533. let supported;
  4534. let perf;
  4535. function startMeasure(instance, type) {
  4536. if (instance.appContext.config.performance && isSupported()) {
  4537. perf.mark(`vue-${type}-${instance.uid}`);
  4538. }
  4539. }
  4540. function endMeasure(instance, type) {
  4541. if (instance.appContext.config.performance && isSupported()) {
  4542. const startTag = `vue-${type}-${instance.uid}`;
  4543. const endTag = startTag + `:end`;
  4544. perf.mark(endTag);
  4545. perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
  4546. perf.clearMarks(startTag);
  4547. perf.clearMarks(endTag);
  4548. }
  4549. }
  4550. function isSupported() {
  4551. if (supported !== undefined) {
  4552. return supported;
  4553. }
  4554. /* eslint-disable no-restricted-globals */
  4555. if (typeof window !== 'undefined' && window.performance) {
  4556. supported = true;
  4557. perf = window.performance;
  4558. }
  4559. else {
  4560. supported = false;
  4561. }
  4562. /* eslint-enable no-restricted-globals */
  4563. return supported;
  4564. }
  4565. // implementation, close to no-op
  4566. function defineComponent(options) {
  4567. return isFunction(options) ? { setup: options, name: options.name } : options;
  4568. }
  4569. const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
  4570. function defineAsyncComponent(source) {
  4571. if (isFunction(source)) {
  4572. source = { loader: source };
  4573. }
  4574. const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
  4575. suspensible = true, onError: userOnError } = source;
  4576. let pendingRequest = null;
  4577. let resolvedComp;
  4578. let retries = 0;
  4579. const retry = () => {
  4580. retries++;
  4581. pendingRequest = null;
  4582. return load();
  4583. };
  4584. const load = () => {
  4585. let thisRequest;
  4586. return (pendingRequest ||
  4587. (thisRequest = pendingRequest = loader()
  4588. .catch(err => {
  4589. err = err instanceof Error ? err : new Error(String(err));
  4590. if (userOnError) {
  4591. return new Promise((resolve, reject) => {
  4592. const userRetry = () => resolve(retry());
  4593. const userFail = () => reject(err);
  4594. userOnError(err, userRetry, userFail, retries + 1);
  4595. });
  4596. }
  4597. else {
  4598. throw err;
  4599. }
  4600. })
  4601. .then((comp) => {
  4602. if (thisRequest !== pendingRequest && pendingRequest) {
  4603. return pendingRequest;
  4604. }
  4605. if (!comp) {
  4606. warn(`Async component loader resolved to undefined. ` +
  4607. `If you are using retry(), make sure to return its return value.`);
  4608. }
  4609. // interop module default
  4610. if (comp &&
  4611. (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
  4612. comp = comp.default;
  4613. }
  4614. if (comp && !isObject(comp) && !isFunction(comp)) {
  4615. throw new Error(`Invalid async component load result: ${comp}`);
  4616. }
  4617. resolvedComp = comp;
  4618. return comp;
  4619. })));
  4620. };
  4621. return defineComponent({
  4622. __asyncLoader: load,
  4623. name: 'AsyncComponentWrapper',
  4624. setup() {
  4625. const instance = currentInstance;
  4626. // already resolved
  4627. if (resolvedComp) {
  4628. return () => createInnerComp(resolvedComp, instance);
  4629. }
  4630. const onError = (err) => {
  4631. pendingRequest = null;
  4632. handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
  4633. };
  4634. // suspense-controlled or SSR.
  4635. if ((suspensible && instance.suspense) ||
  4636. (false )) {
  4637. return load()
  4638. .then(comp => {
  4639. return () => createInnerComp(comp, instance);
  4640. })
  4641. .catch(err => {
  4642. onError(err);
  4643. return () => errorComponent
  4644. ? createVNode(errorComponent, {
  4645. error: err
  4646. })
  4647. : null;
  4648. });
  4649. }
  4650. const loaded = ref(false);
  4651. const error = ref();
  4652. const delayed = ref(!!delay);
  4653. if (delay) {
  4654. setTimeout(() => {
  4655. delayed.value = false;
  4656. }, delay);
  4657. }
  4658. if (timeout != null) {
  4659. setTimeout(() => {
  4660. if (!loaded.value && !error.value) {
  4661. const err = new Error(`Async component timed out after ${timeout}ms.`);
  4662. onError(err);
  4663. error.value = err;
  4664. }
  4665. }, timeout);
  4666. }
  4667. load()
  4668. .then(() => {
  4669. loaded.value = true;
  4670. })
  4671. .catch(err => {
  4672. onError(err);
  4673. error.value = err;
  4674. });
  4675. return () => {
  4676. if (loaded.value && resolvedComp) {
  4677. return createInnerComp(resolvedComp, instance);
  4678. }
  4679. else if (error.value && errorComponent) {
  4680. return createVNode(errorComponent, {
  4681. error: error.value
  4682. });
  4683. }
  4684. else if (loadingComponent && !delayed.value) {
  4685. return createVNode(loadingComponent);
  4686. }
  4687. };
  4688. }
  4689. });
  4690. }
  4691. function createInnerComp(comp, { vnode: { ref, props, children } }) {
  4692. const vnode = createVNode(comp, props, children);
  4693. // ensure inner component inherits the async wrapper's ref owner
  4694. vnode.ref = ref;
  4695. return vnode;
  4696. }
  4697. function createDevEffectOptions(instance) {
  4698. return {
  4699. scheduler: queueJob,
  4700. allowRecurse: true,
  4701. onTrack: instance.rtc ? e => invokeArrayFns(instance.rtc, e) : void 0,
  4702. onTrigger: instance.rtg ? e => invokeArrayFns(instance.rtg, e) : void 0
  4703. };
  4704. }
  4705. const queuePostRenderEffect = queueEffectWithSuspense
  4706. ;
  4707. const setRef = (rawRef, oldRawRef, parentSuspense, vnode) => {
  4708. if (isArray(rawRef)) {
  4709. rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode));
  4710. return;
  4711. }
  4712. let value;
  4713. if (!vnode || isAsyncWrapper(vnode)) {
  4714. value = null;
  4715. }
  4716. else {
  4717. if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
  4718. value = vnode.component.exposed || vnode.component.proxy;
  4719. }
  4720. else {
  4721. value = vnode.el;
  4722. }
  4723. }
  4724. const { i: owner, r: ref } = rawRef;
  4725. if (!owner) {
  4726. warn(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
  4727. `A vnode with ref must be created inside the render function.`);
  4728. return;
  4729. }
  4730. const oldRef = oldRawRef && oldRawRef.r;
  4731. const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
  4732. const setupState = owner.setupState;
  4733. // unset old ref
  4734. if (oldRef != null && oldRef !== ref) {
  4735. if (isString(oldRef)) {
  4736. refs[oldRef] = null;
  4737. if (hasOwn(setupState, oldRef)) {
  4738. setupState[oldRef] = null;
  4739. }
  4740. }
  4741. else if (isRef(oldRef)) {
  4742. oldRef.value = null;
  4743. }
  4744. }
  4745. if (isString(ref)) {
  4746. const doSet = () => {
  4747. refs[ref] = value;
  4748. if (hasOwn(setupState, ref)) {
  4749. setupState[ref] = value;
  4750. }
  4751. };
  4752. // #1789: for non-null values, set them after render
  4753. // null values means this is unmount and it should not overwrite another
  4754. // ref with the same key
  4755. if (value) {
  4756. doSet.id = -1;
  4757. queuePostRenderEffect(doSet, parentSuspense);
  4758. }
  4759. else {
  4760. doSet();
  4761. }
  4762. }
  4763. else if (isRef(ref)) {
  4764. const doSet = () => {
  4765. ref.value = value;
  4766. };
  4767. if (value) {
  4768. doSet.id = -1;
  4769. queuePostRenderEffect(doSet, parentSuspense);
  4770. }
  4771. else {
  4772. doSet();
  4773. }
  4774. }
  4775. else if (isFunction(ref)) {
  4776. callWithErrorHandling(ref, owner, 12 /* FUNCTION_REF */, [value, refs]);
  4777. }
  4778. else {
  4779. warn('Invalid template ref type:', value, `(${typeof value})`);
  4780. }
  4781. };
  4782. /**
  4783. * The createRenderer function accepts two generic arguments:
  4784. * HostNode and HostElement, corresponding to Node and Element types in the
  4785. * host environment. For example, for runtime-dom, HostNode would be the DOM
  4786. * `Node` interface and HostElement would be the DOM `Element` interface.
  4787. *
  4788. * Custom renderers can pass in the platform specific types like this:
  4789. *
  4790. * ``` js
  4791. * const { render, createApp } = createRenderer<Node, Element>({
  4792. * patchProp,
  4793. * ...nodeOps
  4794. * })
  4795. * ```
  4796. */
  4797. function createRenderer(options) {
  4798. return baseCreateRenderer(options);
  4799. }
  4800. // Separate API for creating hydration-enabled renderer.
  4801. // Hydration logic is only used when calling this function, making it
  4802. // tree-shakable.
  4803. function createHydrationRenderer(options) {
  4804. return baseCreateRenderer(options, createHydrationFunctions);
  4805. }
  4806. // implementation
  4807. function baseCreateRenderer(options, createHydrationFns) {
  4808. const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, forcePatchProp: hostForcePatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, cloneNode: hostCloneNode, insertStaticContent: hostInsertStaticContent } = options;
  4809. // Note: functions inside this closure should use `const xxx = () => {}`
  4810. // style in order to prevent being inlined by minifiers.
  4811. const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, optimized = false) => {
  4812. // patching & not same type, unmount old tree
  4813. if (n1 && !isSameVNodeType(n1, n2)) {
  4814. anchor = getNextHostNode(n1);
  4815. unmount(n1, parentComponent, parentSuspense, true);
  4816. n1 = null;
  4817. }
  4818. if (n2.patchFlag === -2 /* BAIL */) {
  4819. optimized = false;
  4820. n2.dynamicChildren = null;
  4821. }
  4822. const { type, ref, shapeFlag } = n2;
  4823. switch (type) {
  4824. case Text:
  4825. processText(n1, n2, container, anchor);
  4826. break;
  4827. case Comment:
  4828. processCommentNode(n1, n2, container, anchor);
  4829. break;
  4830. case Static:
  4831. if (n1 == null) {
  4832. mountStaticNode(n2, container, anchor, isSVG);
  4833. }
  4834. else {
  4835. patchStaticNode(n1, n2, container, isSVG);
  4836. }
  4837. break;
  4838. case Fragment:
  4839. processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  4840. break;
  4841. default:
  4842. if (shapeFlag & 1 /* ELEMENT */) {
  4843. processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  4844. }
  4845. else if (shapeFlag & 6 /* COMPONENT */) {
  4846. processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  4847. }
  4848. else if (shapeFlag & 64 /* TELEPORT */) {
  4849. type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, internals);
  4850. }
  4851. else if (shapeFlag & 128 /* SUSPENSE */) {
  4852. type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, internals);
  4853. }
  4854. else {
  4855. warn('Invalid VNode type:', type, `(${typeof type})`);
  4856. }
  4857. }
  4858. // set ref
  4859. if (ref != null && parentComponent) {
  4860. setRef(ref, n1 && n1.ref, parentSuspense, n2);
  4861. }
  4862. };
  4863. const processText = (n1, n2, container, anchor) => {
  4864. if (n1 == null) {
  4865. hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
  4866. }
  4867. else {
  4868. const el = (n2.el = n1.el);
  4869. if (n2.children !== n1.children) {
  4870. hostSetText(el, n2.children);
  4871. }
  4872. }
  4873. };
  4874. const processCommentNode = (n1, n2, container, anchor) => {
  4875. if (n1 == null) {
  4876. hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
  4877. }
  4878. else {
  4879. // there's no support for dynamic comments
  4880. n2.el = n1.el;
  4881. }
  4882. };
  4883. const mountStaticNode = (n2, container, anchor, isSVG) => {
  4884. [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
  4885. };
  4886. /**
  4887. * Dev / HMR only
  4888. */
  4889. const patchStaticNode = (n1, n2, container, isSVG) => {
  4890. // static nodes are only patched during dev for HMR
  4891. if (n2.children !== n1.children) {
  4892. const anchor = hostNextSibling(n1.anchor);
  4893. // remove existing
  4894. removeStaticNode(n1);
  4895. [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
  4896. }
  4897. else {
  4898. n2.el = n1.el;
  4899. n2.anchor = n1.anchor;
  4900. }
  4901. };
  4902. const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
  4903. let next;
  4904. while (el && el !== anchor) {
  4905. next = hostNextSibling(el);
  4906. hostInsert(el, container, nextSibling);
  4907. el = next;
  4908. }
  4909. hostInsert(anchor, container, nextSibling);
  4910. };
  4911. const removeStaticNode = ({ el, anchor }) => {
  4912. let next;
  4913. while (el && el !== anchor) {
  4914. next = hostNextSibling(el);
  4915. hostRemove(el);
  4916. el = next;
  4917. }
  4918. hostRemove(anchor);
  4919. };
  4920. const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  4921. isSVG = isSVG || n2.type === 'svg';
  4922. if (n1 == null) {
  4923. mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  4924. }
  4925. else {
  4926. patchElement(n1, n2, parentComponent, parentSuspense, isSVG, optimized);
  4927. }
  4928. };
  4929. const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  4930. let el;
  4931. let vnodeHook;
  4932. const { type, props, shapeFlag, transition, scopeId, patchFlag, dirs } = vnode;
  4933. {
  4934. el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is);
  4935. // mount children first, since some props may rely on child content
  4936. // being already rendered, e.g. `<select value>`
  4937. if (shapeFlag & 8 /* TEXT_CHILDREN */) {
  4938. hostSetElementText(el, vnode.children);
  4939. }
  4940. else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  4941. mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', optimized || !!vnode.dynamicChildren);
  4942. }
  4943. if (dirs) {
  4944. invokeDirectiveHook(vnode, null, parentComponent, 'created');
  4945. }
  4946. // props
  4947. if (props) {
  4948. for (const key in props) {
  4949. if (!isReservedProp(key)) {
  4950. hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  4951. }
  4952. }
  4953. if ((vnodeHook = props.onVnodeBeforeMount)) {
  4954. invokeVNodeHook(vnodeHook, parentComponent, vnode);
  4955. }
  4956. }
  4957. // scopeId
  4958. setScopeId(el, scopeId, vnode, parentComponent);
  4959. }
  4960. {
  4961. Object.defineProperty(el, '__vnode', {
  4962. value: vnode,
  4963. enumerable: false
  4964. });
  4965. Object.defineProperty(el, '__vueParentComponent', {
  4966. value: parentComponent,
  4967. enumerable: false
  4968. });
  4969. }
  4970. if (dirs) {
  4971. invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
  4972. }
  4973. // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
  4974. // #1689 For inside suspense + suspense resolved case, just call it
  4975. const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
  4976. transition &&
  4977. !transition.persisted;
  4978. if (needCallTransitionHooks) {
  4979. transition.beforeEnter(el);
  4980. }
  4981. hostInsert(el, container, anchor);
  4982. if ((vnodeHook = props && props.onVnodeMounted) ||
  4983. needCallTransitionHooks ||
  4984. dirs) {
  4985. queuePostRenderEffect(() => {
  4986. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
  4987. needCallTransitionHooks && transition.enter(el);
  4988. dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
  4989. }, parentSuspense);
  4990. }
  4991. };
  4992. const setScopeId = (el, scopeId, vnode, parentComponent) => {
  4993. if (scopeId) {
  4994. hostSetScopeId(el, scopeId);
  4995. }
  4996. if (parentComponent) {
  4997. const treeOwnerId = parentComponent.type.__scopeId;
  4998. // vnode's own scopeId and the current patched component's scopeId is
  4999. // different - this is a slot content node.
  5000. if (treeOwnerId && treeOwnerId !== scopeId) {
  5001. hostSetScopeId(el, treeOwnerId + '-s');
  5002. }
  5003. let subTree = parentComponent.subTree;
  5004. if (subTree.type === Fragment) {
  5005. subTree =
  5006. filterSingleRoot(subTree.children) || subTree;
  5007. }
  5008. if (vnode === subTree) {
  5009. setScopeId(el, parentComponent.vnode.scopeId, parentComponent.vnode, parentComponent.parent);
  5010. }
  5011. }
  5012. };
  5013. const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, optimized, start = 0) => {
  5014. for (let i = start; i < children.length; i++) {
  5015. const child = (children[i] = optimized
  5016. ? cloneIfMounted(children[i])
  5017. : normalizeVNode(children[i]));
  5018. patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5019. }
  5020. };
  5021. const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, optimized) => {
  5022. const el = (n2.el = n1.el);
  5023. let { patchFlag, dynamicChildren, dirs } = n2;
  5024. // #1426 take the old vnode's patch flag into account since user may clone a
  5025. // compiler-generated vnode, which de-opts to FULL_PROPS
  5026. patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
  5027. const oldProps = n1.props || EMPTY_OBJ;
  5028. const newProps = n2.props || EMPTY_OBJ;
  5029. let vnodeHook;
  5030. if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
  5031. invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
  5032. }
  5033. if (dirs) {
  5034. invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
  5035. }
  5036. if (isHmrUpdating) {
  5037. // HMR updated, force full diff
  5038. patchFlag = 0;
  5039. optimized = false;
  5040. dynamicChildren = null;
  5041. }
  5042. if (patchFlag > 0) {
  5043. // the presence of a patchFlag means this element's render code was
  5044. // generated by the compiler and can take the fast path.
  5045. // in this path old node and new node are guaranteed to have the same shape
  5046. // (i.e. at the exact same position in the source template)
  5047. if (patchFlag & 16 /* FULL_PROPS */) {
  5048. // element props contain dynamic keys, full diff needed
  5049. patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
  5050. }
  5051. else {
  5052. // class
  5053. // this flag is matched when the element has dynamic class bindings.
  5054. if (patchFlag & 2 /* CLASS */) {
  5055. if (oldProps.class !== newProps.class) {
  5056. hostPatchProp(el, 'class', null, newProps.class, isSVG);
  5057. }
  5058. }
  5059. // style
  5060. // this flag is matched when the element has dynamic style bindings
  5061. if (patchFlag & 4 /* STYLE */) {
  5062. hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
  5063. }
  5064. // props
  5065. // This flag is matched when the element has dynamic prop/attr bindings
  5066. // other than class and style. The keys of dynamic prop/attrs are saved for
  5067. // faster iteration.
  5068. // Note dynamic keys like :[foo]="bar" will cause this optimization to
  5069. // bail out and go through a full diff because we need to unset the old key
  5070. if (patchFlag & 8 /* PROPS */) {
  5071. // if the flag is present then dynamicProps must be non-null
  5072. const propsToUpdate = n2.dynamicProps;
  5073. for (let i = 0; i < propsToUpdate.length; i++) {
  5074. const key = propsToUpdate[i];
  5075. const prev = oldProps[key];
  5076. const next = newProps[key];
  5077. if (next !== prev ||
  5078. (hostForcePatchProp && hostForcePatchProp(el, key))) {
  5079. hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
  5080. }
  5081. }
  5082. }
  5083. }
  5084. // text
  5085. // This flag is matched when the element has only dynamic text children.
  5086. if (patchFlag & 1 /* TEXT */) {
  5087. if (n1.children !== n2.children) {
  5088. hostSetElementText(el, n2.children);
  5089. }
  5090. }
  5091. }
  5092. else if (!optimized && dynamicChildren == null) {
  5093. // unoptimized, full diff
  5094. patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
  5095. }
  5096. const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
  5097. if (dynamicChildren) {
  5098. patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG);
  5099. if (parentComponent && parentComponent.type.__hmrId) {
  5100. traverseStaticChildren(n1, n2);
  5101. }
  5102. }
  5103. else if (!optimized) {
  5104. // full diff
  5105. patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG);
  5106. }
  5107. if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
  5108. queuePostRenderEffect(() => {
  5109. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
  5110. dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
  5111. }, parentSuspense);
  5112. }
  5113. };
  5114. // The fast path for blocks.
  5115. const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG) => {
  5116. for (let i = 0; i < newChildren.length; i++) {
  5117. const oldVNode = oldChildren[i];
  5118. const newVNode = newChildren[i];
  5119. // Determine the container (parent element) for the patch.
  5120. const container =
  5121. // - In the case of a Fragment, we need to provide the actual parent
  5122. // of the Fragment itself so it can move its children.
  5123. oldVNode.type === Fragment ||
  5124. // - In the case of different nodes, there is going to be a replacement
  5125. // which also requires the correct parent container
  5126. !isSameVNodeType(oldVNode, newVNode) ||
  5127. // - In the case of a component, it could contain anything.
  5128. oldVNode.shapeFlag & 6 /* COMPONENT */ ||
  5129. oldVNode.shapeFlag & 64 /* TELEPORT */
  5130. ? hostParentNode(oldVNode.el)
  5131. : // In other cases, the parent container is not actually used so we
  5132. // just pass the block element here to avoid a DOM parentNode call.
  5133. fallbackContainer;
  5134. patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, true);
  5135. }
  5136. };
  5137. const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
  5138. if (oldProps !== newProps) {
  5139. for (const key in newProps) {
  5140. // empty string is not valid prop
  5141. if (isReservedProp(key))
  5142. continue;
  5143. const next = newProps[key];
  5144. const prev = oldProps[key];
  5145. if (next !== prev ||
  5146. (hostForcePatchProp && hostForcePatchProp(el, key))) {
  5147. hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  5148. }
  5149. }
  5150. if (oldProps !== EMPTY_OBJ) {
  5151. for (const key in oldProps) {
  5152. if (!isReservedProp(key) && !(key in newProps)) {
  5153. hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  5154. }
  5155. }
  5156. }
  5157. }
  5158. };
  5159. const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  5160. const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
  5161. const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
  5162. let { patchFlag, dynamicChildren } = n2;
  5163. if (patchFlag > 0) {
  5164. optimized = true;
  5165. }
  5166. if (isHmrUpdating) {
  5167. // HMR updated, force full diff
  5168. patchFlag = 0;
  5169. optimized = false;
  5170. dynamicChildren = null;
  5171. }
  5172. if (n1 == null) {
  5173. hostInsert(fragmentStartAnchor, container, anchor);
  5174. hostInsert(fragmentEndAnchor, container, anchor);
  5175. // a fragment can only have array children
  5176. // since they are either generated by the compiler, or implicitly created
  5177. // from arrays.
  5178. mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, optimized);
  5179. }
  5180. else {
  5181. if (patchFlag > 0 &&
  5182. patchFlag & 64 /* STABLE_FRAGMENT */ &&
  5183. dynamicChildren &&
  5184. // #2715 the previous fragment could've been a BAILed one as a result
  5185. // of renderSlot() with no valid children
  5186. n1.dynamicChildren) {
  5187. // a stable fragment (template root or <template v-for>) doesn't need to
  5188. // patch children order, but it may contain dynamicChildren.
  5189. patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG);
  5190. if (parentComponent && parentComponent.type.__hmrId) {
  5191. traverseStaticChildren(n1, n2);
  5192. }
  5193. else if (
  5194. // #2080 if the stable fragment has a key, it's a <template v-for> that may
  5195. // get moved around. Make sure all root level vnodes inherit el.
  5196. // #2134 or if it's a component root, it may also get moved around
  5197. // as the component is being moved.
  5198. n2.key != null ||
  5199. (parentComponent && n2 === parentComponent.subTree)) {
  5200. traverseStaticChildren(n1, n2, true /* shallow */);
  5201. }
  5202. }
  5203. else {
  5204. // keyed / unkeyed, or manual fragments.
  5205. // for keyed & unkeyed, since they are compiler generated from v-for,
  5206. // each child is guaranteed to be a block so the fragment will never
  5207. // have dynamicChildren.
  5208. patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, optimized);
  5209. }
  5210. }
  5211. };
  5212. const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  5213. if (n1 == null) {
  5214. if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
  5215. parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
  5216. }
  5217. else {
  5218. mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5219. }
  5220. }
  5221. else {
  5222. updateComponent(n1, n2, optimized);
  5223. }
  5224. };
  5225. const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  5226. const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
  5227. if (instance.type.__hmrId) {
  5228. registerHMR(instance);
  5229. }
  5230. {
  5231. pushWarningContext(initialVNode);
  5232. startMeasure(instance, `mount`);
  5233. }
  5234. // inject renderer internals for keepAlive
  5235. if (isKeepAlive(initialVNode)) {
  5236. instance.ctx.renderer = internals;
  5237. }
  5238. // resolve props and slots for setup context
  5239. {
  5240. startMeasure(instance, `init`);
  5241. }
  5242. setupComponent(instance);
  5243. {
  5244. endMeasure(instance, `init`);
  5245. }
  5246. // setup() is async. This component relies on async logic to be resolved
  5247. // before proceeding
  5248. if (instance.asyncDep) {
  5249. parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
  5250. // Give it a placeholder if this is not hydration
  5251. // TODO handle self-defined fallback
  5252. if (!initialVNode.el) {
  5253. const placeholder = (instance.subTree = createVNode(Comment));
  5254. processCommentNode(null, placeholder, container, anchor);
  5255. }
  5256. return;
  5257. }
  5258. setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
  5259. {
  5260. popWarningContext();
  5261. endMeasure(instance, `mount`);
  5262. }
  5263. };
  5264. const updateComponent = (n1, n2, optimized) => {
  5265. const instance = (n2.component = n1.component);
  5266. if (shouldUpdateComponent(n1, n2, optimized)) {
  5267. if (instance.asyncDep &&
  5268. !instance.asyncResolved) {
  5269. // async & still pending - just update props and slots
  5270. // since the component's reactive effect for render isn't set-up yet
  5271. {
  5272. pushWarningContext(n2);
  5273. }
  5274. updateComponentPreRender(instance, n2, optimized);
  5275. {
  5276. popWarningContext();
  5277. }
  5278. return;
  5279. }
  5280. else {
  5281. // normal update
  5282. instance.next = n2;
  5283. // in case the child component is also queued, remove it to avoid
  5284. // double updating the same child component in the same flush.
  5285. invalidateJob(instance.update);
  5286. // instance.update is the reactive effect runner.
  5287. instance.update();
  5288. }
  5289. }
  5290. else {
  5291. // no update needed. just copy over properties
  5292. n2.component = n1.component;
  5293. n2.el = n1.el;
  5294. instance.vnode = n2;
  5295. }
  5296. };
  5297. const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
  5298. // create reactive effect for rendering
  5299. instance.update = effect(function componentEffect() {
  5300. if (!instance.isMounted) {
  5301. let vnodeHook;
  5302. const { el, props } = initialVNode;
  5303. const { bm, m, parent } = instance;
  5304. // beforeMount hook
  5305. if (bm) {
  5306. invokeArrayFns(bm);
  5307. }
  5308. // onVnodeBeforeMount
  5309. if ((vnodeHook = props && props.onVnodeBeforeMount)) {
  5310. invokeVNodeHook(vnodeHook, parent, initialVNode);
  5311. }
  5312. // render
  5313. {
  5314. startMeasure(instance, `render`);
  5315. }
  5316. const subTree = (instance.subTree = renderComponentRoot(instance));
  5317. {
  5318. endMeasure(instance, `render`);
  5319. }
  5320. if (el && hydrateNode) {
  5321. {
  5322. startMeasure(instance, `hydrate`);
  5323. }
  5324. // vnode has adopted host node - perform hydration instead of mount.
  5325. hydrateNode(initialVNode.el, subTree, instance, parentSuspense);
  5326. {
  5327. endMeasure(instance, `hydrate`);
  5328. }
  5329. }
  5330. else {
  5331. {
  5332. startMeasure(instance, `patch`);
  5333. }
  5334. patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
  5335. {
  5336. endMeasure(instance, `patch`);
  5337. }
  5338. initialVNode.el = subTree.el;
  5339. }
  5340. // mounted hook
  5341. if (m) {
  5342. queuePostRenderEffect(m, parentSuspense);
  5343. }
  5344. // onVnodeMounted
  5345. if ((vnodeHook = props && props.onVnodeMounted)) {
  5346. const scopedInitialVNode = initialVNode;
  5347. queuePostRenderEffect(() => {
  5348. invokeVNodeHook(vnodeHook, parent, scopedInitialVNode);
  5349. }, parentSuspense);
  5350. }
  5351. // activated hook for keep-alive roots.
  5352. // #1742 activated hook must be accessed after first render
  5353. // since the hook may be injected by a child keep-alive
  5354. const { a } = instance;
  5355. if (a &&
  5356. initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
  5357. queuePostRenderEffect(a, parentSuspense);
  5358. }
  5359. instance.isMounted = true;
  5360. {
  5361. devtoolsComponentAdded(instance);
  5362. }
  5363. // #2458: deference mount-only object parameters to prevent memleaks
  5364. initialVNode = container = anchor = null;
  5365. }
  5366. else {
  5367. // updateComponent
  5368. // This is triggered by mutation of component's own state (next: null)
  5369. // OR parent calling processComponent (next: VNode)
  5370. let { next, bu, u, parent, vnode } = instance;
  5371. let originNext = next;
  5372. let vnodeHook;
  5373. {
  5374. pushWarningContext(next || instance.vnode);
  5375. }
  5376. if (next) {
  5377. next.el = vnode.el;
  5378. updateComponentPreRender(instance, next, optimized);
  5379. }
  5380. else {
  5381. next = vnode;
  5382. }
  5383. // beforeUpdate hook
  5384. if (bu) {
  5385. invokeArrayFns(bu);
  5386. }
  5387. // onVnodeBeforeUpdate
  5388. if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
  5389. invokeVNodeHook(vnodeHook, parent, next, vnode);
  5390. }
  5391. // render
  5392. {
  5393. startMeasure(instance, `render`);
  5394. }
  5395. const nextTree = renderComponentRoot(instance);
  5396. {
  5397. endMeasure(instance, `render`);
  5398. }
  5399. const prevTree = instance.subTree;
  5400. instance.subTree = nextTree;
  5401. {
  5402. startMeasure(instance, `patch`);
  5403. }
  5404. patch(prevTree, nextTree,
  5405. // parent may have changed if it's in a teleport
  5406. hostParentNode(prevTree.el),
  5407. // anchor may have changed if it's in a fragment
  5408. getNextHostNode(prevTree), instance, parentSuspense, isSVG);
  5409. {
  5410. endMeasure(instance, `patch`);
  5411. }
  5412. next.el = nextTree.el;
  5413. if (originNext === null) {
  5414. // self-triggered update. In case of HOC, update parent component
  5415. // vnode el. HOC is indicated by parent instance's subTree pointing
  5416. // to child component's vnode
  5417. updateHOCHostEl(instance, nextTree.el);
  5418. }
  5419. // updated hook
  5420. if (u) {
  5421. queuePostRenderEffect(u, parentSuspense);
  5422. }
  5423. // onVnodeUpdated
  5424. if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
  5425. queuePostRenderEffect(() => {
  5426. invokeVNodeHook(vnodeHook, parent, next, vnode);
  5427. }, parentSuspense);
  5428. }
  5429. {
  5430. devtoolsComponentUpdated(instance);
  5431. }
  5432. {
  5433. popWarningContext();
  5434. }
  5435. }
  5436. }, createDevEffectOptions(instance) );
  5437. };
  5438. const updateComponentPreRender = (instance, nextVNode, optimized) => {
  5439. nextVNode.component = instance;
  5440. const prevProps = instance.vnode.props;
  5441. instance.vnode = nextVNode;
  5442. instance.next = null;
  5443. updateProps(instance, nextVNode.props, prevProps, optimized);
  5444. updateSlots(instance, nextVNode.children);
  5445. // props update may have triggered pre-flush watchers.
  5446. // flush them before the render update.
  5447. flushPreFlushCbs(undefined, instance.update);
  5448. };
  5449. const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized = false) => {
  5450. const c1 = n1 && n1.children;
  5451. const prevShapeFlag = n1 ? n1.shapeFlag : 0;
  5452. const c2 = n2.children;
  5453. const { patchFlag, shapeFlag } = n2;
  5454. // fast path
  5455. if (patchFlag > 0) {
  5456. if (patchFlag & 128 /* KEYED_FRAGMENT */) {
  5457. // this could be either fully-keyed or mixed (some keyed some not)
  5458. // presence of patchFlag means children are guaranteed to be arrays
  5459. patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5460. return;
  5461. }
  5462. else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
  5463. // unkeyed
  5464. patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5465. return;
  5466. }
  5467. }
  5468. // children has 3 possibilities: text, array or no children.
  5469. if (shapeFlag & 8 /* TEXT_CHILDREN */) {
  5470. // text children fast path
  5471. if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
  5472. unmountChildren(c1, parentComponent, parentSuspense);
  5473. }
  5474. if (c2 !== c1) {
  5475. hostSetElementText(container, c2);
  5476. }
  5477. }
  5478. else {
  5479. if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
  5480. // prev children was array
  5481. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  5482. // two arrays, cannot assume anything, do full diff
  5483. patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5484. }
  5485. else {
  5486. // no new children, just unmount old
  5487. unmountChildren(c1, parentComponent, parentSuspense, true);
  5488. }
  5489. }
  5490. else {
  5491. // prev children was text OR null
  5492. // new children is array OR null
  5493. if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
  5494. hostSetElementText(container, '');
  5495. }
  5496. // mount new if array
  5497. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  5498. mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5499. }
  5500. }
  5501. }
  5502. };
  5503. const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  5504. c1 = c1 || EMPTY_ARR;
  5505. c2 = c2 || EMPTY_ARR;
  5506. const oldLength = c1.length;
  5507. const newLength = c2.length;
  5508. const commonLength = Math.min(oldLength, newLength);
  5509. let i;
  5510. for (i = 0; i < commonLength; i++) {
  5511. const nextChild = (c2[i] = optimized
  5512. ? cloneIfMounted(c2[i])
  5513. : normalizeVNode(c2[i]));
  5514. patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, optimized);
  5515. }
  5516. if (oldLength > newLength) {
  5517. // remove old
  5518. unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
  5519. }
  5520. else {
  5521. // mount new
  5522. mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, commonLength);
  5523. }
  5524. };
  5525. // can be all-keyed or mixed
  5526. const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, optimized) => {
  5527. let i = 0;
  5528. const l2 = c2.length;
  5529. let e1 = c1.length - 1; // prev ending index
  5530. let e2 = l2 - 1; // next ending index
  5531. // 1. sync from start
  5532. // (a b) c
  5533. // (a b) d e
  5534. while (i <= e1 && i <= e2) {
  5535. const n1 = c1[i];
  5536. const n2 = (c2[i] = optimized
  5537. ? cloneIfMounted(c2[i])
  5538. : normalizeVNode(c2[i]));
  5539. if (isSameVNodeType(n1, n2)) {
  5540. patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, optimized);
  5541. }
  5542. else {
  5543. break;
  5544. }
  5545. i++;
  5546. }
  5547. // 2. sync from end
  5548. // a (b c)
  5549. // d e (b c)
  5550. while (i <= e1 && i <= e2) {
  5551. const n1 = c1[e1];
  5552. const n2 = (c2[e2] = optimized
  5553. ? cloneIfMounted(c2[e2])
  5554. : normalizeVNode(c2[e2]));
  5555. if (isSameVNodeType(n1, n2)) {
  5556. patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, optimized);
  5557. }
  5558. else {
  5559. break;
  5560. }
  5561. e1--;
  5562. e2--;
  5563. }
  5564. // 3. common sequence + mount
  5565. // (a b)
  5566. // (a b) c
  5567. // i = 2, e1 = 1, e2 = 2
  5568. // (a b)
  5569. // c (a b)
  5570. // i = 0, e1 = -1, e2 = 0
  5571. if (i > e1) {
  5572. if (i <= e2) {
  5573. const nextPos = e2 + 1;
  5574. const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
  5575. while (i <= e2) {
  5576. patch(null, (c2[i] = optimized
  5577. ? cloneIfMounted(c2[i])
  5578. : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG);
  5579. i++;
  5580. }
  5581. }
  5582. }
  5583. // 4. common sequence + unmount
  5584. // (a b) c
  5585. // (a b)
  5586. // i = 2, e1 = 2, e2 = 1
  5587. // a (b c)
  5588. // (b c)
  5589. // i = 0, e1 = 0, e2 = -1
  5590. else if (i > e2) {
  5591. while (i <= e1) {
  5592. unmount(c1[i], parentComponent, parentSuspense, true);
  5593. i++;
  5594. }
  5595. }
  5596. // 5. unknown sequence
  5597. // [i ... e1 + 1]: a b [c d e] f g
  5598. // [i ... e2 + 1]: a b [e d c h] f g
  5599. // i = 2, e1 = 4, e2 = 5
  5600. else {
  5601. const s1 = i; // prev starting index
  5602. const s2 = i; // next starting index
  5603. // 5.1 build key:index map for newChildren
  5604. const keyToNewIndexMap = new Map();
  5605. for (i = s2; i <= e2; i++) {
  5606. const nextChild = (c2[i] = optimized
  5607. ? cloneIfMounted(c2[i])
  5608. : normalizeVNode(c2[i]));
  5609. if (nextChild.key != null) {
  5610. if (keyToNewIndexMap.has(nextChild.key)) {
  5611. warn(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
  5612. }
  5613. keyToNewIndexMap.set(nextChild.key, i);
  5614. }
  5615. }
  5616. // 5.2 loop through old children left to be patched and try to patch
  5617. // matching nodes & remove nodes that are no longer present
  5618. let j;
  5619. let patched = 0;
  5620. const toBePatched = e2 - s2 + 1;
  5621. let moved = false;
  5622. // used to track whether any node has moved
  5623. let maxNewIndexSoFar = 0;
  5624. // works as Map<newIndex, oldIndex>
  5625. // Note that oldIndex is offset by +1
  5626. // and oldIndex = 0 is a special value indicating the new node has
  5627. // no corresponding old node.
  5628. // used for determining longest stable subsequence
  5629. const newIndexToOldIndexMap = new Array(toBePatched);
  5630. for (i = 0; i < toBePatched; i++)
  5631. newIndexToOldIndexMap[i] = 0;
  5632. for (i = s1; i <= e1; i++) {
  5633. const prevChild = c1[i];
  5634. if (patched >= toBePatched) {
  5635. // all new children have been patched so this can only be a removal
  5636. unmount(prevChild, parentComponent, parentSuspense, true);
  5637. continue;
  5638. }
  5639. let newIndex;
  5640. if (prevChild.key != null) {
  5641. newIndex = keyToNewIndexMap.get(prevChild.key);
  5642. }
  5643. else {
  5644. // key-less node, try to locate a key-less node of the same type
  5645. for (j = s2; j <= e2; j++) {
  5646. if (newIndexToOldIndexMap[j - s2] === 0 &&
  5647. isSameVNodeType(prevChild, c2[j])) {
  5648. newIndex = j;
  5649. break;
  5650. }
  5651. }
  5652. }
  5653. if (newIndex === undefined) {
  5654. unmount(prevChild, parentComponent, parentSuspense, true);
  5655. }
  5656. else {
  5657. newIndexToOldIndexMap[newIndex - s2] = i + 1;
  5658. if (newIndex >= maxNewIndexSoFar) {
  5659. maxNewIndexSoFar = newIndex;
  5660. }
  5661. else {
  5662. moved = true;
  5663. }
  5664. patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, optimized);
  5665. patched++;
  5666. }
  5667. }
  5668. // 5.3 move and mount
  5669. // generate longest stable subsequence only when nodes have moved
  5670. const increasingNewIndexSequence = moved
  5671. ? getSequence(newIndexToOldIndexMap)
  5672. : EMPTY_ARR;
  5673. j = increasingNewIndexSequence.length - 1;
  5674. // looping backwards so that we can use last patched node as anchor
  5675. for (i = toBePatched - 1; i >= 0; i--) {
  5676. const nextIndex = s2 + i;
  5677. const nextChild = c2[nextIndex];
  5678. const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
  5679. if (newIndexToOldIndexMap[i] === 0) {
  5680. // mount new
  5681. patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG);
  5682. }
  5683. else if (moved) {
  5684. // move if:
  5685. // There is no stable subsequence (e.g. a reverse)
  5686. // OR current node is not among the stable sequence
  5687. if (j < 0 || i !== increasingNewIndexSequence[j]) {
  5688. move(nextChild, container, anchor, 2 /* REORDER */);
  5689. }
  5690. else {
  5691. j--;
  5692. }
  5693. }
  5694. }
  5695. }
  5696. };
  5697. const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
  5698. const { el, type, transition, children, shapeFlag } = vnode;
  5699. if (shapeFlag & 6 /* COMPONENT */) {
  5700. move(vnode.component.subTree, container, anchor, moveType);
  5701. return;
  5702. }
  5703. if (shapeFlag & 128 /* SUSPENSE */) {
  5704. vnode.suspense.move(container, anchor, moveType);
  5705. return;
  5706. }
  5707. if (shapeFlag & 64 /* TELEPORT */) {
  5708. type.move(vnode, container, anchor, internals);
  5709. return;
  5710. }
  5711. if (type === Fragment) {
  5712. hostInsert(el, container, anchor);
  5713. for (let i = 0; i < children.length; i++) {
  5714. move(children[i], container, anchor, moveType);
  5715. }
  5716. hostInsert(vnode.anchor, container, anchor);
  5717. return;
  5718. }
  5719. if (type === Static) {
  5720. moveStaticNode(vnode, container, anchor);
  5721. return;
  5722. }
  5723. // single nodes
  5724. const needTransition = moveType !== 2 /* REORDER */ &&
  5725. shapeFlag & 1 /* ELEMENT */ &&
  5726. transition;
  5727. if (needTransition) {
  5728. if (moveType === 0 /* ENTER */) {
  5729. transition.beforeEnter(el);
  5730. hostInsert(el, container, anchor);
  5731. queuePostRenderEffect(() => transition.enter(el), parentSuspense);
  5732. }
  5733. else {
  5734. const { leave, delayLeave, afterLeave } = transition;
  5735. const remove = () => hostInsert(el, container, anchor);
  5736. const performLeave = () => {
  5737. leave(el, () => {
  5738. remove();
  5739. afterLeave && afterLeave();
  5740. });
  5741. };
  5742. if (delayLeave) {
  5743. delayLeave(el, remove, performLeave);
  5744. }
  5745. else {
  5746. performLeave();
  5747. }
  5748. }
  5749. }
  5750. else {
  5751. hostInsert(el, container, anchor);
  5752. }
  5753. };
  5754. const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
  5755. const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
  5756. // unset ref
  5757. if (ref != null) {
  5758. setRef(ref, null, parentSuspense, null);
  5759. }
  5760. if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
  5761. parentComponent.ctx.deactivate(vnode);
  5762. return;
  5763. }
  5764. const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
  5765. let vnodeHook;
  5766. if ((vnodeHook = props && props.onVnodeBeforeUnmount)) {
  5767. invokeVNodeHook(vnodeHook, parentComponent, vnode);
  5768. }
  5769. if (shapeFlag & 6 /* COMPONENT */) {
  5770. unmountComponent(vnode.component, parentSuspense, doRemove);
  5771. }
  5772. else {
  5773. if (shapeFlag & 128 /* SUSPENSE */) {
  5774. vnode.suspense.unmount(parentSuspense, doRemove);
  5775. return;
  5776. }
  5777. if (shouldInvokeDirs) {
  5778. invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
  5779. }
  5780. if (dynamicChildren &&
  5781. // #1153: fast path should not be taken for non-stable (v-for) fragments
  5782. (type !== Fragment ||
  5783. (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
  5784. // fast path for block nodes: only need to unmount dynamic children.
  5785. unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
  5786. }
  5787. else if ((type === Fragment &&
  5788. (patchFlag & 128 /* KEYED_FRAGMENT */ ||
  5789. patchFlag & 256 /* UNKEYED_FRAGMENT */)) ||
  5790. (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
  5791. unmountChildren(children, parentComponent, parentSuspense);
  5792. }
  5793. // an unmounted teleport should always remove its children if not disabled
  5794. if (shapeFlag & 64 /* TELEPORT */ &&
  5795. (doRemove || !isTeleportDisabled(vnode.props))) {
  5796. vnode.type.remove(vnode, internals);
  5797. }
  5798. if (doRemove) {
  5799. remove(vnode);
  5800. }
  5801. }
  5802. if ((vnodeHook = props && props.onVnodeUnmounted) || shouldInvokeDirs) {
  5803. queuePostRenderEffect(() => {
  5804. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
  5805. shouldInvokeDirs &&
  5806. invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
  5807. }, parentSuspense);
  5808. }
  5809. };
  5810. const remove = vnode => {
  5811. const { type, el, anchor, transition } = vnode;
  5812. if (type === Fragment) {
  5813. removeFragment(el, anchor);
  5814. return;
  5815. }
  5816. if (type === Static) {
  5817. removeStaticNode(vnode);
  5818. return;
  5819. }
  5820. const performRemove = () => {
  5821. hostRemove(el);
  5822. if (transition && !transition.persisted && transition.afterLeave) {
  5823. transition.afterLeave();
  5824. }
  5825. };
  5826. if (vnode.shapeFlag & 1 /* ELEMENT */ &&
  5827. transition &&
  5828. !transition.persisted) {
  5829. const { leave, delayLeave } = transition;
  5830. const performLeave = () => leave(el, performRemove);
  5831. if (delayLeave) {
  5832. delayLeave(vnode.el, performRemove, performLeave);
  5833. }
  5834. else {
  5835. performLeave();
  5836. }
  5837. }
  5838. else {
  5839. performRemove();
  5840. }
  5841. };
  5842. const removeFragment = (cur, end) => {
  5843. // For fragments, directly remove all contained DOM nodes.
  5844. // (fragment child nodes cannot have transition)
  5845. let next;
  5846. while (cur !== end) {
  5847. next = hostNextSibling(cur);
  5848. hostRemove(cur);
  5849. cur = next;
  5850. }
  5851. hostRemove(end);
  5852. };
  5853. const unmountComponent = (instance, parentSuspense, doRemove) => {
  5854. if (instance.type.__hmrId) {
  5855. unregisterHMR(instance);
  5856. }
  5857. const { bum, effects, update, subTree, um } = instance;
  5858. // beforeUnmount hook
  5859. if (bum) {
  5860. invokeArrayFns(bum);
  5861. }
  5862. if (effects) {
  5863. for (let i = 0; i < effects.length; i++) {
  5864. stop(effects[i]);
  5865. }
  5866. }
  5867. // update may be null if a component is unmounted before its async
  5868. // setup has resolved.
  5869. if (update) {
  5870. stop(update);
  5871. unmount(subTree, instance, parentSuspense, doRemove);
  5872. }
  5873. // unmounted hook
  5874. if (um) {
  5875. queuePostRenderEffect(um, parentSuspense);
  5876. }
  5877. queuePostRenderEffect(() => {
  5878. instance.isUnmounted = true;
  5879. }, parentSuspense);
  5880. // A component with async dep inside a pending suspense is unmounted before
  5881. // its async dep resolves. This should remove the dep from the suspense, and
  5882. // cause the suspense to resolve immediately if that was the last dep.
  5883. if (parentSuspense &&
  5884. parentSuspense.pendingBranch &&
  5885. !parentSuspense.isUnmounted &&
  5886. instance.asyncDep &&
  5887. !instance.asyncResolved &&
  5888. instance.suspenseId === parentSuspense.pendingId) {
  5889. parentSuspense.deps--;
  5890. if (parentSuspense.deps === 0) {
  5891. parentSuspense.resolve();
  5892. }
  5893. }
  5894. {
  5895. devtoolsComponentRemoved(instance);
  5896. }
  5897. };
  5898. const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
  5899. for (let i = start; i < children.length; i++) {
  5900. unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
  5901. }
  5902. };
  5903. const getNextHostNode = vnode => {
  5904. if (vnode.shapeFlag & 6 /* COMPONENT */) {
  5905. return getNextHostNode(vnode.component.subTree);
  5906. }
  5907. if (vnode.shapeFlag & 128 /* SUSPENSE */) {
  5908. return vnode.suspense.next();
  5909. }
  5910. return hostNextSibling((vnode.anchor || vnode.el));
  5911. };
  5912. const render = (vnode, container) => {
  5913. if (vnode == null) {
  5914. if (container._vnode) {
  5915. unmount(container._vnode, null, null, true);
  5916. }
  5917. }
  5918. else {
  5919. patch(container._vnode || null, vnode, container);
  5920. }
  5921. flushPostFlushCbs();
  5922. container._vnode = vnode;
  5923. };
  5924. const internals = {
  5925. p: patch,
  5926. um: unmount,
  5927. m: move,
  5928. r: remove,
  5929. mt: mountComponent,
  5930. mc: mountChildren,
  5931. pc: patchChildren,
  5932. pbc: patchBlockChildren,
  5933. n: getNextHostNode,
  5934. o: options
  5935. };
  5936. let hydrate;
  5937. let hydrateNode;
  5938. if (createHydrationFns) {
  5939. [hydrate, hydrateNode] = createHydrationFns(internals);
  5940. }
  5941. return {
  5942. render,
  5943. hydrate,
  5944. createApp: createAppAPI(render, hydrate)
  5945. };
  5946. }
  5947. function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
  5948. callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
  5949. vnode,
  5950. prevVNode
  5951. ]);
  5952. }
  5953. /**
  5954. * #1156
  5955. * When a component is HMR-enabled, we need to make sure that all static nodes
  5956. * inside a block also inherit the DOM element from the previous tree so that
  5957. * HMR updates (which are full updates) can retrieve the element for patching.
  5958. *
  5959. * #2080
  5960. * Inside keyed `template` fragment static children, if a fragment is moved,
  5961. * the children will always moved so that need inherit el form previous nodes
  5962. * to ensure correct moved position.
  5963. */
  5964. function traverseStaticChildren(n1, n2, shallow = false) {
  5965. const ch1 = n1.children;
  5966. const ch2 = n2.children;
  5967. if (isArray(ch1) && isArray(ch2)) {
  5968. for (let i = 0; i < ch1.length; i++) {
  5969. // this is only called in the optimized path so array children are
  5970. // guaranteed to be vnodes
  5971. const c1 = ch1[i];
  5972. let c2 = ch2[i];
  5973. if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
  5974. if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
  5975. c2 = ch2[i] = cloneIfMounted(ch2[i]);
  5976. c2.el = c1.el;
  5977. }
  5978. if (!shallow)
  5979. traverseStaticChildren(c1, c2);
  5980. }
  5981. // also inherit for comment nodes, but not placeholders (e.g. v-if which
  5982. // would have received .el during block patch)
  5983. if (c2.type === Comment && !c2.el) {
  5984. c2.el = c1.el;
  5985. }
  5986. }
  5987. }
  5988. }
  5989. // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
  5990. function getSequence(arr) {
  5991. const p = arr.slice();
  5992. const result = [0];
  5993. let i, j, u, v, c;
  5994. const len = arr.length;
  5995. for (i = 0; i < len; i++) {
  5996. const arrI = arr[i];
  5997. if (arrI !== 0) {
  5998. j = result[result.length - 1];
  5999. if (arr[j] < arrI) {
  6000. p[i] = j;
  6001. result.push(i);
  6002. continue;
  6003. }
  6004. u = 0;
  6005. v = result.length - 1;
  6006. while (u < v) {
  6007. c = ((u + v) / 2) | 0;
  6008. if (arr[result[c]] < arrI) {
  6009. u = c + 1;
  6010. }
  6011. else {
  6012. v = c;
  6013. }
  6014. }
  6015. if (arrI < arr[result[u]]) {
  6016. if (u > 0) {
  6017. p[i] = result[u - 1];
  6018. }
  6019. result[u] = i;
  6020. }
  6021. }
  6022. }
  6023. u = result.length;
  6024. v = result[u - 1];
  6025. while (u-- > 0) {
  6026. result[u] = v;
  6027. v = p[v];
  6028. }
  6029. return result;
  6030. }
  6031. const isTeleport = (type) => type.__isTeleport;
  6032. const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
  6033. const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
  6034. const resolveTarget = (props, select) => {
  6035. const targetSelector = props && props.to;
  6036. if (isString(targetSelector)) {
  6037. if (!select) {
  6038. warn(`Current renderer does not support string target for Teleports. ` +
  6039. `(missing querySelector renderer option)`);
  6040. return null;
  6041. }
  6042. else {
  6043. const target = select(targetSelector);
  6044. if (!target) {
  6045. warn(`Failed to locate Teleport target with selector "${targetSelector}". ` +
  6046. `Note the target element must exist before the component is mounted - ` +
  6047. `i.e. the target cannot be rendered by the component itself, and ` +
  6048. `ideally should be outside of the entire Vue component tree.`);
  6049. }
  6050. return target;
  6051. }
  6052. }
  6053. else {
  6054. if (!targetSelector && !isTeleportDisabled(props)) {
  6055. warn(`Invalid Teleport target: ${targetSelector}`);
  6056. }
  6057. return targetSelector;
  6058. }
  6059. };
  6060. const TeleportImpl = {
  6061. __isTeleport: true,
  6062. process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, internals) {
  6063. const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
  6064. const disabled = isTeleportDisabled(n2.props);
  6065. const { shapeFlag, children } = n2;
  6066. if (n1 == null) {
  6067. // insert anchors in the main view
  6068. const placeholder = (n2.el = createComment('teleport start')
  6069. );
  6070. const mainAnchor = (n2.anchor = createComment('teleport end')
  6071. );
  6072. insert(placeholder, container, anchor);
  6073. insert(mainAnchor, container, anchor);
  6074. const target = (n2.target = resolveTarget(n2.props, querySelector));
  6075. const targetAnchor = (n2.targetAnchor = createText(''));
  6076. if (target) {
  6077. insert(targetAnchor, target);
  6078. // #2652 we could be teleporting from a non-SVG tree into an SVG tree
  6079. isSVG = isSVG || isTargetSVG(target);
  6080. }
  6081. else if (!disabled) {
  6082. warn('Invalid Teleport target on mount:', target, `(${typeof target})`);
  6083. }
  6084. const mount = (container, anchor) => {
  6085. // Teleport *always* has Array children. This is enforced in both the
  6086. // compiler and vnode children normalization.
  6087. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  6088. mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  6089. }
  6090. };
  6091. if (disabled) {
  6092. mount(container, mainAnchor);
  6093. }
  6094. else if (target) {
  6095. mount(target, targetAnchor);
  6096. }
  6097. }
  6098. else {
  6099. // update content
  6100. n2.el = n1.el;
  6101. const mainAnchor = (n2.anchor = n1.anchor);
  6102. const target = (n2.target = n1.target);
  6103. const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
  6104. const wasDisabled = isTeleportDisabled(n1.props);
  6105. const currentContainer = wasDisabled ? container : target;
  6106. const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
  6107. isSVG = isSVG || isTargetSVG(target);
  6108. if (n2.dynamicChildren) {
  6109. // fast path when the teleport happens to be a block root
  6110. patchBlockChildren(n1.dynamicChildren, n2.dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG);
  6111. // even in block tree mode we need to make sure all root-level nodes
  6112. // in the teleport inherit previous DOM references so that they can
  6113. // be moved in future patches.
  6114. traverseStaticChildren(n1, n2, true);
  6115. }
  6116. else if (!optimized) {
  6117. patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG);
  6118. }
  6119. if (disabled) {
  6120. if (!wasDisabled) {
  6121. // enabled -> disabled
  6122. // move into main container
  6123. moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
  6124. }
  6125. }
  6126. else {
  6127. // target changed
  6128. if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
  6129. const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
  6130. if (nextTarget) {
  6131. moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
  6132. }
  6133. else {
  6134. warn('Invalid Teleport target on update:', target, `(${typeof target})`);
  6135. }
  6136. }
  6137. else if (wasDisabled) {
  6138. // disabled -> enabled
  6139. // move into teleport target
  6140. moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
  6141. }
  6142. }
  6143. }
  6144. },
  6145. remove(vnode, { r: remove, o: { remove: hostRemove } }) {
  6146. const { shapeFlag, children, anchor } = vnode;
  6147. hostRemove(anchor);
  6148. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  6149. for (let i = 0; i < children.length; i++) {
  6150. remove(children[i]);
  6151. }
  6152. }
  6153. },
  6154. move: moveTeleport,
  6155. hydrate: hydrateTeleport
  6156. };
  6157. function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
  6158. // move target anchor if this is a target change.
  6159. if (moveType === 0 /* TARGET_CHANGE */) {
  6160. insert(vnode.targetAnchor, container, parentAnchor);
  6161. }
  6162. const { el, anchor, shapeFlag, children, props } = vnode;
  6163. const isReorder = moveType === 2 /* REORDER */;
  6164. // move main view anchor if this is a re-order.
  6165. if (isReorder) {
  6166. insert(el, container, parentAnchor);
  6167. }
  6168. // if this is a re-order and teleport is enabled (content is in target)
  6169. // do not move children. So the opposite is: only move children if this
  6170. // is not a reorder, or the teleport is disabled
  6171. if (!isReorder || isTeleportDisabled(props)) {
  6172. // Teleport has either Array children or no children.
  6173. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  6174. for (let i = 0; i < children.length; i++) {
  6175. move(children[i], container, parentAnchor, 2 /* REORDER */);
  6176. }
  6177. }
  6178. }
  6179. // move main view anchor if this is a re-order.
  6180. if (isReorder) {
  6181. insert(anchor, container, parentAnchor);
  6182. }
  6183. }
  6184. function hydrateTeleport(node, vnode, parentComponent, parentSuspense, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
  6185. const target = (vnode.target = resolveTarget(vnode.props, querySelector));
  6186. if (target) {
  6187. // if multiple teleports rendered to the same target element, we need to
  6188. // pick up from where the last teleport finished instead of the first node
  6189. const targetNode = target._lpa || target.firstChild;
  6190. if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
  6191. if (isTeleportDisabled(vnode.props)) {
  6192. vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, optimized);
  6193. vnode.targetAnchor = targetNode;
  6194. }
  6195. else {
  6196. vnode.anchor = nextSibling(node);
  6197. vnode.targetAnchor = hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, optimized);
  6198. }
  6199. target._lpa =
  6200. vnode.targetAnchor && nextSibling(vnode.targetAnchor);
  6201. }
  6202. }
  6203. return vnode.anchor && nextSibling(vnode.anchor);
  6204. }
  6205. // Force-casted public typing for h and TSX props inference
  6206. const Teleport = TeleportImpl;
  6207. const COMPONENTS = 'components';
  6208. const DIRECTIVES = 'directives';
  6209. /**
  6210. * @private
  6211. */
  6212. function resolveComponent(name) {
  6213. return resolveAsset(COMPONENTS, name) || name;
  6214. }
  6215. const NULL_DYNAMIC_COMPONENT = Symbol();
  6216. /**
  6217. * @private
  6218. */
  6219. function resolveDynamicComponent(component) {
  6220. if (isString(component)) {
  6221. return resolveAsset(COMPONENTS, component, false) || component;
  6222. }
  6223. else {
  6224. // invalid types will fallthrough to createVNode and raise warning
  6225. return (component || NULL_DYNAMIC_COMPONENT);
  6226. }
  6227. }
  6228. /**
  6229. * @private
  6230. */
  6231. function resolveDirective(name) {
  6232. return resolveAsset(DIRECTIVES, name);
  6233. }
  6234. // implementation
  6235. function resolveAsset(type, name, warnMissing = true) {
  6236. const instance = currentRenderingInstance || currentInstance;
  6237. if (instance) {
  6238. const Component = instance.type;
  6239. // self name has highest priority
  6240. if (type === COMPONENTS) {
  6241. // special self referencing call generated by compiler
  6242. // inferred from SFC filename
  6243. if (name === `_self`) {
  6244. return Component;
  6245. }
  6246. const selfName = getComponentName(Component);
  6247. if (selfName &&
  6248. (selfName === name ||
  6249. selfName === camelize(name) ||
  6250. selfName === capitalize(camelize(name)))) {
  6251. return Component;
  6252. }
  6253. }
  6254. const res =
  6255. // local registration
  6256. // check instance[type] first for components with mixin or extends.
  6257. resolve(instance[type] || Component[type], name) ||
  6258. // global registration
  6259. resolve(instance.appContext[type], name);
  6260. if (warnMissing && !res) {
  6261. warn(`Failed to resolve ${type.slice(0, -1)}: ${name}`);
  6262. }
  6263. return res;
  6264. }
  6265. else {
  6266. warn(`resolve${capitalize(type.slice(0, -1))} ` +
  6267. `can only be used in render() or setup().`);
  6268. }
  6269. }
  6270. function resolve(registry, name) {
  6271. return (registry &&
  6272. (registry[name] ||
  6273. registry[camelize(name)] ||
  6274. registry[capitalize(camelize(name))]));
  6275. }
  6276. const Fragment = Symbol('Fragment' );
  6277. const Text = Symbol('Text' );
  6278. const Comment = Symbol('Comment' );
  6279. const Static = Symbol('Static' );
  6280. // Since v-if and v-for are the two possible ways node structure can dynamically
  6281. // change, once we consider v-if branches and each v-for fragment a block, we
  6282. // can divide a template into nested blocks, and within each block the node
  6283. // structure would be stable. This allows us to skip most children diffing
  6284. // and only worry about the dynamic nodes (indicated by patch flags).
  6285. const blockStack = [];
  6286. let currentBlock = null;
  6287. /**
  6288. * Open a block.
  6289. * This must be called before `createBlock`. It cannot be part of `createBlock`
  6290. * because the children of the block are evaluated before `createBlock` itself
  6291. * is called. The generated code typically looks like this:
  6292. *
  6293. * ```js
  6294. * function render() {
  6295. * return (openBlock(),createBlock('div', null, [...]))
  6296. * }
  6297. * ```
  6298. * disableTracking is true when creating a v-for fragment block, since a v-for
  6299. * fragment always diffs its children.
  6300. *
  6301. * @private
  6302. */
  6303. function openBlock(disableTracking = false) {
  6304. blockStack.push((currentBlock = disableTracking ? null : []));
  6305. }
  6306. function closeBlock() {
  6307. blockStack.pop();
  6308. currentBlock = blockStack[blockStack.length - 1] || null;
  6309. }
  6310. // Whether we should be tracking dynamic child nodes inside a block.
  6311. // Only tracks when this value is > 0
  6312. // We are not using a simple boolean because this value may need to be
  6313. // incremented/decremented by nested usage of v-once (see below)
  6314. let shouldTrack$1 = 1;
  6315. /**
  6316. * Block tracking sometimes needs to be disabled, for example during the
  6317. * creation of a tree that needs to be cached by v-once. The compiler generates
  6318. * code like this:
  6319. *
  6320. * ``` js
  6321. * _cache[1] || (
  6322. * setBlockTracking(-1),
  6323. * _cache[1] = createVNode(...),
  6324. * setBlockTracking(1),
  6325. * _cache[1]
  6326. * )
  6327. * ```
  6328. *
  6329. * @private
  6330. */
  6331. function setBlockTracking(value) {
  6332. shouldTrack$1 += value;
  6333. }
  6334. /**
  6335. * Create a block root vnode. Takes the same exact arguments as `createVNode`.
  6336. * A block root keeps track of dynamic nodes within the block in the
  6337. * `dynamicChildren` array.
  6338. *
  6339. * @private
  6340. */
  6341. function createBlock(type, props, children, patchFlag, dynamicProps) {
  6342. const vnode = createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */);
  6343. // save current block children on the block vnode
  6344. vnode.dynamicChildren = currentBlock || EMPTY_ARR;
  6345. // close block
  6346. closeBlock();
  6347. // a block is always going to be patched, so track it as a child of its
  6348. // parent block
  6349. if (shouldTrack$1 > 0 && currentBlock) {
  6350. currentBlock.push(vnode);
  6351. }
  6352. return vnode;
  6353. }
  6354. function isVNode(value) {
  6355. return value ? value.__v_isVNode === true : false;
  6356. }
  6357. function isSameVNodeType(n1, n2) {
  6358. if (n2.shapeFlag & 6 /* COMPONENT */ &&
  6359. hmrDirtyComponents.has(n2.type)) {
  6360. // HMR only: if the component has been hot-updated, force a reload.
  6361. return false;
  6362. }
  6363. return n1.type === n2.type && n1.key === n2.key;
  6364. }
  6365. let vnodeArgsTransformer;
  6366. /**
  6367. * Internal API for registering an arguments transform for createVNode
  6368. * used for creating stubs in the test-utils
  6369. * It is *internal* but needs to be exposed for test-utils to pick up proper
  6370. * typings
  6371. */
  6372. function transformVNodeArgs(transformer) {
  6373. vnodeArgsTransformer = transformer;
  6374. }
  6375. const createVNodeWithArgsTransform = (...args) => {
  6376. return _createVNode(...(vnodeArgsTransformer
  6377. ? vnodeArgsTransformer(args, currentRenderingInstance)
  6378. : args));
  6379. };
  6380. const InternalObjectKey = `__vInternal`;
  6381. const normalizeKey = ({ key }) => key != null ? key : null;
  6382. const normalizeRef = ({ ref }) => {
  6383. return (ref != null
  6384. ? isString(ref) || isRef(ref) || isFunction(ref)
  6385. ? { i: currentRenderingInstance, r: ref }
  6386. : ref
  6387. : null);
  6388. };
  6389. const createVNode = (createVNodeWithArgsTransform
  6390. );
  6391. function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
  6392. if (!type || type === NULL_DYNAMIC_COMPONENT) {
  6393. if (!type) {
  6394. warn(`Invalid vnode type when creating vnode: ${type}.`);
  6395. }
  6396. type = Comment;
  6397. }
  6398. if (isVNode(type)) {
  6399. // createVNode receiving an existing vnode. This happens in cases like
  6400. // <component :is="vnode"/>
  6401. // #2078 make sure to merge refs during the clone instead of overwriting it
  6402. const cloned = cloneVNode(type, props, true /* mergeRef: true */);
  6403. if (children) {
  6404. normalizeChildren(cloned, children);
  6405. }
  6406. return cloned;
  6407. }
  6408. // class component normalization.
  6409. if (isClassComponent(type)) {
  6410. type = type.__vccOpts;
  6411. }
  6412. // class & style normalization.
  6413. if (props) {
  6414. // for reactive or proxy objects, we need to clone it to enable mutation.
  6415. if (isProxy(props) || InternalObjectKey in props) {
  6416. props = extend({}, props);
  6417. }
  6418. let { class: klass, style } = props;
  6419. if (klass && !isString(klass)) {
  6420. props.class = normalizeClass(klass);
  6421. }
  6422. if (isObject(style)) {
  6423. // reactive state objects need to be cloned since they are likely to be
  6424. // mutated
  6425. if (isProxy(style) && !isArray(style)) {
  6426. style = extend({}, style);
  6427. }
  6428. props.style = normalizeStyle(style);
  6429. }
  6430. }
  6431. // encode the vnode type information into a bitmap
  6432. const shapeFlag = isString(type)
  6433. ? 1 /* ELEMENT */
  6434. : isSuspense(type)
  6435. ? 128 /* SUSPENSE */
  6436. : isTeleport(type)
  6437. ? 64 /* TELEPORT */
  6438. : isObject(type)
  6439. ? 4 /* STATEFUL_COMPONENT */
  6440. : isFunction(type)
  6441. ? 2 /* FUNCTIONAL_COMPONENT */
  6442. : 0;
  6443. if (shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
  6444. type = toRaw(type);
  6445. warn(`Vue received a Component which was made a reactive object. This can ` +
  6446. `lead to unnecessary performance overhead, and should be avoided by ` +
  6447. `marking the component with \`markRaw\` or using \`shallowRef\` ` +
  6448. `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
  6449. }
  6450. const vnode = {
  6451. __v_isVNode: true,
  6452. ["__v_skip" /* SKIP */]: true,
  6453. type,
  6454. props,
  6455. key: props && normalizeKey(props),
  6456. ref: props && normalizeRef(props),
  6457. scopeId: currentScopeId,
  6458. children: null,
  6459. component: null,
  6460. suspense: null,
  6461. ssContent: null,
  6462. ssFallback: null,
  6463. dirs: null,
  6464. transition: null,
  6465. el: null,
  6466. anchor: null,
  6467. target: null,
  6468. targetAnchor: null,
  6469. staticCount: 0,
  6470. shapeFlag,
  6471. patchFlag,
  6472. dynamicProps,
  6473. dynamicChildren: null,
  6474. appContext: null
  6475. };
  6476. // validate key
  6477. if (vnode.key !== vnode.key) {
  6478. warn(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
  6479. }
  6480. normalizeChildren(vnode, children);
  6481. // normalize suspense children
  6482. if (shapeFlag & 128 /* SUSPENSE */) {
  6483. const { content, fallback } = normalizeSuspenseChildren(vnode);
  6484. vnode.ssContent = content;
  6485. vnode.ssFallback = fallback;
  6486. }
  6487. if (shouldTrack$1 > 0 &&
  6488. // avoid a block node from tracking itself
  6489. !isBlockNode &&
  6490. // has current parent block
  6491. currentBlock &&
  6492. // presence of a patch flag indicates this node needs patching on updates.
  6493. // component nodes also should always be patched, because even if the
  6494. // component doesn't need to update, it needs to persist the instance on to
  6495. // the next vnode so that it can be properly unmounted later.
  6496. (patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
  6497. // the EVENTS flag is only for hydration and if it is the only flag, the
  6498. // vnode should not be considered dynamic due to handler caching.
  6499. patchFlag !== 32 /* HYDRATE_EVENTS */) {
  6500. currentBlock.push(vnode);
  6501. }
  6502. return vnode;
  6503. }
  6504. function cloneVNode(vnode, extraProps, mergeRef = false) {
  6505. // This is intentionally NOT using spread or extend to avoid the runtime
  6506. // key enumeration cost.
  6507. const { props, ref, patchFlag, children } = vnode;
  6508. const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
  6509. return {
  6510. __v_isVNode: true,
  6511. ["__v_skip" /* SKIP */]: true,
  6512. type: vnode.type,
  6513. props: mergedProps,
  6514. key: mergedProps && normalizeKey(mergedProps),
  6515. ref: extraProps && extraProps.ref
  6516. ? // #2078 in the case of <component :is="vnode" ref="extra"/>
  6517. // if the vnode itself already has a ref, cloneVNode will need to merge
  6518. // the refs so the single vnode can be set on multiple refs
  6519. mergeRef && ref
  6520. ? isArray(ref)
  6521. ? ref.concat(normalizeRef(extraProps))
  6522. : [ref, normalizeRef(extraProps)]
  6523. : normalizeRef(extraProps)
  6524. : ref,
  6525. scopeId: vnode.scopeId,
  6526. children: patchFlag === -1 /* HOISTED */ && isArray(children)
  6527. ? children.map(deepCloneVNode)
  6528. : children,
  6529. target: vnode.target,
  6530. targetAnchor: vnode.targetAnchor,
  6531. staticCount: vnode.staticCount,
  6532. shapeFlag: vnode.shapeFlag,
  6533. // if the vnode is cloned with extra props, we can no longer assume its
  6534. // existing patch flag to be reliable and need to add the FULL_PROPS flag.
  6535. // note: perserve flag for fragments since they use the flag for children
  6536. // fast paths only.
  6537. patchFlag: extraProps && vnode.type !== Fragment
  6538. ? patchFlag === -1 // hoisted node
  6539. ? 16 /* FULL_PROPS */
  6540. : patchFlag | 16 /* FULL_PROPS */
  6541. : patchFlag,
  6542. dynamicProps: vnode.dynamicProps,
  6543. dynamicChildren: vnode.dynamicChildren,
  6544. appContext: vnode.appContext,
  6545. dirs: vnode.dirs,
  6546. transition: vnode.transition,
  6547. // These should technically only be non-null on mounted VNodes. However,
  6548. // they *should* be copied for kept-alive vnodes. So we just always copy
  6549. // them since them being non-null during a mount doesn't affect the logic as
  6550. // they will simply be overwritten.
  6551. component: vnode.component,
  6552. suspense: vnode.suspense,
  6553. ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
  6554. ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
  6555. el: vnode.el,
  6556. anchor: vnode.anchor
  6557. };
  6558. }
  6559. /**
  6560. * Dev only, for HMR of hoisted vnodes reused in v-for
  6561. * https://github.com/vitejs/vite/issues/2022
  6562. */
  6563. function deepCloneVNode(vnode) {
  6564. const cloned = cloneVNode(vnode);
  6565. if (isArray(vnode.children)) {
  6566. cloned.children = vnode.children.map(deepCloneVNode);
  6567. }
  6568. return cloned;
  6569. }
  6570. /**
  6571. * @private
  6572. */
  6573. function createTextVNode(text = ' ', flag = 0) {
  6574. return createVNode(Text, null, text, flag);
  6575. }
  6576. /**
  6577. * @private
  6578. */
  6579. function createStaticVNode(content, numberOfNodes) {
  6580. // A static vnode can contain multiple stringified elements, and the number
  6581. // of elements is necessary for hydration.
  6582. const vnode = createVNode(Static, null, content);
  6583. vnode.staticCount = numberOfNodes;
  6584. return vnode;
  6585. }
  6586. /**
  6587. * @private
  6588. */
  6589. function createCommentVNode(text = '',
  6590. // when used as the v-else branch, the comment node must be created as a
  6591. // block to ensure correct updates.
  6592. asBlock = false) {
  6593. return asBlock
  6594. ? (openBlock(), createBlock(Comment, null, text))
  6595. : createVNode(Comment, null, text);
  6596. }
  6597. function normalizeVNode(child) {
  6598. if (child == null || typeof child === 'boolean') {
  6599. // empty placeholder
  6600. return createVNode(Comment);
  6601. }
  6602. else if (isArray(child)) {
  6603. // fragment
  6604. return createVNode(Fragment, null, child);
  6605. }
  6606. else if (typeof child === 'object') {
  6607. // already vnode, this should be the most common since compiled templates
  6608. // always produce all-vnode children arrays
  6609. return child.el === null ? child : cloneVNode(child);
  6610. }
  6611. else {
  6612. // strings and numbers
  6613. return createVNode(Text, null, String(child));
  6614. }
  6615. }
  6616. // optimized normalization for template-compiled render fns
  6617. function cloneIfMounted(child) {
  6618. return child.el === null ? child : cloneVNode(child);
  6619. }
  6620. function normalizeChildren(vnode, children) {
  6621. let type = 0;
  6622. const { shapeFlag } = vnode;
  6623. if (children == null) {
  6624. children = null;
  6625. }
  6626. else if (isArray(children)) {
  6627. type = 16 /* ARRAY_CHILDREN */;
  6628. }
  6629. else if (typeof children === 'object') {
  6630. if (shapeFlag & 1 /* ELEMENT */ || shapeFlag & 64 /* TELEPORT */) {
  6631. // Normalize slot to plain children for plain element and Teleport
  6632. const slot = children.default;
  6633. if (slot) {
  6634. // _c marker is added by withCtx() indicating this is a compiled slot
  6635. slot._c && setCompiledSlotRendering(1);
  6636. normalizeChildren(vnode, slot());
  6637. slot._c && setCompiledSlotRendering(-1);
  6638. }
  6639. return;
  6640. }
  6641. else {
  6642. type = 32 /* SLOTS_CHILDREN */;
  6643. const slotFlag = children._;
  6644. if (!slotFlag && !(InternalObjectKey in children)) {
  6645. children._ctx = currentRenderingInstance;
  6646. }
  6647. else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
  6648. // a child component receives forwarded slots from the parent.
  6649. // its slot type is determined by its parent's slot type.
  6650. if (currentRenderingInstance.vnode.patchFlag & 1024 /* DYNAMIC_SLOTS */) {
  6651. children._ = 2 /* DYNAMIC */;
  6652. vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  6653. }
  6654. else {
  6655. children._ = 1 /* STABLE */;
  6656. }
  6657. }
  6658. }
  6659. }
  6660. else if (isFunction(children)) {
  6661. children = { default: children, _ctx: currentRenderingInstance };
  6662. type = 32 /* SLOTS_CHILDREN */;
  6663. }
  6664. else {
  6665. children = String(children);
  6666. // force teleport children to array so it can be moved around
  6667. if (shapeFlag & 64 /* TELEPORT */) {
  6668. type = 16 /* ARRAY_CHILDREN */;
  6669. children = [createTextVNode(children)];
  6670. }
  6671. else {
  6672. type = 8 /* TEXT_CHILDREN */;
  6673. }
  6674. }
  6675. vnode.children = children;
  6676. vnode.shapeFlag |= type;
  6677. }
  6678. function mergeProps(...args) {
  6679. const ret = extend({}, args[0]);
  6680. for (let i = 1; i < args.length; i++) {
  6681. const toMerge = args[i];
  6682. for (const key in toMerge) {
  6683. if (key === 'class') {
  6684. if (ret.class !== toMerge.class) {
  6685. ret.class = normalizeClass([ret.class, toMerge.class]);
  6686. }
  6687. }
  6688. else if (key === 'style') {
  6689. ret.style = normalizeStyle([ret.style, toMerge.style]);
  6690. }
  6691. else if (isOn(key)) {
  6692. const existing = ret[key];
  6693. const incoming = toMerge[key];
  6694. if (existing !== incoming) {
  6695. ret[key] = existing
  6696. ? [].concat(existing, toMerge[key])
  6697. : incoming;
  6698. }
  6699. }
  6700. else if (key !== '') {
  6701. ret[key] = toMerge[key];
  6702. }
  6703. }
  6704. }
  6705. return ret;
  6706. }
  6707. function provide(key, value) {
  6708. if (!currentInstance) {
  6709. {
  6710. warn(`provide() can only be used inside setup().`);
  6711. }
  6712. }
  6713. else {
  6714. let provides = currentInstance.provides;
  6715. // by default an instance inherits its parent's provides object
  6716. // but when it needs to provide values of its own, it creates its
  6717. // own provides object using parent provides object as prototype.
  6718. // this way in `inject` we can simply look up injections from direct
  6719. // parent and let the prototype chain do the work.
  6720. const parentProvides = currentInstance.parent && currentInstance.parent.provides;
  6721. if (parentProvides === provides) {
  6722. provides = currentInstance.provides = Object.create(parentProvides);
  6723. }
  6724. // TS doesn't allow symbol as index type
  6725. provides[key] = value;
  6726. }
  6727. }
  6728. function inject(key, defaultValue, treatDefaultAsFactory = false) {
  6729. // fallback to `currentRenderingInstance` so that this can be called in
  6730. // a functional component
  6731. const instance = currentInstance || currentRenderingInstance;
  6732. if (instance) {
  6733. // #2400
  6734. // to support `app.use` plugins,
  6735. // fallback to appContext's `provides` if the intance is at root
  6736. const provides = instance.parent == null
  6737. ? instance.vnode.appContext && instance.vnode.appContext.provides
  6738. : instance.parent.provides;
  6739. if (provides && key in provides) {
  6740. // TS doesn't allow symbol as index type
  6741. return provides[key];
  6742. }
  6743. else if (arguments.length > 1) {
  6744. return treatDefaultAsFactory && isFunction(defaultValue)
  6745. ? defaultValue()
  6746. : defaultValue;
  6747. }
  6748. else {
  6749. warn(`injection "${String(key)}" not found.`);
  6750. }
  6751. }
  6752. else {
  6753. warn(`inject() can only be used inside setup() or functional components.`);
  6754. }
  6755. }
  6756. function createDuplicateChecker() {
  6757. const cache = Object.create(null);
  6758. return (type, key) => {
  6759. if (cache[key]) {
  6760. warn(`${type} property "${key}" is already defined in ${cache[key]}.`);
  6761. }
  6762. else {
  6763. cache[key] = type;
  6764. }
  6765. };
  6766. }
  6767. let isInBeforeCreate = false;
  6768. function applyOptions(instance, options, deferredData = [], deferredWatch = [], deferredProvide = [], asMixin = false) {
  6769. const {
  6770. // composition
  6771. mixins, extends: extendsOptions,
  6772. // state
  6773. data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
  6774. // assets
  6775. components, directives,
  6776. // lifecycle
  6777. beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured,
  6778. // public API
  6779. expose } = options;
  6780. const publicThis = instance.proxy;
  6781. const ctx = instance.ctx;
  6782. const globalMixins = instance.appContext.mixins;
  6783. if (asMixin && render && instance.render === NOOP) {
  6784. instance.render = render;
  6785. }
  6786. // applyOptions is called non-as-mixin once per instance
  6787. if (!asMixin) {
  6788. isInBeforeCreate = true;
  6789. callSyncHook('beforeCreate', "bc" /* BEFORE_CREATE */, options, instance, globalMixins);
  6790. isInBeforeCreate = false;
  6791. // global mixins are applied first
  6792. applyMixins(instance, globalMixins, deferredData, deferredWatch, deferredProvide);
  6793. }
  6794. // extending a base component...
  6795. if (extendsOptions) {
  6796. applyOptions(instance, extendsOptions, deferredData, deferredWatch, deferredProvide, true);
  6797. }
  6798. // local mixins
  6799. if (mixins) {
  6800. applyMixins(instance, mixins, deferredData, deferredWatch, deferredProvide);
  6801. }
  6802. const checkDuplicateProperties = createDuplicateChecker() ;
  6803. {
  6804. const [propsOptions] = instance.propsOptions;
  6805. if (propsOptions) {
  6806. for (const key in propsOptions) {
  6807. checkDuplicateProperties("Props" /* PROPS */, key);
  6808. }
  6809. }
  6810. }
  6811. // options initialization order (to be consistent with Vue 2):
  6812. // - props (already done outside of this function)
  6813. // - inject
  6814. // - methods
  6815. // - data (deferred since it relies on `this` access)
  6816. // - computed
  6817. // - watch (deferred since it relies on `this` access)
  6818. if (injectOptions) {
  6819. if (isArray(injectOptions)) {
  6820. for (let i = 0; i < injectOptions.length; i++) {
  6821. const key = injectOptions[i];
  6822. ctx[key] = inject(key);
  6823. {
  6824. checkDuplicateProperties("Inject" /* INJECT */, key);
  6825. }
  6826. }
  6827. }
  6828. else {
  6829. for (const key in injectOptions) {
  6830. const opt = injectOptions[key];
  6831. if (isObject(opt)) {
  6832. ctx[key] = inject(opt.from || key, opt.default, true /* treat default function as factory */);
  6833. }
  6834. else {
  6835. ctx[key] = inject(opt);
  6836. }
  6837. {
  6838. checkDuplicateProperties("Inject" /* INJECT */, key);
  6839. }
  6840. }
  6841. }
  6842. }
  6843. if (methods) {
  6844. for (const key in methods) {
  6845. const methodHandler = methods[key];
  6846. if (isFunction(methodHandler)) {
  6847. // In dev mode, we use the `createRenderContext` function to define methods to the proxy target,
  6848. // and those are read-only but reconfigurable, so it needs to be redefined here
  6849. {
  6850. Object.defineProperty(ctx, key, {
  6851. value: methodHandler.bind(publicThis),
  6852. configurable: true,
  6853. enumerable: false
  6854. });
  6855. }
  6856. {
  6857. checkDuplicateProperties("Methods" /* METHODS */, key);
  6858. }
  6859. }
  6860. else {
  6861. warn(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
  6862. `Did you reference the function correctly?`);
  6863. }
  6864. }
  6865. }
  6866. if (!asMixin) {
  6867. if (deferredData.length) {
  6868. deferredData.forEach(dataFn => resolveData(instance, dataFn, publicThis));
  6869. }
  6870. if (dataOptions) {
  6871. // @ts-ignore dataOptions is not fully type safe
  6872. resolveData(instance, dataOptions, publicThis);
  6873. }
  6874. {
  6875. const rawData = toRaw(instance.data);
  6876. for (const key in rawData) {
  6877. checkDuplicateProperties("Data" /* DATA */, key);
  6878. // expose data on ctx during dev
  6879. if (key[0] !== '$' && key[0] !== '_') {
  6880. Object.defineProperty(ctx, key, {
  6881. configurable: true,
  6882. enumerable: true,
  6883. get: () => rawData[key],
  6884. set: NOOP
  6885. });
  6886. }
  6887. }
  6888. }
  6889. }
  6890. else if (dataOptions) {
  6891. deferredData.push(dataOptions);
  6892. }
  6893. if (computedOptions) {
  6894. for (const key in computedOptions) {
  6895. const opt = computedOptions[key];
  6896. const get = isFunction(opt)
  6897. ? opt.bind(publicThis, publicThis)
  6898. : isFunction(opt.get)
  6899. ? opt.get.bind(publicThis, publicThis)
  6900. : NOOP;
  6901. if (get === NOOP) {
  6902. warn(`Computed property "${key}" has no getter.`);
  6903. }
  6904. const set = !isFunction(opt) && isFunction(opt.set)
  6905. ? opt.set.bind(publicThis)
  6906. : () => {
  6907. warn(`Write operation failed: computed property "${key}" is readonly.`);
  6908. }
  6909. ;
  6910. const c = computed$1({
  6911. get,
  6912. set
  6913. });
  6914. Object.defineProperty(ctx, key, {
  6915. enumerable: true,
  6916. configurable: true,
  6917. get: () => c.value,
  6918. set: v => (c.value = v)
  6919. });
  6920. {
  6921. checkDuplicateProperties("Computed" /* COMPUTED */, key);
  6922. }
  6923. }
  6924. }
  6925. if (watchOptions) {
  6926. deferredWatch.push(watchOptions);
  6927. }
  6928. if (!asMixin && deferredWatch.length) {
  6929. deferredWatch.forEach(watchOptions => {
  6930. for (const key in watchOptions) {
  6931. createWatcher(watchOptions[key], ctx, publicThis, key);
  6932. }
  6933. });
  6934. }
  6935. if (provideOptions) {
  6936. deferredProvide.push(provideOptions);
  6937. }
  6938. if (!asMixin && deferredProvide.length) {
  6939. deferredProvide.forEach(provideOptions => {
  6940. const provides = isFunction(provideOptions)
  6941. ? provideOptions.call(publicThis)
  6942. : provideOptions;
  6943. Reflect.ownKeys(provides).forEach(key => {
  6944. provide(key, provides[key]);
  6945. });
  6946. });
  6947. }
  6948. // asset options.
  6949. // To reduce memory usage, only components with mixins or extends will have
  6950. // resolved asset registry attached to instance.
  6951. if (asMixin) {
  6952. if (components) {
  6953. extend(instance.components ||
  6954. (instance.components = extend({}, instance.type.components)), components);
  6955. }
  6956. if (directives) {
  6957. extend(instance.directives ||
  6958. (instance.directives = extend({}, instance.type.directives)), directives);
  6959. }
  6960. }
  6961. // lifecycle options
  6962. if (!asMixin) {
  6963. callSyncHook('created', "c" /* CREATED */, options, instance, globalMixins);
  6964. }
  6965. if (beforeMount) {
  6966. onBeforeMount(beforeMount.bind(publicThis));
  6967. }
  6968. if (mounted) {
  6969. onMounted(mounted.bind(publicThis));
  6970. }
  6971. if (beforeUpdate) {
  6972. onBeforeUpdate(beforeUpdate.bind(publicThis));
  6973. }
  6974. if (updated) {
  6975. onUpdated(updated.bind(publicThis));
  6976. }
  6977. if (activated) {
  6978. onActivated(activated.bind(publicThis));
  6979. }
  6980. if (deactivated) {
  6981. onDeactivated(deactivated.bind(publicThis));
  6982. }
  6983. if (errorCaptured) {
  6984. onErrorCaptured(errorCaptured.bind(publicThis));
  6985. }
  6986. if (renderTracked) {
  6987. onRenderTracked(renderTracked.bind(publicThis));
  6988. }
  6989. if (renderTriggered) {
  6990. onRenderTriggered(renderTriggered.bind(publicThis));
  6991. }
  6992. if (beforeDestroy) {
  6993. warn(`\`beforeDestroy\` has been renamed to \`beforeUnmount\`.`);
  6994. }
  6995. if (beforeUnmount) {
  6996. onBeforeUnmount(beforeUnmount.bind(publicThis));
  6997. }
  6998. if (destroyed) {
  6999. warn(`\`destroyed\` has been renamed to \`unmounted\`.`);
  7000. }
  7001. if (unmounted) {
  7002. onUnmounted(unmounted.bind(publicThis));
  7003. }
  7004. if (isArray(expose)) {
  7005. if (!asMixin) {
  7006. if (expose.length) {
  7007. const exposed = instance.exposed || (instance.exposed = proxyRefs({}));
  7008. expose.forEach(key => {
  7009. exposed[key] = toRef(publicThis, key);
  7010. });
  7011. }
  7012. else if (!instance.exposed) {
  7013. instance.exposed = EMPTY_OBJ;
  7014. }
  7015. }
  7016. else {
  7017. warn(`The \`expose\` option is ignored when used in mixins.`);
  7018. }
  7019. }
  7020. }
  7021. function callSyncHook(name, type, options, instance, globalMixins) {
  7022. callHookFromMixins(name, type, globalMixins, instance);
  7023. const { extends: base, mixins } = options;
  7024. if (base) {
  7025. callHookFromExtends(name, type, base, instance);
  7026. }
  7027. if (mixins) {
  7028. callHookFromMixins(name, type, mixins, instance);
  7029. }
  7030. const selfHook = options[name];
  7031. if (selfHook) {
  7032. callWithAsyncErrorHandling(selfHook.bind(instance.proxy), instance, type);
  7033. }
  7034. }
  7035. function callHookFromExtends(name, type, base, instance) {
  7036. if (base.extends) {
  7037. callHookFromExtends(name, type, base.extends, instance);
  7038. }
  7039. const baseHook = base[name];
  7040. if (baseHook) {
  7041. callWithAsyncErrorHandling(baseHook.bind(instance.proxy), instance, type);
  7042. }
  7043. }
  7044. function callHookFromMixins(name, type, mixins, instance) {
  7045. for (let i = 0; i < mixins.length; i++) {
  7046. const chainedMixins = mixins[i].mixins;
  7047. if (chainedMixins) {
  7048. callHookFromMixins(name, type, chainedMixins, instance);
  7049. }
  7050. const fn = mixins[i][name];
  7051. if (fn) {
  7052. callWithAsyncErrorHandling(fn.bind(instance.proxy), instance, type);
  7053. }
  7054. }
  7055. }
  7056. function applyMixins(instance, mixins, deferredData, deferredWatch, deferredProvide) {
  7057. for (let i = 0; i < mixins.length; i++) {
  7058. applyOptions(instance, mixins[i], deferredData, deferredWatch, deferredProvide, true);
  7059. }
  7060. }
  7061. function resolveData(instance, dataFn, publicThis) {
  7062. if (!isFunction(dataFn)) {
  7063. warn(`The data option must be a function. ` +
  7064. `Plain object usage is no longer supported.`);
  7065. }
  7066. const data = dataFn.call(publicThis, publicThis);
  7067. if (isPromise(data)) {
  7068. warn(`data() returned a Promise - note data() cannot be async; If you ` +
  7069. `intend to perform data fetching before component renders, use ` +
  7070. `async setup() + <Suspense>.`);
  7071. }
  7072. if (!isObject(data)) {
  7073. warn(`data() should return an object.`);
  7074. }
  7075. else if (instance.data === EMPTY_OBJ) {
  7076. instance.data = reactive(data);
  7077. }
  7078. else {
  7079. // existing data: this is a mixin or extends.
  7080. extend(instance.data, data);
  7081. }
  7082. }
  7083. function createWatcher(raw, ctx, publicThis, key) {
  7084. const getter = key.includes('.')
  7085. ? createPathGetter(publicThis, key)
  7086. : () => publicThis[key];
  7087. if (isString(raw)) {
  7088. const handler = ctx[raw];
  7089. if (isFunction(handler)) {
  7090. watch(getter, handler);
  7091. }
  7092. else {
  7093. warn(`Invalid watch handler specified by key "${raw}"`, handler);
  7094. }
  7095. }
  7096. else if (isFunction(raw)) {
  7097. watch(getter, raw.bind(publicThis));
  7098. }
  7099. else if (isObject(raw)) {
  7100. if (isArray(raw)) {
  7101. raw.forEach(r => createWatcher(r, ctx, publicThis, key));
  7102. }
  7103. else {
  7104. const handler = isFunction(raw.handler)
  7105. ? raw.handler.bind(publicThis)
  7106. : ctx[raw.handler];
  7107. if (isFunction(handler)) {
  7108. watch(getter, handler, raw);
  7109. }
  7110. else {
  7111. warn(`Invalid watch handler specified by key "${raw.handler}"`, handler);
  7112. }
  7113. }
  7114. }
  7115. else {
  7116. warn(`Invalid watch option: "${key}"`, raw);
  7117. }
  7118. }
  7119. function createPathGetter(ctx, path) {
  7120. const segments = path.split('.');
  7121. return () => {
  7122. let cur = ctx;
  7123. for (let i = 0; i < segments.length && cur; i++) {
  7124. cur = cur[segments[i]];
  7125. }
  7126. return cur;
  7127. };
  7128. }
  7129. function resolveMergedOptions(instance) {
  7130. const raw = instance.type;
  7131. const { __merged, mixins, extends: extendsOptions } = raw;
  7132. if (__merged)
  7133. return __merged;
  7134. const globalMixins = instance.appContext.mixins;
  7135. if (!globalMixins.length && !mixins && !extendsOptions)
  7136. return raw;
  7137. const options = {};
  7138. globalMixins.forEach(m => mergeOptions(options, m, instance));
  7139. mergeOptions(options, raw, instance);
  7140. return (raw.__merged = options);
  7141. }
  7142. function mergeOptions(to, from, instance) {
  7143. const strats = instance.appContext.config.optionMergeStrategies;
  7144. const { mixins, extends: extendsOptions } = from;
  7145. extendsOptions && mergeOptions(to, extendsOptions, instance);
  7146. mixins &&
  7147. mixins.forEach((m) => mergeOptions(to, m, instance));
  7148. for (const key in from) {
  7149. if (strats && hasOwn(strats, key)) {
  7150. to[key] = strats[key](to[key], from[key], instance.proxy, key);
  7151. }
  7152. else {
  7153. to[key] = from[key];
  7154. }
  7155. }
  7156. }
  7157. /**
  7158. * #2437 In Vue 3, functional components do not have a public instance proxy but
  7159. * they exist in the internal parent chain. For code that relies on traversing
  7160. * public $parent chains, skip functional ones and go to the parent instead.
  7161. */
  7162. const getPublicInstance = (i) => {
  7163. if (!i)
  7164. return null;
  7165. if (isStatefulComponent(i))
  7166. return i.exposed ? i.exposed : i.proxy;
  7167. return getPublicInstance(i.parent);
  7168. };
  7169. const publicPropertiesMap = extend(Object.create(null), {
  7170. $: i => i,
  7171. $el: i => i.vnode.el,
  7172. $data: i => i.data,
  7173. $props: i => (shallowReadonly(i.props) ),
  7174. $attrs: i => (shallowReadonly(i.attrs) ),
  7175. $slots: i => (shallowReadonly(i.slots) ),
  7176. $refs: i => (shallowReadonly(i.refs) ),
  7177. $parent: i => getPublicInstance(i.parent),
  7178. $root: i => getPublicInstance(i.root),
  7179. $emit: i => i.emit,
  7180. $options: i => (resolveMergedOptions(i) ),
  7181. $forceUpdate: i => () => queueJob(i.update),
  7182. $nextTick: i => nextTick.bind(i.proxy),
  7183. $watch: i => (instanceWatch.bind(i) )
  7184. });
  7185. const PublicInstanceProxyHandlers = {
  7186. get({ _: instance }, key) {
  7187. const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
  7188. // let @vue/reactivity know it should never observe Vue public instances.
  7189. if (key === "__v_skip" /* SKIP */) {
  7190. return true;
  7191. }
  7192. // for internal formatters to know that this is a Vue instance
  7193. if (key === '__isVue') {
  7194. return true;
  7195. }
  7196. // data / props / ctx
  7197. // This getter gets called for every property access on the render context
  7198. // during render and is a major hotspot. The most expensive part of this
  7199. // is the multiple hasOwn() calls. It's much faster to do a simple property
  7200. // access on a plain object, so we use an accessCache object (with null
  7201. // prototype) to memoize what access type a key corresponds to.
  7202. let normalizedProps;
  7203. if (key[0] !== '$') {
  7204. const n = accessCache[key];
  7205. if (n !== undefined) {
  7206. switch (n) {
  7207. case 0 /* SETUP */:
  7208. return setupState[key];
  7209. case 1 /* DATA */:
  7210. return data[key];
  7211. case 3 /* CONTEXT */:
  7212. return ctx[key];
  7213. case 2 /* PROPS */:
  7214. return props[key];
  7215. // default: just fallthrough
  7216. }
  7217. }
  7218. else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
  7219. accessCache[key] = 0 /* SETUP */;
  7220. return setupState[key];
  7221. }
  7222. else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  7223. accessCache[key] = 1 /* DATA */;
  7224. return data[key];
  7225. }
  7226. else if (
  7227. // only cache other properties when instance has declared (thus stable)
  7228. // props
  7229. (normalizedProps = instance.propsOptions[0]) &&
  7230. hasOwn(normalizedProps, key)) {
  7231. accessCache[key] = 2 /* PROPS */;
  7232. return props[key];
  7233. }
  7234. else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  7235. accessCache[key] = 3 /* CONTEXT */;
  7236. return ctx[key];
  7237. }
  7238. else if (!isInBeforeCreate) {
  7239. accessCache[key] = 4 /* OTHER */;
  7240. }
  7241. }
  7242. const publicGetter = publicPropertiesMap[key];
  7243. let cssModule, globalProperties;
  7244. // public $xxx properties
  7245. if (publicGetter) {
  7246. if (key === '$attrs') {
  7247. track(instance, "get" /* GET */, key);
  7248. markAttrsAccessed();
  7249. }
  7250. return publicGetter(instance);
  7251. }
  7252. else if (
  7253. // css module (injected by vue-loader)
  7254. (cssModule = type.__cssModules) &&
  7255. (cssModule = cssModule[key])) {
  7256. return cssModule;
  7257. }
  7258. else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  7259. // user may set custom properties to `this` that start with `$`
  7260. accessCache[key] = 3 /* CONTEXT */;
  7261. return ctx[key];
  7262. }
  7263. else if (
  7264. // global properties
  7265. ((globalProperties = appContext.config.globalProperties),
  7266. hasOwn(globalProperties, key))) {
  7267. return globalProperties[key];
  7268. }
  7269. else if (currentRenderingInstance &&
  7270. (!isString(key) ||
  7271. // #1091 avoid internal isRef/isVNode checks on component instance leading
  7272. // to infinite warning loop
  7273. key.indexOf('__v') !== 0)) {
  7274. if (data !== EMPTY_OBJ &&
  7275. (key[0] === '$' || key[0] === '_') &&
  7276. hasOwn(data, key)) {
  7277. warn(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
  7278. `character ("$" or "_") and is not proxied on the render context.`);
  7279. }
  7280. else if (instance === currentRenderingInstance) {
  7281. warn(`Property ${JSON.stringify(key)} was accessed during render ` +
  7282. `but is not defined on instance.`);
  7283. }
  7284. }
  7285. },
  7286. set({ _: instance }, key, value) {
  7287. const { data, setupState, ctx } = instance;
  7288. if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
  7289. setupState[key] = value;
  7290. }
  7291. else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  7292. data[key] = value;
  7293. }
  7294. else if (hasOwn(instance.props, key)) {
  7295. warn(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
  7296. return false;
  7297. }
  7298. if (key[0] === '$' && key.slice(1) in instance) {
  7299. warn(`Attempting to mutate public property "${key}". ` +
  7300. `Properties starting with $ are reserved and readonly.`, instance);
  7301. return false;
  7302. }
  7303. else {
  7304. if (key in instance.appContext.config.globalProperties) {
  7305. Object.defineProperty(ctx, key, {
  7306. enumerable: true,
  7307. configurable: true,
  7308. value
  7309. });
  7310. }
  7311. else {
  7312. ctx[key] = value;
  7313. }
  7314. }
  7315. return true;
  7316. },
  7317. has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
  7318. let normalizedProps;
  7319. return (accessCache[key] !== undefined ||
  7320. (data !== EMPTY_OBJ && hasOwn(data, key)) ||
  7321. (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
  7322. ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
  7323. hasOwn(ctx, key) ||
  7324. hasOwn(publicPropertiesMap, key) ||
  7325. hasOwn(appContext.config.globalProperties, key));
  7326. }
  7327. };
  7328. {
  7329. PublicInstanceProxyHandlers.ownKeys = (target) => {
  7330. warn(`Avoid app logic that relies on enumerating keys on a component instance. ` +
  7331. `The keys will be empty in production mode to avoid performance overhead.`);
  7332. return Reflect.ownKeys(target);
  7333. };
  7334. }
  7335. const RuntimeCompiledPublicInstanceProxyHandlers = extend({}, PublicInstanceProxyHandlers, {
  7336. get(target, key) {
  7337. // fast path for unscopables when using `with` block
  7338. if (key === Symbol.unscopables) {
  7339. return;
  7340. }
  7341. return PublicInstanceProxyHandlers.get(target, key, target);
  7342. },
  7343. has(_, key) {
  7344. const has = key[0] !== '_' && !isGloballyWhitelisted(key);
  7345. if (!has && PublicInstanceProxyHandlers.has(_, key)) {
  7346. warn(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
  7347. }
  7348. return has;
  7349. }
  7350. });
  7351. // In dev mode, the proxy target exposes the same properties as seen on `this`
  7352. // for easier console inspection. In prod mode it will be an empty object so
  7353. // these properties definitions can be skipped.
  7354. function createRenderContext(instance) {
  7355. const target = {};
  7356. // expose internal instance for proxy handlers
  7357. Object.defineProperty(target, `_`, {
  7358. configurable: true,
  7359. enumerable: false,
  7360. get: () => instance
  7361. });
  7362. // expose public properties
  7363. Object.keys(publicPropertiesMap).forEach(key => {
  7364. Object.defineProperty(target, key, {
  7365. configurable: true,
  7366. enumerable: false,
  7367. get: () => publicPropertiesMap[key](instance),
  7368. // intercepted by the proxy so no need for implementation,
  7369. // but needed to prevent set errors
  7370. set: NOOP
  7371. });
  7372. });
  7373. // expose global properties
  7374. const { globalProperties } = instance.appContext.config;
  7375. Object.keys(globalProperties).forEach(key => {
  7376. Object.defineProperty(target, key, {
  7377. configurable: true,
  7378. enumerable: false,
  7379. get: () => globalProperties[key],
  7380. set: NOOP
  7381. });
  7382. });
  7383. return target;
  7384. }
  7385. // dev only
  7386. function exposePropsOnRenderContext(instance) {
  7387. const { ctx, propsOptions: [propsOptions] } = instance;
  7388. if (propsOptions) {
  7389. Object.keys(propsOptions).forEach(key => {
  7390. Object.defineProperty(ctx, key, {
  7391. enumerable: true,
  7392. configurable: true,
  7393. get: () => instance.props[key],
  7394. set: NOOP
  7395. });
  7396. });
  7397. }
  7398. }
  7399. // dev only
  7400. function exposeSetupStateOnRenderContext(instance) {
  7401. const { ctx, setupState } = instance;
  7402. Object.keys(toRaw(setupState)).forEach(key => {
  7403. if (key[0] === '$' || key[0] === '_') {
  7404. warn(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
  7405. `which are reserved prefixes for Vue internals.`);
  7406. return;
  7407. }
  7408. Object.defineProperty(ctx, key, {
  7409. enumerable: true,
  7410. configurable: true,
  7411. get: () => setupState[key],
  7412. set: NOOP
  7413. });
  7414. });
  7415. }
  7416. const emptyAppContext = createAppContext();
  7417. let uid$2 = 0;
  7418. function createComponentInstance(vnode, parent, suspense) {
  7419. const type = vnode.type;
  7420. // inherit parent app context - or - if root, adopt from root vnode
  7421. const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
  7422. const instance = {
  7423. uid: uid$2++,
  7424. vnode,
  7425. type,
  7426. parent,
  7427. appContext,
  7428. root: null,
  7429. next: null,
  7430. subTree: null,
  7431. update: null,
  7432. render: null,
  7433. proxy: null,
  7434. exposed: null,
  7435. withProxy: null,
  7436. effects: null,
  7437. provides: parent ? parent.provides : Object.create(appContext.provides),
  7438. accessCache: null,
  7439. renderCache: [],
  7440. // local resovled assets
  7441. components: null,
  7442. directives: null,
  7443. // resolved props and emits options
  7444. propsOptions: normalizePropsOptions(type, appContext),
  7445. emitsOptions: normalizeEmitsOptions(type, appContext),
  7446. // emit
  7447. emit: null,
  7448. emitted: null,
  7449. // state
  7450. ctx: EMPTY_OBJ,
  7451. data: EMPTY_OBJ,
  7452. props: EMPTY_OBJ,
  7453. attrs: EMPTY_OBJ,
  7454. slots: EMPTY_OBJ,
  7455. refs: EMPTY_OBJ,
  7456. setupState: EMPTY_OBJ,
  7457. setupContext: null,
  7458. // suspense related
  7459. suspense,
  7460. suspenseId: suspense ? suspense.pendingId : 0,
  7461. asyncDep: null,
  7462. asyncResolved: false,
  7463. // lifecycle hooks
  7464. // not using enums here because it results in computed properties
  7465. isMounted: false,
  7466. isUnmounted: false,
  7467. isDeactivated: false,
  7468. bc: null,
  7469. c: null,
  7470. bm: null,
  7471. m: null,
  7472. bu: null,
  7473. u: null,
  7474. um: null,
  7475. bum: null,
  7476. da: null,
  7477. a: null,
  7478. rtg: null,
  7479. rtc: null,
  7480. ec: null
  7481. };
  7482. {
  7483. instance.ctx = createRenderContext(instance);
  7484. }
  7485. instance.root = parent ? parent.root : instance;
  7486. instance.emit = emit.bind(null, instance);
  7487. return instance;
  7488. }
  7489. let currentInstance = null;
  7490. const getCurrentInstance = () => currentInstance || currentRenderingInstance;
  7491. const setCurrentInstance = (instance) => {
  7492. currentInstance = instance;
  7493. };
  7494. const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
  7495. function validateComponentName(name, config) {
  7496. const appIsNativeTag = config.isNativeTag || NO;
  7497. if (isBuiltInTag(name) || appIsNativeTag(name)) {
  7498. warn('Do not use built-in or reserved HTML elements as component id: ' + name);
  7499. }
  7500. }
  7501. function isStatefulComponent(instance) {
  7502. return instance.vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */;
  7503. }
  7504. let isInSSRComponentSetup = false;
  7505. function setupComponent(instance, isSSR = false) {
  7506. isInSSRComponentSetup = isSSR;
  7507. const { props, children } = instance.vnode;
  7508. const isStateful = isStatefulComponent(instance);
  7509. initProps(instance, props, isStateful, isSSR);
  7510. initSlots(instance, children);
  7511. const setupResult = isStateful
  7512. ? setupStatefulComponent(instance, isSSR)
  7513. : undefined;
  7514. isInSSRComponentSetup = false;
  7515. return setupResult;
  7516. }
  7517. function setupStatefulComponent(instance, isSSR) {
  7518. const Component = instance.type;
  7519. {
  7520. if (Component.name) {
  7521. validateComponentName(Component.name, instance.appContext.config);
  7522. }
  7523. if (Component.components) {
  7524. const names = Object.keys(Component.components);
  7525. for (let i = 0; i < names.length; i++) {
  7526. validateComponentName(names[i], instance.appContext.config);
  7527. }
  7528. }
  7529. if (Component.directives) {
  7530. const names = Object.keys(Component.directives);
  7531. for (let i = 0; i < names.length; i++) {
  7532. validateDirectiveName(names[i]);
  7533. }
  7534. }
  7535. }
  7536. // 0. create render proxy property access cache
  7537. instance.accessCache = Object.create(null);
  7538. // 1. create public instance / render proxy
  7539. // also mark it raw so it's never observed
  7540. instance.proxy = new Proxy(instance.ctx, PublicInstanceProxyHandlers);
  7541. {
  7542. exposePropsOnRenderContext(instance);
  7543. }
  7544. // 2. call setup()
  7545. const { setup } = Component;
  7546. if (setup) {
  7547. const setupContext = (instance.setupContext =
  7548. setup.length > 1 ? createSetupContext(instance) : null);
  7549. currentInstance = instance;
  7550. pauseTracking();
  7551. const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
  7552. resetTracking();
  7553. currentInstance = null;
  7554. if (isPromise(setupResult)) {
  7555. if (isSSR) {
  7556. // return the promise so server-renderer can wait on it
  7557. return setupResult.then((resolvedResult) => {
  7558. handleSetupResult(instance, resolvedResult);
  7559. });
  7560. }
  7561. else {
  7562. // async setup returned Promise.
  7563. // bail here and wait for re-entry.
  7564. instance.asyncDep = setupResult;
  7565. }
  7566. }
  7567. else {
  7568. handleSetupResult(instance, setupResult);
  7569. }
  7570. }
  7571. else {
  7572. finishComponentSetup(instance);
  7573. }
  7574. }
  7575. function handleSetupResult(instance, setupResult, isSSR) {
  7576. if (isFunction(setupResult)) {
  7577. // setup returned an inline render function
  7578. {
  7579. instance.render = setupResult;
  7580. }
  7581. }
  7582. else if (isObject(setupResult)) {
  7583. if (isVNode(setupResult)) {
  7584. warn(`setup() should not return VNodes directly - ` +
  7585. `return a render function instead.`);
  7586. }
  7587. // setup returned bindings.
  7588. // assuming a render function compiled from template is present.
  7589. {
  7590. instance.devtoolsRawSetupState = setupResult;
  7591. }
  7592. instance.setupState = proxyRefs(setupResult);
  7593. {
  7594. exposeSetupStateOnRenderContext(instance);
  7595. }
  7596. }
  7597. else if (setupResult !== undefined) {
  7598. warn(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
  7599. }
  7600. finishComponentSetup(instance);
  7601. }
  7602. let compile;
  7603. /**
  7604. * For runtime-dom to register the compiler.
  7605. * Note the exported method uses any to avoid d.ts relying on the compiler types.
  7606. */
  7607. function registerRuntimeCompiler(_compile) {
  7608. compile = _compile;
  7609. }
  7610. function finishComponentSetup(instance, isSSR) {
  7611. const Component = instance.type;
  7612. // template / render function normalization
  7613. if (!instance.render) {
  7614. // could be set from setup()
  7615. if (compile && Component.template && !Component.render) {
  7616. {
  7617. startMeasure(instance, `compile`);
  7618. }
  7619. Component.render = compile(Component.template, {
  7620. isCustomElement: instance.appContext.config.isCustomElement,
  7621. delimiters: Component.delimiters
  7622. });
  7623. {
  7624. endMeasure(instance, `compile`);
  7625. }
  7626. }
  7627. instance.render = (Component.render || NOOP);
  7628. // for runtime-compiled render functions using `with` blocks, the render
  7629. // proxy used needs a different `has` handler which is more performant and
  7630. // also only allows a whitelist of globals to fallthrough.
  7631. if (instance.render._rc) {
  7632. instance.withProxy = new Proxy(instance.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
  7633. }
  7634. }
  7635. // support for 2.x options
  7636. {
  7637. currentInstance = instance;
  7638. pauseTracking();
  7639. applyOptions(instance, Component);
  7640. resetTracking();
  7641. currentInstance = null;
  7642. }
  7643. // warn missing template/render
  7644. if (!Component.render && instance.render === NOOP) {
  7645. /* istanbul ignore if */
  7646. if (!compile && Component.template) {
  7647. warn(`Component provided template option but ` +
  7648. `runtime compilation is not supported in this build of Vue.` +
  7649. (` Use "vue.global.js" instead.`
  7650. ) /* should not happen */);
  7651. }
  7652. else {
  7653. warn(`Component is missing template or render function.`);
  7654. }
  7655. }
  7656. }
  7657. const attrHandlers = {
  7658. get: (target, key) => {
  7659. {
  7660. markAttrsAccessed();
  7661. }
  7662. return target[key];
  7663. },
  7664. set: () => {
  7665. warn(`setupContext.attrs is readonly.`);
  7666. return false;
  7667. },
  7668. deleteProperty: () => {
  7669. warn(`setupContext.attrs is readonly.`);
  7670. return false;
  7671. }
  7672. };
  7673. function createSetupContext(instance) {
  7674. const expose = exposed => {
  7675. if (instance.exposed) {
  7676. warn(`expose() should be called only once per setup().`);
  7677. }
  7678. instance.exposed = proxyRefs(exposed);
  7679. };
  7680. {
  7681. // We use getters in dev in case libs like test-utils overwrite instance
  7682. // properties (overwrites should not be done in prod)
  7683. return Object.freeze({
  7684. get props() {
  7685. return instance.props;
  7686. },
  7687. get attrs() {
  7688. return new Proxy(instance.attrs, attrHandlers);
  7689. },
  7690. get slots() {
  7691. return shallowReadonly(instance.slots);
  7692. },
  7693. get emit() {
  7694. return (event, ...args) => instance.emit(event, ...args);
  7695. },
  7696. expose
  7697. });
  7698. }
  7699. }
  7700. // record effects created during a component's setup() so that they can be
  7701. // stopped when the component unmounts
  7702. function recordInstanceBoundEffect(effect, instance = currentInstance) {
  7703. if (instance) {
  7704. (instance.effects || (instance.effects = [])).push(effect);
  7705. }
  7706. }
  7707. const classifyRE = /(?:^|[-_])(\w)/g;
  7708. const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
  7709. function getComponentName(Component) {
  7710. return isFunction(Component)
  7711. ? Component.displayName || Component.name
  7712. : Component.name;
  7713. }
  7714. /* istanbul ignore next */
  7715. function formatComponentName(instance, Component, isRoot = false) {
  7716. let name = getComponentName(Component);
  7717. if (!name && Component.__file) {
  7718. const match = Component.__file.match(/([^/\\]+)\.\w+$/);
  7719. if (match) {
  7720. name = match[1];
  7721. }
  7722. }
  7723. if (!name && instance && instance.parent) {
  7724. // try to infer the name based on reverse resolution
  7725. const inferFromRegistry = (registry) => {
  7726. for (const key in registry) {
  7727. if (registry[key] === Component) {
  7728. return key;
  7729. }
  7730. }
  7731. };
  7732. name =
  7733. inferFromRegistry(instance.components ||
  7734. instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
  7735. }
  7736. return name ? classify(name) : isRoot ? `App` : `Anonymous`;
  7737. }
  7738. function isClassComponent(value) {
  7739. return isFunction(value) && '__vccOpts' in value;
  7740. }
  7741. function computed$1(getterOrOptions) {
  7742. const c = computed(getterOrOptions);
  7743. recordInstanceBoundEffect(c.effect);
  7744. return c;
  7745. }
  7746. // implementation
  7747. function defineProps() {
  7748. {
  7749. warn(`defineProps() is a compiler-hint helper that is only usable inside ` +
  7750. `<script setup> of a single file component. Its arguments should be ` +
  7751. `compiled away and passing it at runtime has no effect.`);
  7752. }
  7753. return null;
  7754. }
  7755. // implementation
  7756. function defineEmit() {
  7757. {
  7758. warn(`defineEmit() is a compiler-hint helper that is only usable inside ` +
  7759. `<script setup> of a single file component. Its arguments should be ` +
  7760. `compiled away and passing it at runtime has no effect.`);
  7761. }
  7762. return null;
  7763. }
  7764. function useContext() {
  7765. const i = getCurrentInstance();
  7766. if (!i) {
  7767. warn(`useContext() called without active instance.`);
  7768. }
  7769. return i.setupContext || (i.setupContext = createSetupContext(i));
  7770. }
  7771. // Actual implementation
  7772. function h(type, propsOrChildren, children) {
  7773. const l = arguments.length;
  7774. if (l === 2) {
  7775. if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
  7776. // single vnode without props
  7777. if (isVNode(propsOrChildren)) {
  7778. return createVNode(type, null, [propsOrChildren]);
  7779. }
  7780. // props without children
  7781. return createVNode(type, propsOrChildren);
  7782. }
  7783. else {
  7784. // omit props
  7785. return createVNode(type, null, propsOrChildren);
  7786. }
  7787. }
  7788. else {
  7789. if (l > 3) {
  7790. children = Array.prototype.slice.call(arguments, 2);
  7791. }
  7792. else if (l === 3 && isVNode(children)) {
  7793. children = [children];
  7794. }
  7795. return createVNode(type, propsOrChildren, children);
  7796. }
  7797. }
  7798. const ssrContextKey = Symbol(`ssrContext` );
  7799. const useSSRContext = () => {
  7800. {
  7801. warn(`useSSRContext() is not supported in the global build.`);
  7802. }
  7803. };
  7804. function initCustomFormatter() {
  7805. /* eslint-disable no-restricted-globals */
  7806. if (typeof window === 'undefined') {
  7807. return;
  7808. }
  7809. const vueStyle = { style: 'color:#3ba776' };
  7810. const numberStyle = { style: 'color:#0b1bc9' };
  7811. const stringStyle = { style: 'color:#b62e24' };
  7812. const keywordStyle = { style: 'color:#9d288c' };
  7813. // custom formatter for Chrome
  7814. // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
  7815. const formatter = {
  7816. header(obj) {
  7817. // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
  7818. if (!isObject(obj)) {
  7819. return null;
  7820. }
  7821. if (obj.__isVue) {
  7822. return ['div', vueStyle, `VueInstance`];
  7823. }
  7824. else if (isRef(obj)) {
  7825. return [
  7826. 'div',
  7827. {},
  7828. ['span', vueStyle, genRefFlag(obj)],
  7829. '<',
  7830. formatValue(obj.value),
  7831. `>`
  7832. ];
  7833. }
  7834. else if (isReactive(obj)) {
  7835. return [
  7836. 'div',
  7837. {},
  7838. ['span', vueStyle, 'Reactive'],
  7839. '<',
  7840. formatValue(obj),
  7841. `>${isReadonly(obj) ? ` (readonly)` : ``}`
  7842. ];
  7843. }
  7844. else if (isReadonly(obj)) {
  7845. return [
  7846. 'div',
  7847. {},
  7848. ['span', vueStyle, 'Readonly'],
  7849. '<',
  7850. formatValue(obj),
  7851. '>'
  7852. ];
  7853. }
  7854. return null;
  7855. },
  7856. hasBody(obj) {
  7857. return obj && obj.__isVue;
  7858. },
  7859. body(obj) {
  7860. if (obj && obj.__isVue) {
  7861. return [
  7862. 'div',
  7863. {},
  7864. ...formatInstance(obj.$)
  7865. ];
  7866. }
  7867. }
  7868. };
  7869. function formatInstance(instance) {
  7870. const blocks = [];
  7871. if (instance.type.props && instance.props) {
  7872. blocks.push(createInstanceBlock('props', toRaw(instance.props)));
  7873. }
  7874. if (instance.setupState !== EMPTY_OBJ) {
  7875. blocks.push(createInstanceBlock('setup', instance.setupState));
  7876. }
  7877. if (instance.data !== EMPTY_OBJ) {
  7878. blocks.push(createInstanceBlock('data', toRaw(instance.data)));
  7879. }
  7880. const computed = extractKeys(instance, 'computed');
  7881. if (computed) {
  7882. blocks.push(createInstanceBlock('computed', computed));
  7883. }
  7884. const injected = extractKeys(instance, 'inject');
  7885. if (injected) {
  7886. blocks.push(createInstanceBlock('injected', injected));
  7887. }
  7888. blocks.push([
  7889. 'div',
  7890. {},
  7891. [
  7892. 'span',
  7893. {
  7894. style: keywordStyle.style + ';opacity:0.66'
  7895. },
  7896. '$ (internal): '
  7897. ],
  7898. ['object', { object: instance }]
  7899. ]);
  7900. return blocks;
  7901. }
  7902. function createInstanceBlock(type, target) {
  7903. target = extend({}, target);
  7904. if (!Object.keys(target).length) {
  7905. return ['span', {}];
  7906. }
  7907. return [
  7908. 'div',
  7909. { style: 'line-height:1.25em;margin-bottom:0.6em' },
  7910. [
  7911. 'div',
  7912. {
  7913. style: 'color:#476582'
  7914. },
  7915. type
  7916. ],
  7917. [
  7918. 'div',
  7919. {
  7920. style: 'padding-left:1.25em'
  7921. },
  7922. ...Object.keys(target).map(key => {
  7923. return [
  7924. 'div',
  7925. {},
  7926. ['span', keywordStyle, key + ': '],
  7927. formatValue(target[key], false)
  7928. ];
  7929. })
  7930. ]
  7931. ];
  7932. }
  7933. function formatValue(v, asRaw = true) {
  7934. if (typeof v === 'number') {
  7935. return ['span', numberStyle, v];
  7936. }
  7937. else if (typeof v === 'string') {
  7938. return ['span', stringStyle, JSON.stringify(v)];
  7939. }
  7940. else if (typeof v === 'boolean') {
  7941. return ['span', keywordStyle, v];
  7942. }
  7943. else if (isObject(v)) {
  7944. return ['object', { object: asRaw ? toRaw(v) : v }];
  7945. }
  7946. else {
  7947. return ['span', stringStyle, String(v)];
  7948. }
  7949. }
  7950. function extractKeys(instance, type) {
  7951. const Comp = instance.type;
  7952. if (isFunction(Comp)) {
  7953. return;
  7954. }
  7955. const extracted = {};
  7956. for (const key in instance.ctx) {
  7957. if (isKeyOfType(Comp, key, type)) {
  7958. extracted[key] = instance.ctx[key];
  7959. }
  7960. }
  7961. return extracted;
  7962. }
  7963. function isKeyOfType(Comp, key, type) {
  7964. const opts = Comp[type];
  7965. if ((isArray(opts) && opts.includes(key)) ||
  7966. (isObject(opts) && key in opts)) {
  7967. return true;
  7968. }
  7969. if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
  7970. return true;
  7971. }
  7972. if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
  7973. return true;
  7974. }
  7975. }
  7976. function genRefFlag(v) {
  7977. if (v._shallow) {
  7978. return `ShallowRef`;
  7979. }
  7980. if (v.effect) {
  7981. return `ComputedRef`;
  7982. }
  7983. return `Ref`;
  7984. }
  7985. if (window.devtoolsFormatters) {
  7986. window.devtoolsFormatters.push(formatter);
  7987. }
  7988. else {
  7989. window.devtoolsFormatters = [formatter];
  7990. }
  7991. }
  7992. /**
  7993. * Actual implementation
  7994. */
  7995. function renderList(source, renderItem) {
  7996. let ret;
  7997. if (isArray(source) || isString(source)) {
  7998. ret = new Array(source.length);
  7999. for (let i = 0, l = source.length; i < l; i++) {
  8000. ret[i] = renderItem(source[i], i);
  8001. }
  8002. }
  8003. else if (typeof source === 'number') {
  8004. if (!Number.isInteger(source)) {
  8005. warn(`The v-for range expect an integer value but got ${source}.`);
  8006. return [];
  8007. }
  8008. ret = new Array(source);
  8009. for (let i = 0; i < source; i++) {
  8010. ret[i] = renderItem(i + 1, i);
  8011. }
  8012. }
  8013. else if (isObject(source)) {
  8014. if (source[Symbol.iterator]) {
  8015. ret = Array.from(source, renderItem);
  8016. }
  8017. else {
  8018. const keys = Object.keys(source);
  8019. ret = new Array(keys.length);
  8020. for (let i = 0, l = keys.length; i < l; i++) {
  8021. const key = keys[i];
  8022. ret[i] = renderItem(source[key], key, i);
  8023. }
  8024. }
  8025. }
  8026. else {
  8027. ret = [];
  8028. }
  8029. return ret;
  8030. }
  8031. /**
  8032. * For prefixing keys in v-on="obj" with "on"
  8033. * @private
  8034. */
  8035. function toHandlers(obj) {
  8036. const ret = {};
  8037. if (!isObject(obj)) {
  8038. warn(`v-on with no argument expects an object value.`);
  8039. return ret;
  8040. }
  8041. for (const key in obj) {
  8042. ret[toHandlerKey(key)] = obj[key];
  8043. }
  8044. return ret;
  8045. }
  8046. /**
  8047. * Compiler runtime helper for creating dynamic slots object
  8048. * @private
  8049. */
  8050. function createSlots(slots, dynamicSlots) {
  8051. for (let i = 0; i < dynamicSlots.length; i++) {
  8052. const slot = dynamicSlots[i];
  8053. // array of dynamic slot generated by <template v-for="..." #[...]>
  8054. if (isArray(slot)) {
  8055. for (let j = 0; j < slot.length; j++) {
  8056. slots[slot[j].name] = slot[j].fn;
  8057. }
  8058. }
  8059. else if (slot) {
  8060. // conditional single slot generated by <template v-if="..." #foo>
  8061. slots[slot.name] = slot.fn;
  8062. }
  8063. }
  8064. return slots;
  8065. }
  8066. // Core API ------------------------------------------------------------------
  8067. const version = "3.0.6";
  8068. /**
  8069. * SSR utils for \@vue/server-renderer. Only exposed in cjs builds.
  8070. * @internal
  8071. */
  8072. const ssrUtils = (null);
  8073. const svgNS = 'http://www.w3.org/2000/svg';
  8074. const doc = (typeof document !== 'undefined' ? document : null);
  8075. let tempContainer;
  8076. let tempSVGContainer;
  8077. const nodeOps = {
  8078. insert: (child, parent, anchor) => {
  8079. parent.insertBefore(child, anchor || null);
  8080. },
  8081. remove: child => {
  8082. const parent = child.parentNode;
  8083. if (parent) {
  8084. parent.removeChild(child);
  8085. }
  8086. },
  8087. createElement: (tag, isSVG, is) => isSVG
  8088. ? doc.createElementNS(svgNS, tag)
  8089. : doc.createElement(tag, is ? { is } : undefined),
  8090. createText: text => doc.createTextNode(text),
  8091. createComment: text => doc.createComment(text),
  8092. setText: (node, text) => {
  8093. node.nodeValue = text;
  8094. },
  8095. setElementText: (el, text) => {
  8096. el.textContent = text;
  8097. },
  8098. parentNode: node => node.parentNode,
  8099. nextSibling: node => node.nextSibling,
  8100. querySelector: selector => doc.querySelector(selector),
  8101. setScopeId(el, id) {
  8102. el.setAttribute(id, '');
  8103. },
  8104. cloneNode(el) {
  8105. return el.cloneNode(true);
  8106. },
  8107. // __UNSAFE__
  8108. // Reason: innerHTML.
  8109. // Static content here can only come from compiled templates.
  8110. // As long as the user only uses trusted templates, this is safe.
  8111. insertStaticContent(content, parent, anchor, isSVG) {
  8112. const temp = isSVG
  8113. ? tempSVGContainer ||
  8114. (tempSVGContainer = doc.createElementNS(svgNS, 'svg'))
  8115. : tempContainer || (tempContainer = doc.createElement('div'));
  8116. temp.innerHTML = content;
  8117. const first = temp.firstChild;
  8118. let node = first;
  8119. let last = node;
  8120. while (node) {
  8121. last = node;
  8122. nodeOps.insert(node, parent, anchor);
  8123. node = temp.firstChild;
  8124. }
  8125. return [first, last];
  8126. }
  8127. };
  8128. // compiler should normalize class + :class bindings on the same element
  8129. // into a single binding ['staticClass', dynamic]
  8130. function patchClass(el, value, isSVG) {
  8131. if (value == null) {
  8132. value = '';
  8133. }
  8134. if (isSVG) {
  8135. el.setAttribute('class', value);
  8136. }
  8137. else {
  8138. // directly setting className should be faster than setAttribute in theory
  8139. // if this is an element during a transition, take the temporary transition
  8140. // classes into account.
  8141. const transitionClasses = el._vtc;
  8142. if (transitionClasses) {
  8143. value = (value
  8144. ? [value, ...transitionClasses]
  8145. : [...transitionClasses]).join(' ');
  8146. }
  8147. el.className = value;
  8148. }
  8149. }
  8150. function patchStyle(el, prev, next) {
  8151. const style = el.style;
  8152. if (!next) {
  8153. el.removeAttribute('style');
  8154. }
  8155. else if (isString(next)) {
  8156. if (prev !== next) {
  8157. style.cssText = next;
  8158. }
  8159. }
  8160. else {
  8161. for (const key in next) {
  8162. setStyle(style, key, next[key]);
  8163. }
  8164. if (prev && !isString(prev)) {
  8165. for (const key in prev) {
  8166. if (next[key] == null) {
  8167. setStyle(style, key, '');
  8168. }
  8169. }
  8170. }
  8171. }
  8172. }
  8173. const importantRE = /\s*!important$/;
  8174. function setStyle(style, name, val) {
  8175. if (isArray(val)) {
  8176. val.forEach(v => setStyle(style, name, v));
  8177. }
  8178. else {
  8179. if (name.startsWith('--')) {
  8180. // custom property definition
  8181. style.setProperty(name, val);
  8182. }
  8183. else {
  8184. const prefixed = autoPrefix(style, name);
  8185. if (importantRE.test(val)) {
  8186. // !important
  8187. style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
  8188. }
  8189. else {
  8190. style[prefixed] = val;
  8191. }
  8192. }
  8193. }
  8194. }
  8195. const prefixes = ['Webkit', 'Moz', 'ms'];
  8196. const prefixCache = {};
  8197. function autoPrefix(style, rawName) {
  8198. const cached = prefixCache[rawName];
  8199. if (cached) {
  8200. return cached;
  8201. }
  8202. let name = camelize(rawName);
  8203. if (name !== 'filter' && name in style) {
  8204. return (prefixCache[rawName] = name);
  8205. }
  8206. name = capitalize(name);
  8207. for (let i = 0; i < prefixes.length; i++) {
  8208. const prefixed = prefixes[i] + name;
  8209. if (prefixed in style) {
  8210. return (prefixCache[rawName] = prefixed);
  8211. }
  8212. }
  8213. return rawName;
  8214. }
  8215. const xlinkNS = 'http://www.w3.org/1999/xlink';
  8216. function patchAttr(el, key, value, isSVG) {
  8217. if (isSVG && key.startsWith('xlink:')) {
  8218. if (value == null) {
  8219. el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
  8220. }
  8221. else {
  8222. el.setAttributeNS(xlinkNS, key, value);
  8223. }
  8224. }
  8225. else {
  8226. // note we are only checking boolean attributes that don't have a
  8227. // corresponding dom prop of the same name here.
  8228. const isBoolean = isSpecialBooleanAttr(key);
  8229. if (value == null || (isBoolean && value === false)) {
  8230. el.removeAttribute(key);
  8231. }
  8232. else {
  8233. el.setAttribute(key, isBoolean ? '' : value);
  8234. }
  8235. }
  8236. }
  8237. // __UNSAFE__
  8238. // functions. The user is responsible for using them with only trusted content.
  8239. function patchDOMProp(el, key, value,
  8240. // the following args are passed only due to potential innerHTML/textContent
  8241. // overriding existing VNodes, in which case the old tree must be properly
  8242. // unmounted.
  8243. prevChildren, parentComponent, parentSuspense, unmountChildren) {
  8244. if (key === 'innerHTML' || key === 'textContent') {
  8245. if (prevChildren) {
  8246. unmountChildren(prevChildren, parentComponent, parentSuspense);
  8247. }
  8248. el[key] = value == null ? '' : value;
  8249. return;
  8250. }
  8251. if (key === 'value' && el.tagName !== 'PROGRESS') {
  8252. // store value as _value as well since
  8253. // non-string values will be stringified.
  8254. el._value = value;
  8255. const newValue = value == null ? '' : value;
  8256. if (el.value !== newValue) {
  8257. el.value = newValue;
  8258. }
  8259. return;
  8260. }
  8261. if (value === '' || value == null) {
  8262. const type = typeof el[key];
  8263. if (value === '' && type === 'boolean') {
  8264. // e.g. <select multiple> compiles to { multiple: '' }
  8265. el[key] = true;
  8266. return;
  8267. }
  8268. else if (value == null && type === 'string') {
  8269. // e.g. <div :id="null">
  8270. el[key] = '';
  8271. el.removeAttribute(key);
  8272. return;
  8273. }
  8274. else if (type === 'number') {
  8275. // e.g. <img :width="null">
  8276. el[key] = 0;
  8277. el.removeAttribute(key);
  8278. return;
  8279. }
  8280. }
  8281. // some properties perform value validation and throw
  8282. try {
  8283. el[key] = value;
  8284. }
  8285. catch (e) {
  8286. {
  8287. warn(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
  8288. `value ${value} is invalid.`, e);
  8289. }
  8290. }
  8291. }
  8292. // Async edge case fix requires storing an event listener's attach timestamp.
  8293. let _getNow = Date.now;
  8294. // Determine what event timestamp the browser is using. Annoyingly, the
  8295. // timestamp can either be hi-res (relative to page load) or low-res
  8296. // (relative to UNIX epoch), so in order to compare time we have to use the
  8297. // same timestamp type when saving the flush timestamp.
  8298. if (typeof document !== 'undefined' &&
  8299. _getNow() > document.createEvent('Event').timeStamp) {
  8300. // if the low-res timestamp which is bigger than the event timestamp
  8301. // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
  8302. // and we need to use the hi-res version for event listeners as well.
  8303. _getNow = () => performance.now();
  8304. }
  8305. // To avoid the overhead of repeatedly calling performance.now(), we cache
  8306. // and use the same timestamp for all event listeners attached in the same tick.
  8307. let cachedNow = 0;
  8308. const p = Promise.resolve();
  8309. const reset = () => {
  8310. cachedNow = 0;
  8311. };
  8312. const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
  8313. function addEventListener(el, event, handler, options) {
  8314. el.addEventListener(event, handler, options);
  8315. }
  8316. function removeEventListener(el, event, handler, options) {
  8317. el.removeEventListener(event, handler, options);
  8318. }
  8319. function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
  8320. // vei = vue event invokers
  8321. const invokers = el._vei || (el._vei = {});
  8322. const existingInvoker = invokers[rawName];
  8323. if (nextValue && existingInvoker) {
  8324. // patch
  8325. existingInvoker.value = nextValue;
  8326. }
  8327. else {
  8328. const [name, options] = parseName(rawName);
  8329. if (nextValue) {
  8330. // add
  8331. const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
  8332. addEventListener(el, name, invoker, options);
  8333. }
  8334. else if (existingInvoker) {
  8335. // remove
  8336. removeEventListener(el, name, existingInvoker, options);
  8337. invokers[rawName] = undefined;
  8338. }
  8339. }
  8340. }
  8341. const optionsModifierRE = /(?:Once|Passive|Capture)$/;
  8342. function parseName(name) {
  8343. let options;
  8344. if (optionsModifierRE.test(name)) {
  8345. options = {};
  8346. let m;
  8347. while ((m = name.match(optionsModifierRE))) {
  8348. name = name.slice(0, name.length - m[0].length);
  8349. options[m[0].toLowerCase()] = true;
  8350. }
  8351. }
  8352. return [hyphenate(name.slice(2)), options];
  8353. }
  8354. function createInvoker(initialValue, instance) {
  8355. const invoker = (e) => {
  8356. // async edge case #6566: inner click event triggers patch, event handler
  8357. // attached to outer element during patch, and triggered again. This
  8358. // happens because browsers fire microtask ticks between event propagation.
  8359. // the solution is simple: we save the timestamp when a handler is attached,
  8360. // and the handler would only fire if the event passed to it was fired
  8361. // AFTER it was attached.
  8362. const timeStamp = e.timeStamp || _getNow();
  8363. if (timeStamp >= invoker.attached - 1) {
  8364. callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
  8365. }
  8366. };
  8367. invoker.value = initialValue;
  8368. invoker.attached = getNow();
  8369. return invoker;
  8370. }
  8371. function patchStopImmediatePropagation(e, value) {
  8372. if (isArray(value)) {
  8373. const originalStop = e.stopImmediatePropagation;
  8374. e.stopImmediatePropagation = () => {
  8375. originalStop.call(e);
  8376. e._stopped = true;
  8377. };
  8378. return value.map(fn => (e) => !e._stopped && fn(e));
  8379. }
  8380. else {
  8381. return value;
  8382. }
  8383. }
  8384. const nativeOnRE = /^on[a-z]/;
  8385. const forcePatchProp = (_, key) => key === 'value';
  8386. const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
  8387. switch (key) {
  8388. // special
  8389. case 'class':
  8390. patchClass(el, nextValue, isSVG);
  8391. break;
  8392. case 'style':
  8393. patchStyle(el, prevValue, nextValue);
  8394. break;
  8395. default:
  8396. if (isOn(key)) {
  8397. // ignore v-model listeners
  8398. if (!isModelListener(key)) {
  8399. patchEvent(el, key, prevValue, nextValue, parentComponent);
  8400. }
  8401. }
  8402. else if (shouldSetAsProp(el, key, nextValue, isSVG)) {
  8403. patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
  8404. }
  8405. else {
  8406. // special case for <input v-model type="checkbox"> with
  8407. // :true-value & :false-value
  8408. // store value as dom properties since non-string values will be
  8409. // stringified.
  8410. if (key === 'true-value') {
  8411. el._trueValue = nextValue;
  8412. }
  8413. else if (key === 'false-value') {
  8414. el._falseValue = nextValue;
  8415. }
  8416. patchAttr(el, key, nextValue, isSVG);
  8417. }
  8418. break;
  8419. }
  8420. };
  8421. function shouldSetAsProp(el, key, value, isSVG) {
  8422. if (isSVG) {
  8423. // most keys must be set as attribute on svg elements to work
  8424. // ...except innerHTML
  8425. if (key === 'innerHTML') {
  8426. return true;
  8427. }
  8428. // or native onclick with function values
  8429. if (key in el && nativeOnRE.test(key) && isFunction(value)) {
  8430. return true;
  8431. }
  8432. return false;
  8433. }
  8434. // spellcheck and draggable are numerated attrs, however their
  8435. // corresponding DOM properties are actually booleans - this leads to
  8436. // setting it with a string "false" value leading it to be coerced to
  8437. // `true`, so we need to always treat them as attributes.
  8438. // Note that `contentEditable` doesn't have this problem: its DOM
  8439. // property is also enumerated string values.
  8440. if (key === 'spellcheck' || key === 'draggable') {
  8441. return false;
  8442. }
  8443. // #1787, #2840 form property on form elements is readonly and must be set as
  8444. // attribute.
  8445. if (key === 'form') {
  8446. return false;
  8447. }
  8448. // #1526 <input list> must be set as attribute
  8449. if (key === 'list' && el.tagName === 'INPUT') {
  8450. return false;
  8451. }
  8452. // #2766 <textarea type> must be set as attribute
  8453. if (key === 'type' && el.tagName === 'TEXTAREA') {
  8454. return false;
  8455. }
  8456. // native onclick with string value, must be set as attribute
  8457. if (nativeOnRE.test(key) && isString(value)) {
  8458. return false;
  8459. }
  8460. return key in el;
  8461. }
  8462. function useCssModule(name = '$style') {
  8463. /* istanbul ignore else */
  8464. {
  8465. {
  8466. warn(`useCssModule() is not supported in the global build.`);
  8467. }
  8468. return EMPTY_OBJ;
  8469. }
  8470. }
  8471. /**
  8472. * Runtime helper for SFC's CSS variable injection feature.
  8473. * @private
  8474. */
  8475. function useCssVars(getter) {
  8476. const instance = getCurrentInstance();
  8477. /* istanbul ignore next */
  8478. if (!instance) {
  8479. warn(`useCssVars is called without current active component instance.`);
  8480. return;
  8481. }
  8482. const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy));
  8483. onMounted(() => watchEffect(setVars, { flush: 'post' }));
  8484. onUpdated(setVars);
  8485. }
  8486. function setVarsOnVNode(vnode, vars) {
  8487. if (vnode.shapeFlag & 128 /* SUSPENSE */) {
  8488. const suspense = vnode.suspense;
  8489. vnode = suspense.activeBranch;
  8490. if (suspense.pendingBranch && !suspense.isHydrating) {
  8491. suspense.effects.push(() => {
  8492. setVarsOnVNode(suspense.activeBranch, vars);
  8493. });
  8494. }
  8495. }
  8496. // drill down HOCs until it's a non-component vnode
  8497. while (vnode.component) {
  8498. vnode = vnode.component.subTree;
  8499. }
  8500. if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
  8501. const style = vnode.el.style;
  8502. for (const key in vars) {
  8503. style.setProperty(`--${key}`, vars[key]);
  8504. }
  8505. }
  8506. else if (vnode.type === Fragment) {
  8507. vnode.children.forEach(c => setVarsOnVNode(c, vars));
  8508. }
  8509. }
  8510. const TRANSITION = 'transition';
  8511. const ANIMATION = 'animation';
  8512. // DOM Transition is a higher-order-component based on the platform-agnostic
  8513. // base Transition component, with DOM-specific logic.
  8514. const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
  8515. Transition.displayName = 'Transition';
  8516. const DOMTransitionPropsValidators = {
  8517. name: String,
  8518. type: String,
  8519. css: {
  8520. type: Boolean,
  8521. default: true
  8522. },
  8523. duration: [String, Number, Object],
  8524. enterFromClass: String,
  8525. enterActiveClass: String,
  8526. enterToClass: String,
  8527. appearFromClass: String,
  8528. appearActiveClass: String,
  8529. appearToClass: String,
  8530. leaveFromClass: String,
  8531. leaveActiveClass: String,
  8532. leaveToClass: String
  8533. };
  8534. const TransitionPropsValidators = (Transition.props = /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
  8535. function resolveTransitionProps(rawProps) {
  8536. let { name = 'v', type, css = true, duration, enterFromClass = `${name}-enter-from`, enterActiveClass = `${name}-enter-active`, enterToClass = `${name}-enter-to`, appearFromClass = enterFromClass, appearActiveClass = enterActiveClass, appearToClass = enterToClass, leaveFromClass = `${name}-leave-from`, leaveActiveClass = `${name}-leave-active`, leaveToClass = `${name}-leave-to` } = rawProps;
  8537. const baseProps = {};
  8538. for (const key in rawProps) {
  8539. if (!(key in DOMTransitionPropsValidators)) {
  8540. baseProps[key] = rawProps[key];
  8541. }
  8542. }
  8543. if (!css) {
  8544. return baseProps;
  8545. }
  8546. const durations = normalizeDuration(duration);
  8547. const enterDuration = durations && durations[0];
  8548. const leaveDuration = durations && durations[1];
  8549. const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
  8550. const finishEnter = (el, isAppear, done) => {
  8551. removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
  8552. removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
  8553. done && done();
  8554. };
  8555. const finishLeave = (el, done) => {
  8556. removeTransitionClass(el, leaveToClass);
  8557. removeTransitionClass(el, leaveActiveClass);
  8558. done && done();
  8559. };
  8560. const makeEnterHook = (isAppear) => {
  8561. return (el, done) => {
  8562. const hook = isAppear ? onAppear : onEnter;
  8563. const resolve = () => finishEnter(el, isAppear, done);
  8564. hook && hook(el, resolve);
  8565. nextFrame(() => {
  8566. removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
  8567. addTransitionClass(el, isAppear ? appearToClass : enterToClass);
  8568. if (!(hook && hook.length > 1)) {
  8569. whenTransitionEnds(el, type, enterDuration, resolve);
  8570. }
  8571. });
  8572. };
  8573. };
  8574. return extend(baseProps, {
  8575. onBeforeEnter(el) {
  8576. onBeforeEnter && onBeforeEnter(el);
  8577. addTransitionClass(el, enterFromClass);
  8578. addTransitionClass(el, enterActiveClass);
  8579. },
  8580. onBeforeAppear(el) {
  8581. onBeforeAppear && onBeforeAppear(el);
  8582. addTransitionClass(el, appearFromClass);
  8583. addTransitionClass(el, appearActiveClass);
  8584. },
  8585. onEnter: makeEnterHook(false),
  8586. onAppear: makeEnterHook(true),
  8587. onLeave(el, done) {
  8588. const resolve = () => finishLeave(el, done);
  8589. addTransitionClass(el, leaveFromClass);
  8590. // force reflow so *-leave-from classes immediately take effect (#2593)
  8591. forceReflow();
  8592. addTransitionClass(el, leaveActiveClass);
  8593. nextFrame(() => {
  8594. removeTransitionClass(el, leaveFromClass);
  8595. addTransitionClass(el, leaveToClass);
  8596. if (!(onLeave && onLeave.length > 1)) {
  8597. whenTransitionEnds(el, type, leaveDuration, resolve);
  8598. }
  8599. });
  8600. onLeave && onLeave(el, resolve);
  8601. },
  8602. onEnterCancelled(el) {
  8603. finishEnter(el, false);
  8604. onEnterCancelled && onEnterCancelled(el);
  8605. },
  8606. onAppearCancelled(el) {
  8607. finishEnter(el, true);
  8608. onAppearCancelled && onAppearCancelled(el);
  8609. },
  8610. onLeaveCancelled(el) {
  8611. finishLeave(el);
  8612. onLeaveCancelled && onLeaveCancelled(el);
  8613. }
  8614. });
  8615. }
  8616. function normalizeDuration(duration) {
  8617. if (duration == null) {
  8618. return null;
  8619. }
  8620. else if (isObject(duration)) {
  8621. return [NumberOf(duration.enter), NumberOf(duration.leave)];
  8622. }
  8623. else {
  8624. const n = NumberOf(duration);
  8625. return [n, n];
  8626. }
  8627. }
  8628. function NumberOf(val) {
  8629. const res = toNumber(val);
  8630. validateDuration(res);
  8631. return res;
  8632. }
  8633. function validateDuration(val) {
  8634. if (typeof val !== 'number') {
  8635. warn(`<transition> explicit duration is not a valid number - ` +
  8636. `got ${JSON.stringify(val)}.`);
  8637. }
  8638. else if (isNaN(val)) {
  8639. warn(`<transition> explicit duration is NaN - ` +
  8640. 'the duration expression might be incorrect.');
  8641. }
  8642. }
  8643. function addTransitionClass(el, cls) {
  8644. cls.split(/\s+/).forEach(c => c && el.classList.add(c));
  8645. (el._vtc ||
  8646. (el._vtc = new Set())).add(cls);
  8647. }
  8648. function removeTransitionClass(el, cls) {
  8649. cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
  8650. const { _vtc } = el;
  8651. if (_vtc) {
  8652. _vtc.delete(cls);
  8653. if (!_vtc.size) {
  8654. el._vtc = undefined;
  8655. }
  8656. }
  8657. }
  8658. function nextFrame(cb) {
  8659. requestAnimationFrame(() => {
  8660. requestAnimationFrame(cb);
  8661. });
  8662. }
  8663. let endId = 0;
  8664. function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
  8665. const id = (el._endId = ++endId);
  8666. const resolveIfNotStale = () => {
  8667. if (id === el._endId) {
  8668. resolve();
  8669. }
  8670. };
  8671. if (explicitTimeout) {
  8672. return setTimeout(resolveIfNotStale, explicitTimeout);
  8673. }
  8674. const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
  8675. if (!type) {
  8676. return resolve();
  8677. }
  8678. const endEvent = type + 'end';
  8679. let ended = 0;
  8680. const end = () => {
  8681. el.removeEventListener(endEvent, onEnd);
  8682. resolveIfNotStale();
  8683. };
  8684. const onEnd = (e) => {
  8685. if (e.target === el && ++ended >= propCount) {
  8686. end();
  8687. }
  8688. };
  8689. setTimeout(() => {
  8690. if (ended < propCount) {
  8691. end();
  8692. }
  8693. }, timeout + 1);
  8694. el.addEventListener(endEvent, onEnd);
  8695. }
  8696. function getTransitionInfo(el, expectedType) {
  8697. const styles = window.getComputedStyle(el);
  8698. // JSDOM may return undefined for transition properties
  8699. const getStyleProperties = (key) => (styles[key] || '').split(', ');
  8700. const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
  8701. const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
  8702. const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
  8703. const animationDelays = getStyleProperties(ANIMATION + 'Delay');
  8704. const animationDurations = getStyleProperties(ANIMATION + 'Duration');
  8705. const animationTimeout = getTimeout(animationDelays, animationDurations);
  8706. let type = null;
  8707. let timeout = 0;
  8708. let propCount = 0;
  8709. /* istanbul ignore if */
  8710. if (expectedType === TRANSITION) {
  8711. if (transitionTimeout > 0) {
  8712. type = TRANSITION;
  8713. timeout = transitionTimeout;
  8714. propCount = transitionDurations.length;
  8715. }
  8716. }
  8717. else if (expectedType === ANIMATION) {
  8718. if (animationTimeout > 0) {
  8719. type = ANIMATION;
  8720. timeout = animationTimeout;
  8721. propCount = animationDurations.length;
  8722. }
  8723. }
  8724. else {
  8725. timeout = Math.max(transitionTimeout, animationTimeout);
  8726. type =
  8727. timeout > 0
  8728. ? transitionTimeout > animationTimeout
  8729. ? TRANSITION
  8730. : ANIMATION
  8731. : null;
  8732. propCount = type
  8733. ? type === TRANSITION
  8734. ? transitionDurations.length
  8735. : animationDurations.length
  8736. : 0;
  8737. }
  8738. const hasTransform = type === TRANSITION &&
  8739. /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
  8740. return {
  8741. type,
  8742. timeout,
  8743. propCount,
  8744. hasTransform
  8745. };
  8746. }
  8747. function getTimeout(delays, durations) {
  8748. while (delays.length < durations.length) {
  8749. delays = delays.concat(delays);
  8750. }
  8751. return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
  8752. }
  8753. // Old versions of Chromium (below 61.0.3163.100) formats floating pointer
  8754. // numbers in a locale-dependent way, using a comma instead of a dot.
  8755. // If comma is not replaced with a dot, the input will be rounded down
  8756. // (i.e. acting as a floor function) causing unexpected behaviors
  8757. function toMs(s) {
  8758. return Number(s.slice(0, -1).replace(',', '.')) * 1000;
  8759. }
  8760. // synchronously force layout to put elements into a certain state
  8761. function forceReflow() {
  8762. return document.body.offsetHeight;
  8763. }
  8764. const positionMap = new WeakMap();
  8765. const newPositionMap = new WeakMap();
  8766. const TransitionGroupImpl = {
  8767. name: 'TransitionGroup',
  8768. props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
  8769. tag: String,
  8770. moveClass: String
  8771. }),
  8772. setup(props, { slots }) {
  8773. const instance = getCurrentInstance();
  8774. const state = useTransitionState();
  8775. let prevChildren;
  8776. let children;
  8777. onUpdated(() => {
  8778. // children is guaranteed to exist after initial render
  8779. if (!prevChildren.length) {
  8780. return;
  8781. }
  8782. const moveClass = props.moveClass || `${props.name || 'v'}-move`;
  8783. if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
  8784. return;
  8785. }
  8786. // we divide the work into three loops to avoid mixing DOM reads and writes
  8787. // in each iteration - which helps prevent layout thrashing.
  8788. prevChildren.forEach(callPendingCbs);
  8789. prevChildren.forEach(recordPosition);
  8790. const movedChildren = prevChildren.filter(applyTranslation);
  8791. // force reflow to put everything in position
  8792. forceReflow();
  8793. movedChildren.forEach(c => {
  8794. const el = c.el;
  8795. const style = el.style;
  8796. addTransitionClass(el, moveClass);
  8797. style.transform = style.webkitTransform = style.transitionDuration = '';
  8798. const cb = (el._moveCb = (e) => {
  8799. if (e && e.target !== el) {
  8800. return;
  8801. }
  8802. if (!e || /transform$/.test(e.propertyName)) {
  8803. el.removeEventListener('transitionend', cb);
  8804. el._moveCb = null;
  8805. removeTransitionClass(el, moveClass);
  8806. }
  8807. });
  8808. el.addEventListener('transitionend', cb);
  8809. });
  8810. });
  8811. return () => {
  8812. const rawProps = toRaw(props);
  8813. const cssTransitionProps = resolveTransitionProps(rawProps);
  8814. const tag = rawProps.tag || Fragment;
  8815. prevChildren = children;
  8816. children = slots.default ? getTransitionRawChildren(slots.default()) : [];
  8817. for (let i = 0; i < children.length; i++) {
  8818. const child = children[i];
  8819. if (child.key != null) {
  8820. setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
  8821. }
  8822. else {
  8823. warn(`<TransitionGroup> children must be keyed.`);
  8824. }
  8825. }
  8826. if (prevChildren) {
  8827. for (let i = 0; i < prevChildren.length; i++) {
  8828. const child = prevChildren[i];
  8829. setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
  8830. positionMap.set(child, child.el.getBoundingClientRect());
  8831. }
  8832. }
  8833. return createVNode(tag, null, children);
  8834. };
  8835. }
  8836. };
  8837. const TransitionGroup = TransitionGroupImpl;
  8838. function callPendingCbs(c) {
  8839. const el = c.el;
  8840. if (el._moveCb) {
  8841. el._moveCb();
  8842. }
  8843. if (el._enterCb) {
  8844. el._enterCb();
  8845. }
  8846. }
  8847. function recordPosition(c) {
  8848. newPositionMap.set(c, c.el.getBoundingClientRect());
  8849. }
  8850. function applyTranslation(c) {
  8851. const oldPos = positionMap.get(c);
  8852. const newPos = newPositionMap.get(c);
  8853. const dx = oldPos.left - newPos.left;
  8854. const dy = oldPos.top - newPos.top;
  8855. if (dx || dy) {
  8856. const s = c.el.style;
  8857. s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
  8858. s.transitionDuration = '0s';
  8859. return c;
  8860. }
  8861. }
  8862. function hasCSSTransform(el, root, moveClass) {
  8863. // Detect whether an element with the move class applied has
  8864. // CSS transitions. Since the element may be inside an entering
  8865. // transition at this very moment, we make a clone of it and remove
  8866. // all other transition classes applied to ensure only the move class
  8867. // is applied.
  8868. const clone = el.cloneNode();
  8869. if (el._vtc) {
  8870. el._vtc.forEach(cls => {
  8871. cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
  8872. });
  8873. }
  8874. moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
  8875. clone.style.display = 'none';
  8876. const container = (root.nodeType === 1
  8877. ? root
  8878. : root.parentNode);
  8879. container.appendChild(clone);
  8880. const { hasTransform } = getTransitionInfo(clone);
  8881. container.removeChild(clone);
  8882. return hasTransform;
  8883. }
  8884. const getModelAssigner = (vnode) => {
  8885. const fn = vnode.props['onUpdate:modelValue'];
  8886. return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
  8887. };
  8888. function onCompositionStart(e) {
  8889. e.target.composing = true;
  8890. }
  8891. function onCompositionEnd(e) {
  8892. const target = e.target;
  8893. if (target.composing) {
  8894. target.composing = false;
  8895. trigger$1(target, 'input');
  8896. }
  8897. }
  8898. function trigger$1(el, type) {
  8899. const e = document.createEvent('HTMLEvents');
  8900. e.initEvent(type, true, true);
  8901. el.dispatchEvent(e);
  8902. }
  8903. // We are exporting the v-model runtime directly as vnode hooks so that it can
  8904. // be tree-shaken in case v-model is never used.
  8905. const vModelText = {
  8906. created(el, { modifiers: { lazy, trim, number } }, vnode) {
  8907. el._assign = getModelAssigner(vnode);
  8908. const castToNumber = number || el.type === 'number';
  8909. addEventListener(el, lazy ? 'change' : 'input', e => {
  8910. if (e.target.composing)
  8911. return;
  8912. let domValue = el.value;
  8913. if (trim) {
  8914. domValue = domValue.trim();
  8915. }
  8916. else if (castToNumber) {
  8917. domValue = toNumber(domValue);
  8918. }
  8919. el._assign(domValue);
  8920. });
  8921. if (trim) {
  8922. addEventListener(el, 'change', () => {
  8923. el.value = el.value.trim();
  8924. });
  8925. }
  8926. if (!lazy) {
  8927. addEventListener(el, 'compositionstart', onCompositionStart);
  8928. addEventListener(el, 'compositionend', onCompositionEnd);
  8929. // Safari < 10.2 & UIWebView doesn't fire compositionend when
  8930. // switching focus before confirming composition choice
  8931. // this also fixes the issue where some browsers e.g. iOS Chrome
  8932. // fires "change" instead of "input" on autocomplete.
  8933. addEventListener(el, 'change', onCompositionEnd);
  8934. }
  8935. },
  8936. // set value on mounted so it's after min/max for type="range"
  8937. mounted(el, { value }) {
  8938. el.value = value == null ? '' : value;
  8939. },
  8940. beforeUpdate(el, { value, modifiers: { trim, number } }, vnode) {
  8941. el._assign = getModelAssigner(vnode);
  8942. // avoid clearing unresolved text. #2302
  8943. if (el.composing)
  8944. return;
  8945. if (document.activeElement === el) {
  8946. if (trim && el.value.trim() === value) {
  8947. return;
  8948. }
  8949. if ((number || el.type === 'number') && toNumber(el.value) === value) {
  8950. return;
  8951. }
  8952. }
  8953. const newValue = value == null ? '' : value;
  8954. if (el.value !== newValue) {
  8955. el.value = newValue;
  8956. }
  8957. }
  8958. };
  8959. const vModelCheckbox = {
  8960. created(el, _, vnode) {
  8961. el._assign = getModelAssigner(vnode);
  8962. addEventListener(el, 'change', () => {
  8963. const modelValue = el._modelValue;
  8964. const elementValue = getValue(el);
  8965. const checked = el.checked;
  8966. const assign = el._assign;
  8967. if (isArray(modelValue)) {
  8968. const index = looseIndexOf(modelValue, elementValue);
  8969. const found = index !== -1;
  8970. if (checked && !found) {
  8971. assign(modelValue.concat(elementValue));
  8972. }
  8973. else if (!checked && found) {
  8974. const filtered = [...modelValue];
  8975. filtered.splice(index, 1);
  8976. assign(filtered);
  8977. }
  8978. }
  8979. else if (isSet(modelValue)) {
  8980. const cloned = new Set(modelValue);
  8981. if (checked) {
  8982. cloned.add(elementValue);
  8983. }
  8984. else {
  8985. cloned.delete(elementValue);
  8986. }
  8987. assign(cloned);
  8988. }
  8989. else {
  8990. assign(getCheckboxValue(el, checked));
  8991. }
  8992. });
  8993. },
  8994. // set initial checked on mount to wait for true-value/false-value
  8995. mounted: setChecked,
  8996. beforeUpdate(el, binding, vnode) {
  8997. el._assign = getModelAssigner(vnode);
  8998. setChecked(el, binding, vnode);
  8999. }
  9000. };
  9001. function setChecked(el, { value, oldValue }, vnode) {
  9002. el._modelValue = value;
  9003. if (isArray(value)) {
  9004. el.checked = looseIndexOf(value, vnode.props.value) > -1;
  9005. }
  9006. else if (isSet(value)) {
  9007. el.checked = value.has(vnode.props.value);
  9008. }
  9009. else if (value !== oldValue) {
  9010. el.checked = looseEqual(value, getCheckboxValue(el, true));
  9011. }
  9012. }
  9013. const vModelRadio = {
  9014. created(el, { value }, vnode) {
  9015. el.checked = looseEqual(value, vnode.props.value);
  9016. el._assign = getModelAssigner(vnode);
  9017. addEventListener(el, 'change', () => {
  9018. el._assign(getValue(el));
  9019. });
  9020. },
  9021. beforeUpdate(el, { value, oldValue }, vnode) {
  9022. el._assign = getModelAssigner(vnode);
  9023. if (value !== oldValue) {
  9024. el.checked = looseEqual(value, vnode.props.value);
  9025. }
  9026. }
  9027. };
  9028. const vModelSelect = {
  9029. created(el, { value, modifiers: { number } }, vnode) {
  9030. const isSetModel = isSet(value);
  9031. addEventListener(el, 'change', () => {
  9032. const selectedVal = Array.prototype.filter
  9033. .call(el.options, (o) => o.selected)
  9034. .map((o) => number ? toNumber(getValue(o)) : getValue(o));
  9035. el._assign(el.multiple
  9036. ? isSetModel
  9037. ? new Set(selectedVal)
  9038. : selectedVal
  9039. : selectedVal[0]);
  9040. });
  9041. el._assign = getModelAssigner(vnode);
  9042. },
  9043. // set value in mounted & updated because <select> relies on its children
  9044. // <option>s.
  9045. mounted(el, { value }) {
  9046. setSelected(el, value);
  9047. },
  9048. beforeUpdate(el, _binding, vnode) {
  9049. el._assign = getModelAssigner(vnode);
  9050. },
  9051. updated(el, { value }) {
  9052. setSelected(el, value);
  9053. }
  9054. };
  9055. function setSelected(el, value) {
  9056. const isMultiple = el.multiple;
  9057. if (isMultiple && !isArray(value) && !isSet(value)) {
  9058. warn(`<select multiple v-model> expects an Array or Set value for its binding, ` +
  9059. `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
  9060. return;
  9061. }
  9062. for (let i = 0, l = el.options.length; i < l; i++) {
  9063. const option = el.options[i];
  9064. const optionValue = getValue(option);
  9065. if (isMultiple) {
  9066. if (isArray(value)) {
  9067. option.selected = looseIndexOf(value, optionValue) > -1;
  9068. }
  9069. else {
  9070. option.selected = value.has(optionValue);
  9071. }
  9072. }
  9073. else {
  9074. if (looseEqual(getValue(option), value)) {
  9075. el.selectedIndex = i;
  9076. return;
  9077. }
  9078. }
  9079. }
  9080. if (!isMultiple) {
  9081. el.selectedIndex = -1;
  9082. }
  9083. }
  9084. // retrieve raw value set via :value bindings
  9085. function getValue(el) {
  9086. return '_value' in el ? el._value : el.value;
  9087. }
  9088. // retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
  9089. function getCheckboxValue(el, checked) {
  9090. const key = checked ? '_trueValue' : '_falseValue';
  9091. return key in el ? el[key] : checked;
  9092. }
  9093. const vModelDynamic = {
  9094. created(el, binding, vnode) {
  9095. callModelHook(el, binding, vnode, null, 'created');
  9096. },
  9097. mounted(el, binding, vnode) {
  9098. callModelHook(el, binding, vnode, null, 'mounted');
  9099. },
  9100. beforeUpdate(el, binding, vnode, prevVNode) {
  9101. callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
  9102. },
  9103. updated(el, binding, vnode, prevVNode) {
  9104. callModelHook(el, binding, vnode, prevVNode, 'updated');
  9105. }
  9106. };
  9107. function callModelHook(el, binding, vnode, prevVNode, hook) {
  9108. let modelToUse;
  9109. switch (el.tagName) {
  9110. case 'SELECT':
  9111. modelToUse = vModelSelect;
  9112. break;
  9113. case 'TEXTAREA':
  9114. modelToUse = vModelText;
  9115. break;
  9116. default:
  9117. switch (vnode.props && vnode.props.type) {
  9118. case 'checkbox':
  9119. modelToUse = vModelCheckbox;
  9120. break;
  9121. case 'radio':
  9122. modelToUse = vModelRadio;
  9123. break;
  9124. default:
  9125. modelToUse = vModelText;
  9126. }
  9127. }
  9128. const fn = modelToUse[hook];
  9129. fn && fn(el, binding, vnode, prevVNode);
  9130. }
  9131. const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
  9132. const modifierGuards = {
  9133. stop: e => e.stopPropagation(),
  9134. prevent: e => e.preventDefault(),
  9135. self: e => e.target !== e.currentTarget,
  9136. ctrl: e => !e.ctrlKey,
  9137. shift: e => !e.shiftKey,
  9138. alt: e => !e.altKey,
  9139. meta: e => !e.metaKey,
  9140. left: e => 'button' in e && e.button !== 0,
  9141. middle: e => 'button' in e && e.button !== 1,
  9142. right: e => 'button' in e && e.button !== 2,
  9143. exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
  9144. };
  9145. /**
  9146. * @private
  9147. */
  9148. const withModifiers = (fn, modifiers) => {
  9149. return (event, ...args) => {
  9150. for (let i = 0; i < modifiers.length; i++) {
  9151. const guard = modifierGuards[modifiers[i]];
  9152. if (guard && guard(event, modifiers))
  9153. return;
  9154. }
  9155. return fn(event, ...args);
  9156. };
  9157. };
  9158. // Kept for 2.x compat.
  9159. // Note: IE11 compat for `spacebar` and `del` is removed for now.
  9160. const keyNames = {
  9161. esc: 'escape',
  9162. space: ' ',
  9163. up: 'arrow-up',
  9164. left: 'arrow-left',
  9165. right: 'arrow-right',
  9166. down: 'arrow-down',
  9167. delete: 'backspace'
  9168. };
  9169. /**
  9170. * @private
  9171. */
  9172. const withKeys = (fn, modifiers) => {
  9173. return (event) => {
  9174. if (!('key' in event))
  9175. return;
  9176. const eventKey = hyphenate(event.key);
  9177. if (
  9178. // None of the provided key modifiers match the current event key
  9179. !modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
  9180. return;
  9181. }
  9182. return fn(event);
  9183. };
  9184. };
  9185. const vShow = {
  9186. beforeMount(el, { value }, { transition }) {
  9187. el._vod = el.style.display === 'none' ? '' : el.style.display;
  9188. if (transition && value) {
  9189. transition.beforeEnter(el);
  9190. }
  9191. else {
  9192. setDisplay(el, value);
  9193. }
  9194. },
  9195. mounted(el, { value }, { transition }) {
  9196. if (transition && value) {
  9197. transition.enter(el);
  9198. }
  9199. },
  9200. updated(el, { value, oldValue }, { transition }) {
  9201. if (transition && value !== oldValue) {
  9202. if (value) {
  9203. transition.beforeEnter(el);
  9204. setDisplay(el, true);
  9205. transition.enter(el);
  9206. }
  9207. else {
  9208. transition.leave(el, () => {
  9209. setDisplay(el, false);
  9210. });
  9211. }
  9212. }
  9213. else {
  9214. setDisplay(el, value);
  9215. }
  9216. },
  9217. beforeUnmount(el, { value }) {
  9218. setDisplay(el, value);
  9219. }
  9220. };
  9221. function setDisplay(el, value) {
  9222. el.style.display = value ? el._vod : 'none';
  9223. }
  9224. const rendererOptions = extend({ patchProp, forcePatchProp }, nodeOps);
  9225. // lazy create the renderer - this makes core renderer logic tree-shakable
  9226. // in case the user only imports reactivity utilities from Vue.
  9227. let renderer;
  9228. let enabledHydration = false;
  9229. function ensureRenderer() {
  9230. return renderer || (renderer = createRenderer(rendererOptions));
  9231. }
  9232. function ensureHydrationRenderer() {
  9233. renderer = enabledHydration
  9234. ? renderer
  9235. : createHydrationRenderer(rendererOptions);
  9236. enabledHydration = true;
  9237. return renderer;
  9238. }
  9239. // use explicit type casts here to avoid import() calls in rolled-up d.ts
  9240. const render = ((...args) => {
  9241. ensureRenderer().render(...args);
  9242. });
  9243. const hydrate = ((...args) => {
  9244. ensureHydrationRenderer().hydrate(...args);
  9245. });
  9246. const createApp = ((...args) => {
  9247. const app = ensureRenderer().createApp(...args);
  9248. {
  9249. injectNativeTagCheck(app);
  9250. }
  9251. const { mount } = app;
  9252. app.mount = (containerOrSelector) => {
  9253. const container = normalizeContainer(containerOrSelector);
  9254. if (!container)
  9255. return;
  9256. const component = app._component;
  9257. if (!isFunction(component) && !component.render && !component.template) {
  9258. component.template = container.innerHTML;
  9259. }
  9260. // clear content before mounting
  9261. container.innerHTML = '';
  9262. const proxy = mount(container);
  9263. if (container instanceof Element) {
  9264. container.removeAttribute('v-cloak');
  9265. container.setAttribute('data-v-app', '');
  9266. }
  9267. return proxy;
  9268. };
  9269. return app;
  9270. });
  9271. const createSSRApp = ((...args) => {
  9272. const app = ensureHydrationRenderer().createApp(...args);
  9273. {
  9274. injectNativeTagCheck(app);
  9275. }
  9276. const { mount } = app;
  9277. app.mount = (containerOrSelector) => {
  9278. const container = normalizeContainer(containerOrSelector);
  9279. if (container) {
  9280. return mount(container, true);
  9281. }
  9282. };
  9283. return app;
  9284. });
  9285. function injectNativeTagCheck(app) {
  9286. // Inject `isNativeTag`
  9287. // this is used for component name validation (dev only)
  9288. Object.defineProperty(app.config, 'isNativeTag', {
  9289. value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
  9290. writable: false
  9291. });
  9292. }
  9293. function normalizeContainer(container) {
  9294. if (isString(container)) {
  9295. const res = document.querySelector(container);
  9296. if (!res) {
  9297. warn(`Failed to mount app: mount target selector "${container}" returned null.`);
  9298. }
  9299. return res;
  9300. }
  9301. if (container instanceof window.ShadowRoot &&
  9302. container.mode === 'closed') {
  9303. warn(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
  9304. }
  9305. return container;
  9306. }
  9307. function initDev() {
  9308. const target = getGlobalThis();
  9309. target.__VUE__ = true;
  9310. setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__);
  9311. {
  9312. {
  9313. console.info(`You are running a development build of Vue.\n` +
  9314. `Make sure to use the production build (*.prod.js) when deploying for production.`);
  9315. }
  9316. initCustomFormatter();
  9317. }
  9318. }
  9319. function defaultOnError(error) {
  9320. throw error;
  9321. }
  9322. function createCompilerError(code, loc, messages, additionalMessage) {
  9323. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  9324. ;
  9325. const error = new SyntaxError(String(msg));
  9326. error.code = code;
  9327. error.loc = loc;
  9328. return error;
  9329. }
  9330. const errorMessages = {
  9331. // parse errors
  9332. [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  9333. [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  9334. [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  9335. [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  9336. [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  9337. [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  9338. [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  9339. [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  9340. [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  9341. [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  9342. [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  9343. [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  9344. [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  9345. [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  9346. [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  9347. [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  9348. [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  9349. [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  9350. [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  9351. [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  9352. [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  9353. [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  9354. // Vue-specific parse errors
  9355. [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
  9356. [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
  9357. [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  9358. [26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  9359. 'Note that dynamic directive argument cannot contain spaces.',
  9360. // transform errors
  9361. [27 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  9362. [28 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  9363. [29 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
  9364. [30 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  9365. [31 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  9366. [32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  9367. [33 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  9368. [34 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  9369. [35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  9370. [36 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
  9371. `When there are multiple named slots, all slots should use <template> ` +
  9372. `syntax to avoid scope ambiguity.`,
  9373. [37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  9374. [38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  9375. `default slot. These children will be ignored.`,
  9376. [39 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  9377. [40 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  9378. [41 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  9379. [42 /* X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  9380. [43 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  9381. [44 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  9382. // generic errors
  9383. [45 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  9384. [46 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  9385. [47 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  9386. [48 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`
  9387. };
  9388. const FRAGMENT = Symbol(`Fragment` );
  9389. const TELEPORT = Symbol(`Teleport` );
  9390. const SUSPENSE = Symbol(`Suspense` );
  9391. const KEEP_ALIVE = Symbol(`KeepAlive` );
  9392. const BASE_TRANSITION = Symbol(`BaseTransition` );
  9393. const OPEN_BLOCK = Symbol(`openBlock` );
  9394. const CREATE_BLOCK = Symbol(`createBlock` );
  9395. const CREATE_VNODE = Symbol(`createVNode` );
  9396. const CREATE_COMMENT = Symbol(`createCommentVNode` );
  9397. const CREATE_TEXT = Symbol(`createTextVNode` );
  9398. const CREATE_STATIC = Symbol(`createStaticVNode` );
  9399. const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
  9400. const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
  9401. const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
  9402. const WITH_DIRECTIVES = Symbol(`withDirectives` );
  9403. const RENDER_LIST = Symbol(`renderList` );
  9404. const RENDER_SLOT = Symbol(`renderSlot` );
  9405. const CREATE_SLOTS = Symbol(`createSlots` );
  9406. const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
  9407. const MERGE_PROPS = Symbol(`mergeProps` );
  9408. const TO_HANDLERS = Symbol(`toHandlers` );
  9409. const CAMELIZE = Symbol(`camelize` );
  9410. const CAPITALIZE = Symbol(`capitalize` );
  9411. const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
  9412. const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
  9413. const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
  9414. const POP_SCOPE_ID = Symbol(`popScopeId` );
  9415. const WITH_SCOPE_ID = Symbol(`withScopeId` );
  9416. const WITH_CTX = Symbol(`withCtx` );
  9417. const UNREF = Symbol(`unref` );
  9418. const IS_REF = Symbol(`isRef` );
  9419. // Name mapping for runtime helpers that need to be imported from 'vue' in
  9420. // generated code. Make sure these are correctly exported in the runtime!
  9421. // Using `any` here because TS doesn't allow symbols as index type.
  9422. const helperNameMap = {
  9423. [FRAGMENT]: `Fragment`,
  9424. [TELEPORT]: `Teleport`,
  9425. [SUSPENSE]: `Suspense`,
  9426. [KEEP_ALIVE]: `KeepAlive`,
  9427. [BASE_TRANSITION]: `BaseTransition`,
  9428. [OPEN_BLOCK]: `openBlock`,
  9429. [CREATE_BLOCK]: `createBlock`,
  9430. [CREATE_VNODE]: `createVNode`,
  9431. [CREATE_COMMENT]: `createCommentVNode`,
  9432. [CREATE_TEXT]: `createTextVNode`,
  9433. [CREATE_STATIC]: `createStaticVNode`,
  9434. [RESOLVE_COMPONENT]: `resolveComponent`,
  9435. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  9436. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  9437. [WITH_DIRECTIVES]: `withDirectives`,
  9438. [RENDER_LIST]: `renderList`,
  9439. [RENDER_SLOT]: `renderSlot`,
  9440. [CREATE_SLOTS]: `createSlots`,
  9441. [TO_DISPLAY_STRING]: `toDisplayString`,
  9442. [MERGE_PROPS]: `mergeProps`,
  9443. [TO_HANDLERS]: `toHandlers`,
  9444. [CAMELIZE]: `camelize`,
  9445. [CAPITALIZE]: `capitalize`,
  9446. [TO_HANDLER_KEY]: `toHandlerKey`,
  9447. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  9448. [PUSH_SCOPE_ID]: `pushScopeId`,
  9449. [POP_SCOPE_ID]: `popScopeId`,
  9450. [WITH_SCOPE_ID]: `withScopeId`,
  9451. [WITH_CTX]: `withCtx`,
  9452. [UNREF]: `unref`,
  9453. [IS_REF]: `isRef`
  9454. };
  9455. function registerRuntimeHelpers(helpers) {
  9456. Object.getOwnPropertySymbols(helpers).forEach(s => {
  9457. helperNameMap[s] = helpers[s];
  9458. });
  9459. }
  9460. // AST Utilities ---------------------------------------------------------------
  9461. // Some expressions, e.g. sequence and conditional expressions, are never
  9462. // associated with template nodes, so their source locations are just a stub.
  9463. // Container types like CompoundExpression also don't need a real location.
  9464. const locStub = {
  9465. source: '',
  9466. start: { line: 1, column: 1, offset: 0 },
  9467. end: { line: 1, column: 1, offset: 0 }
  9468. };
  9469. function createRoot(children, loc = locStub) {
  9470. return {
  9471. type: 0 /* ROOT */,
  9472. children,
  9473. helpers: [],
  9474. components: [],
  9475. directives: [],
  9476. hoists: [],
  9477. imports: [],
  9478. cached: 0,
  9479. temps: 0,
  9480. codegenNode: undefined,
  9481. loc
  9482. };
  9483. }
  9484. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, loc = locStub) {
  9485. if (context) {
  9486. if (isBlock) {
  9487. context.helper(OPEN_BLOCK);
  9488. context.helper(CREATE_BLOCK);
  9489. }
  9490. else {
  9491. context.helper(CREATE_VNODE);
  9492. }
  9493. if (directives) {
  9494. context.helper(WITH_DIRECTIVES);
  9495. }
  9496. }
  9497. return {
  9498. type: 13 /* VNODE_CALL */,
  9499. tag,
  9500. props,
  9501. children,
  9502. patchFlag,
  9503. dynamicProps,
  9504. directives,
  9505. isBlock,
  9506. disableTracking,
  9507. loc
  9508. };
  9509. }
  9510. function createArrayExpression(elements, loc = locStub) {
  9511. return {
  9512. type: 17 /* JS_ARRAY_EXPRESSION */,
  9513. loc,
  9514. elements
  9515. };
  9516. }
  9517. function createObjectExpression(properties, loc = locStub) {
  9518. return {
  9519. type: 15 /* JS_OBJECT_EXPRESSION */,
  9520. loc,
  9521. properties
  9522. };
  9523. }
  9524. function createObjectProperty(key, value) {
  9525. return {
  9526. type: 16 /* JS_PROPERTY */,
  9527. loc: locStub,
  9528. key: isString(key) ? createSimpleExpression(key, true) : key,
  9529. value
  9530. };
  9531. }
  9532. function createSimpleExpression(content, isStatic, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
  9533. return {
  9534. type: 4 /* SIMPLE_EXPRESSION */,
  9535. loc,
  9536. content,
  9537. isStatic,
  9538. constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
  9539. };
  9540. }
  9541. function createCompoundExpression(children, loc = locStub) {
  9542. return {
  9543. type: 8 /* COMPOUND_EXPRESSION */,
  9544. loc,
  9545. children
  9546. };
  9547. }
  9548. function createCallExpression(callee, args = [], loc = locStub) {
  9549. return {
  9550. type: 14 /* JS_CALL_EXPRESSION */,
  9551. loc,
  9552. callee,
  9553. arguments: args
  9554. };
  9555. }
  9556. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  9557. return {
  9558. type: 18 /* JS_FUNCTION_EXPRESSION */,
  9559. params,
  9560. returns,
  9561. newline,
  9562. isSlot,
  9563. loc
  9564. };
  9565. }
  9566. function createConditionalExpression(test, consequent, alternate, newline = true) {
  9567. return {
  9568. type: 19 /* JS_CONDITIONAL_EXPRESSION */,
  9569. test,
  9570. consequent,
  9571. alternate,
  9572. newline,
  9573. loc: locStub
  9574. };
  9575. }
  9576. function createCacheExpression(index, value, isVNode = false) {
  9577. return {
  9578. type: 20 /* JS_CACHE_EXPRESSION */,
  9579. index,
  9580. value,
  9581. isVNode,
  9582. loc: locStub
  9583. };
  9584. }
  9585. const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
  9586. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  9587. function isCoreComponent(tag) {
  9588. if (isBuiltInType(tag, 'Teleport')) {
  9589. return TELEPORT;
  9590. }
  9591. else if (isBuiltInType(tag, 'Suspense')) {
  9592. return SUSPENSE;
  9593. }
  9594. else if (isBuiltInType(tag, 'KeepAlive')) {
  9595. return KEEP_ALIVE;
  9596. }
  9597. else if (isBuiltInType(tag, 'BaseTransition')) {
  9598. return BASE_TRANSITION;
  9599. }
  9600. }
  9601. const nonIdentifierRE = /^\d|[^\$\w]/;
  9602. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  9603. const memberExpRE = /^[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*|\[[^\]]+\])*$/;
  9604. const isMemberExpression = (path) => {
  9605. if (!path)
  9606. return false;
  9607. return memberExpRE.test(path.trim());
  9608. };
  9609. function getInnerRange(loc, offset, length) {
  9610. const source = loc.source.substr(offset, length);
  9611. const newLoc = {
  9612. source,
  9613. start: advancePositionWithClone(loc.start, loc.source, offset),
  9614. end: loc.end
  9615. };
  9616. if (length != null) {
  9617. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  9618. }
  9619. return newLoc;
  9620. }
  9621. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  9622. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  9623. }
  9624. // advance by mutation without cloning (for performance reasons), since this
  9625. // gets called a lot in the parser
  9626. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  9627. let linesCount = 0;
  9628. let lastNewLinePos = -1;
  9629. for (let i = 0; i < numberOfCharacters; i++) {
  9630. if (source.charCodeAt(i) === 10 /* newline char code */) {
  9631. linesCount++;
  9632. lastNewLinePos = i;
  9633. }
  9634. }
  9635. pos.offset += numberOfCharacters;
  9636. pos.line += linesCount;
  9637. pos.column =
  9638. lastNewLinePos === -1
  9639. ? pos.column + numberOfCharacters
  9640. : numberOfCharacters - lastNewLinePos;
  9641. return pos;
  9642. }
  9643. function assert(condition, msg) {
  9644. /* istanbul ignore if */
  9645. if (!condition) {
  9646. throw new Error(msg || `unexpected compiler condition`);
  9647. }
  9648. }
  9649. function findDir(node, name, allowEmpty = false) {
  9650. for (let i = 0; i < node.props.length; i++) {
  9651. const p = node.props[i];
  9652. if (p.type === 7 /* DIRECTIVE */ &&
  9653. (allowEmpty || p.exp) &&
  9654. (isString(name) ? p.name === name : name.test(p.name))) {
  9655. return p;
  9656. }
  9657. }
  9658. }
  9659. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  9660. for (let i = 0; i < node.props.length; i++) {
  9661. const p = node.props[i];
  9662. if (p.type === 6 /* ATTRIBUTE */) {
  9663. if (dynamicOnly)
  9664. continue;
  9665. if (p.name === name && (p.value || allowEmpty)) {
  9666. return p;
  9667. }
  9668. }
  9669. else if (p.name === 'bind' &&
  9670. (p.exp || allowEmpty) &&
  9671. isBindKey(p.arg, name)) {
  9672. return p;
  9673. }
  9674. }
  9675. }
  9676. function isBindKey(arg, name) {
  9677. return !!(arg && isStaticExp(arg) && arg.content === name);
  9678. }
  9679. function hasDynamicKeyVBind(node) {
  9680. return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
  9681. p.name === 'bind' &&
  9682. (!p.arg || // v-bind="obj"
  9683. p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  9684. !p.arg.isStatic) // v-bind:[foo]
  9685. );
  9686. }
  9687. function isText(node) {
  9688. return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
  9689. }
  9690. function isVSlot(p) {
  9691. return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
  9692. }
  9693. function isTemplateNode(node) {
  9694. return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
  9695. }
  9696. function isSlotOutlet(node) {
  9697. return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
  9698. }
  9699. function injectProp(node, prop, context) {
  9700. let propsWithInjection;
  9701. const props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
  9702. if (props == null || isString(props)) {
  9703. propsWithInjection = createObjectExpression([prop]);
  9704. }
  9705. else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
  9706. // merged props... add ours
  9707. // only inject key to object literal if it's the first argument so that
  9708. // if doesn't override user provided keys
  9709. const first = props.arguments[0];
  9710. if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
  9711. first.properties.unshift(prop);
  9712. }
  9713. else {
  9714. if (props.callee === TO_HANDLERS) {
  9715. // #2366
  9716. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  9717. createObjectExpression([prop]),
  9718. props
  9719. ]);
  9720. }
  9721. else {
  9722. props.arguments.unshift(createObjectExpression([prop]));
  9723. }
  9724. }
  9725. !propsWithInjection && (propsWithInjection = props);
  9726. }
  9727. else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  9728. let alreadyExists = false;
  9729. // check existing key to avoid overriding user provided keys
  9730. if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
  9731. const propKeyName = prop.key.content;
  9732. alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  9733. p.key.content === propKeyName);
  9734. }
  9735. if (!alreadyExists) {
  9736. props.properties.unshift(prop);
  9737. }
  9738. propsWithInjection = props;
  9739. }
  9740. else {
  9741. // single v-bind with expression, return a merged replacement
  9742. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  9743. createObjectExpression([prop]),
  9744. props
  9745. ]);
  9746. }
  9747. if (node.type === 13 /* VNODE_CALL */) {
  9748. node.props = propsWithInjection;
  9749. }
  9750. else {
  9751. node.arguments[2] = propsWithInjection;
  9752. }
  9753. }
  9754. function toValidAssetId(name, type) {
  9755. return `_${type}_${name.replace(/[^\w]/g, '_')}`;
  9756. }
  9757. // The default decoder only provides escapes for characters reserved as part of
  9758. // the template syntax, and is only used if the custom renderer did not provide
  9759. // a platform-specific decoder.
  9760. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  9761. const decodeMap = {
  9762. gt: '>',
  9763. lt: '<',
  9764. amp: '&',
  9765. apos: "'",
  9766. quot: '"'
  9767. };
  9768. const defaultParserOptions = {
  9769. delimiters: [`{{`, `}}`],
  9770. getNamespace: () => 0 /* HTML */,
  9771. getTextMode: () => 0 /* DATA */,
  9772. isVoidTag: NO,
  9773. isPreTag: NO,
  9774. isCustomElement: NO,
  9775. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  9776. onError: defaultOnError,
  9777. comments: false
  9778. };
  9779. function baseParse(content, options = {}) {
  9780. const context = createParserContext(content, options);
  9781. const start = getCursor(context);
  9782. return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
  9783. }
  9784. function createParserContext(content, rawOptions) {
  9785. const options = extend({}, defaultParserOptions);
  9786. for (const key in rawOptions) {
  9787. // @ts-ignore
  9788. options[key] = rawOptions[key] || defaultParserOptions[key];
  9789. }
  9790. return {
  9791. options,
  9792. column: 1,
  9793. line: 1,
  9794. offset: 0,
  9795. originalSource: content,
  9796. source: content,
  9797. inPre: false,
  9798. inVPre: false
  9799. };
  9800. }
  9801. function parseChildren(context, mode, ancestors) {
  9802. const parent = last(ancestors);
  9803. const ns = parent ? parent.ns : 0 /* HTML */;
  9804. const nodes = [];
  9805. while (!isEnd(context, mode, ancestors)) {
  9806. const s = context.source;
  9807. let node = undefined;
  9808. if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
  9809. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  9810. // '{{'
  9811. node = parseInterpolation(context, mode);
  9812. }
  9813. else if (mode === 0 /* DATA */ && s[0] === '<') {
  9814. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  9815. if (s.length === 1) {
  9816. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
  9817. }
  9818. else if (s[1] === '!') {
  9819. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  9820. if (startsWith(s, '<!--')) {
  9821. node = parseComment(context);
  9822. }
  9823. else if (startsWith(s, '<!DOCTYPE')) {
  9824. // Ignore DOCTYPE by a limitation.
  9825. node = parseBogusComment(context);
  9826. }
  9827. else if (startsWith(s, '<![CDATA[')) {
  9828. if (ns !== 0 /* HTML */) {
  9829. node = parseCDATA(context, ancestors);
  9830. }
  9831. else {
  9832. emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
  9833. node = parseBogusComment(context);
  9834. }
  9835. }
  9836. else {
  9837. emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
  9838. node = parseBogusComment(context);
  9839. }
  9840. }
  9841. else if (s[1] === '/') {
  9842. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  9843. if (s.length === 2) {
  9844. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
  9845. }
  9846. else if (s[2] === '>') {
  9847. emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
  9848. advanceBy(context, 3);
  9849. continue;
  9850. }
  9851. else if (/[a-z]/i.test(s[2])) {
  9852. emitError(context, 23 /* X_INVALID_END_TAG */);
  9853. parseTag(context, 1 /* End */, parent);
  9854. continue;
  9855. }
  9856. else {
  9857. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  9858. node = parseBogusComment(context);
  9859. }
  9860. }
  9861. else if (/[a-z]/i.test(s[1])) {
  9862. node = parseElement(context, ancestors);
  9863. }
  9864. else if (s[1] === '?') {
  9865. emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  9866. node = parseBogusComment(context);
  9867. }
  9868. else {
  9869. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  9870. }
  9871. }
  9872. }
  9873. if (!node) {
  9874. node = parseText(context, mode);
  9875. }
  9876. if (isArray(node)) {
  9877. for (let i = 0; i < node.length; i++) {
  9878. pushNode(nodes, node[i]);
  9879. }
  9880. }
  9881. else {
  9882. pushNode(nodes, node);
  9883. }
  9884. }
  9885. // Whitespace management for more efficient output
  9886. // (same as v2 whitespace: 'condense')
  9887. let removedWhitespace = false;
  9888. if (mode !== 2 /* RAWTEXT */) {
  9889. for (let i = 0; i < nodes.length; i++) {
  9890. const node = nodes[i];
  9891. if (!context.inPre && node.type === 2 /* TEXT */) {
  9892. if (!/[^\t\r\n\f ]/.test(node.content)) {
  9893. const prev = nodes[i - 1];
  9894. const next = nodes[i + 1];
  9895. // If:
  9896. // - the whitespace is the first or last node, or:
  9897. // - the whitespace is adjacent to a comment, or:
  9898. // - the whitespace is between two elements AND contains newline
  9899. // Then the whitespace is ignored.
  9900. if (!prev ||
  9901. !next ||
  9902. prev.type === 3 /* COMMENT */ ||
  9903. next.type === 3 /* COMMENT */ ||
  9904. (prev.type === 1 /* ELEMENT */ &&
  9905. next.type === 1 /* ELEMENT */ &&
  9906. /[\r\n]/.test(node.content))) {
  9907. removedWhitespace = true;
  9908. nodes[i] = null;
  9909. }
  9910. else {
  9911. // Otherwise, condensed consecutive whitespace inside the text
  9912. // down to a single space
  9913. node.content = ' ';
  9914. }
  9915. }
  9916. else {
  9917. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  9918. }
  9919. }
  9920. }
  9921. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  9922. // remove leading newline per html spec
  9923. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  9924. const first = nodes[0];
  9925. if (first && first.type === 2 /* TEXT */) {
  9926. first.content = first.content.replace(/^\r?\n/, '');
  9927. }
  9928. }
  9929. }
  9930. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  9931. }
  9932. function pushNode(nodes, node) {
  9933. if (node.type === 2 /* TEXT */) {
  9934. const prev = last(nodes);
  9935. // Merge if both this and the previous node are text and those are
  9936. // consecutive. This happens for cases like "a < b".
  9937. if (prev &&
  9938. prev.type === 2 /* TEXT */ &&
  9939. prev.loc.end.offset === node.loc.start.offset) {
  9940. prev.content += node.content;
  9941. prev.loc.end = node.loc.end;
  9942. prev.loc.source += node.loc.source;
  9943. return;
  9944. }
  9945. }
  9946. nodes.push(node);
  9947. }
  9948. function parseCDATA(context, ancestors) {
  9949. advanceBy(context, 9);
  9950. const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
  9951. if (context.source.length === 0) {
  9952. emitError(context, 6 /* EOF_IN_CDATA */);
  9953. }
  9954. else {
  9955. advanceBy(context, 3);
  9956. }
  9957. return nodes;
  9958. }
  9959. function parseComment(context) {
  9960. const start = getCursor(context);
  9961. let content;
  9962. // Regular comment.
  9963. const match = /--(\!)?>/.exec(context.source);
  9964. if (!match) {
  9965. content = context.source.slice(4);
  9966. advanceBy(context, context.source.length);
  9967. emitError(context, 7 /* EOF_IN_COMMENT */);
  9968. }
  9969. else {
  9970. if (match.index <= 3) {
  9971. emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  9972. }
  9973. if (match[1]) {
  9974. emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
  9975. }
  9976. content = context.source.slice(4, match.index);
  9977. // Advancing with reporting nested comments.
  9978. const s = context.source.slice(0, match.index);
  9979. let prevIndex = 1, nestedIndex = 0;
  9980. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  9981. advanceBy(context, nestedIndex - prevIndex + 1);
  9982. if (nestedIndex + 4 < s.length) {
  9983. emitError(context, 16 /* NESTED_COMMENT */);
  9984. }
  9985. prevIndex = nestedIndex + 1;
  9986. }
  9987. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  9988. }
  9989. return {
  9990. type: 3 /* COMMENT */,
  9991. content,
  9992. loc: getSelection(context, start)
  9993. };
  9994. }
  9995. function parseBogusComment(context) {
  9996. const start = getCursor(context);
  9997. const contentStart = context.source[1] === '?' ? 1 : 2;
  9998. let content;
  9999. const closeIndex = context.source.indexOf('>');
  10000. if (closeIndex === -1) {
  10001. content = context.source.slice(contentStart);
  10002. advanceBy(context, context.source.length);
  10003. }
  10004. else {
  10005. content = context.source.slice(contentStart, closeIndex);
  10006. advanceBy(context, closeIndex + 1);
  10007. }
  10008. return {
  10009. type: 3 /* COMMENT */,
  10010. content,
  10011. loc: getSelection(context, start)
  10012. };
  10013. }
  10014. function parseElement(context, ancestors) {
  10015. // Start tag.
  10016. const wasInPre = context.inPre;
  10017. const wasInVPre = context.inVPre;
  10018. const parent = last(ancestors);
  10019. const element = parseTag(context, 0 /* Start */, parent);
  10020. const isPreBoundary = context.inPre && !wasInPre;
  10021. const isVPreBoundary = context.inVPre && !wasInVPre;
  10022. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  10023. return element;
  10024. }
  10025. // Children.
  10026. ancestors.push(element);
  10027. const mode = context.options.getTextMode(element, parent);
  10028. const children = parseChildren(context, mode, ancestors);
  10029. ancestors.pop();
  10030. element.children = children;
  10031. // End tag.
  10032. if (startsWithEndTagOpen(context.source, element.tag)) {
  10033. parseTag(context, 1 /* End */, parent);
  10034. }
  10035. else {
  10036. emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
  10037. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  10038. const first = children[0];
  10039. if (first && startsWith(first.loc.source, '<!--')) {
  10040. emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  10041. }
  10042. }
  10043. }
  10044. element.loc = getSelection(context, element.loc.start);
  10045. if (isPreBoundary) {
  10046. context.inPre = false;
  10047. }
  10048. if (isVPreBoundary) {
  10049. context.inVPre = false;
  10050. }
  10051. return element;
  10052. }
  10053. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  10054. /**
  10055. * Parse a tag (E.g. `<div id=a>`) with that type (start tag or end tag).
  10056. */
  10057. function parseTag(context, type, parent) {
  10058. // Tag open.
  10059. const start = getCursor(context);
  10060. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  10061. const tag = match[1];
  10062. const ns = context.options.getNamespace(tag, parent);
  10063. advanceBy(context, match[0].length);
  10064. advanceSpaces(context);
  10065. // save current state in case we need to re-parse attributes with v-pre
  10066. const cursor = getCursor(context);
  10067. const currentSource = context.source;
  10068. // Attributes.
  10069. let props = parseAttributes(context, type);
  10070. // check <pre> tag
  10071. if (context.options.isPreTag(tag)) {
  10072. context.inPre = true;
  10073. }
  10074. // check v-pre
  10075. if (!context.inVPre &&
  10076. props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
  10077. context.inVPre = true;
  10078. // reset context
  10079. extend(context, cursor);
  10080. context.source = currentSource;
  10081. // re-parse attrs and filter out v-pre itself
  10082. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  10083. }
  10084. // Tag close.
  10085. let isSelfClosing = false;
  10086. if (context.source.length === 0) {
  10087. emitError(context, 9 /* EOF_IN_TAG */);
  10088. }
  10089. else {
  10090. isSelfClosing = startsWith(context.source, '/>');
  10091. if (type === 1 /* End */ && isSelfClosing) {
  10092. emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
  10093. }
  10094. advanceBy(context, isSelfClosing ? 2 : 1);
  10095. }
  10096. let tagType = 0 /* ELEMENT */;
  10097. const options = context.options;
  10098. if (!context.inVPre && !options.isCustomElement(tag)) {
  10099. const hasVIs = props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'is');
  10100. if (options.isNativeTag && !hasVIs) {
  10101. if (!options.isNativeTag(tag))
  10102. tagType = 1 /* COMPONENT */;
  10103. }
  10104. else if (hasVIs ||
  10105. isCoreComponent(tag) ||
  10106. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  10107. /^[A-Z]/.test(tag) ||
  10108. tag === 'component') {
  10109. tagType = 1 /* COMPONENT */;
  10110. }
  10111. if (tag === 'slot') {
  10112. tagType = 2 /* SLOT */;
  10113. }
  10114. else if (tag === 'template' &&
  10115. props.some(p => {
  10116. return (p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name));
  10117. })) {
  10118. tagType = 3 /* TEMPLATE */;
  10119. }
  10120. }
  10121. return {
  10122. type: 1 /* ELEMENT */,
  10123. ns,
  10124. tag,
  10125. tagType,
  10126. props,
  10127. isSelfClosing,
  10128. children: [],
  10129. loc: getSelection(context, start),
  10130. codegenNode: undefined // to be created during transform phase
  10131. };
  10132. }
  10133. function parseAttributes(context, type) {
  10134. const props = [];
  10135. const attributeNames = new Set();
  10136. while (context.source.length > 0 &&
  10137. !startsWith(context.source, '>') &&
  10138. !startsWith(context.source, '/>')) {
  10139. if (startsWith(context.source, '/')) {
  10140. emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
  10141. advanceBy(context, 1);
  10142. advanceSpaces(context);
  10143. continue;
  10144. }
  10145. if (type === 1 /* End */) {
  10146. emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
  10147. }
  10148. const attr = parseAttribute(context, attributeNames);
  10149. if (type === 0 /* Start */) {
  10150. props.push(attr);
  10151. }
  10152. if (/^[^\t\r\n\f />]/.test(context.source)) {
  10153. emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  10154. }
  10155. advanceSpaces(context);
  10156. }
  10157. return props;
  10158. }
  10159. function parseAttribute(context, nameSet) {
  10160. // Name.
  10161. const start = getCursor(context);
  10162. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  10163. const name = match[0];
  10164. if (nameSet.has(name)) {
  10165. emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
  10166. }
  10167. nameSet.add(name);
  10168. if (name[0] === '=') {
  10169. emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  10170. }
  10171. {
  10172. const pattern = /["'<]/g;
  10173. let m;
  10174. while ((m = pattern.exec(name))) {
  10175. emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  10176. }
  10177. }
  10178. advanceBy(context, name.length);
  10179. // Value
  10180. let value = undefined;
  10181. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  10182. advanceSpaces(context);
  10183. advanceBy(context, 1);
  10184. advanceSpaces(context);
  10185. value = parseAttributeValue(context);
  10186. if (!value) {
  10187. emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
  10188. }
  10189. }
  10190. const loc = getSelection(context, start);
  10191. if (!context.inVPre && /^(v-|:|@|#)/.test(name)) {
  10192. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  10193. const dirName = match[1] ||
  10194. (startsWith(name, ':') ? 'bind' : startsWith(name, '@') ? 'on' : 'slot');
  10195. let arg;
  10196. if (match[2]) {
  10197. const isSlot = dirName === 'slot';
  10198. const startOffset = name.indexOf(match[2]);
  10199. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  10200. let content = match[2];
  10201. let isStatic = true;
  10202. if (content.startsWith('[')) {
  10203. isStatic = false;
  10204. if (!content.endsWith(']')) {
  10205. emitError(context, 26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  10206. }
  10207. content = content.substr(1, content.length - 2);
  10208. }
  10209. else if (isSlot) {
  10210. // #1241 special case for v-slot: vuetify relies extensively on slot
  10211. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  10212. // supports such usage so we are keeping it consistent with 2.x.
  10213. content += match[3] || '';
  10214. }
  10215. arg = {
  10216. type: 4 /* SIMPLE_EXPRESSION */,
  10217. content,
  10218. isStatic,
  10219. constType: isStatic
  10220. ? 3 /* CAN_STRINGIFY */
  10221. : 0 /* NOT_CONSTANT */,
  10222. loc
  10223. };
  10224. }
  10225. if (value && value.isQuoted) {
  10226. const valueLoc = value.loc;
  10227. valueLoc.start.offset++;
  10228. valueLoc.start.column++;
  10229. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  10230. valueLoc.source = valueLoc.source.slice(1, -1);
  10231. }
  10232. return {
  10233. type: 7 /* DIRECTIVE */,
  10234. name: dirName,
  10235. exp: value && {
  10236. type: 4 /* SIMPLE_EXPRESSION */,
  10237. content: value.content,
  10238. isStatic: false,
  10239. // Treat as non-constant by default. This can be potentially set to
  10240. // other values by `transformExpression` to make it eligible for hoisting.
  10241. constType: 0 /* NOT_CONSTANT */,
  10242. loc: value.loc
  10243. },
  10244. arg,
  10245. modifiers: match[3] ? match[3].substr(1).split('.') : [],
  10246. loc
  10247. };
  10248. }
  10249. return {
  10250. type: 6 /* ATTRIBUTE */,
  10251. name,
  10252. value: value && {
  10253. type: 2 /* TEXT */,
  10254. content: value.content,
  10255. loc: value.loc
  10256. },
  10257. loc
  10258. };
  10259. }
  10260. function parseAttributeValue(context) {
  10261. const start = getCursor(context);
  10262. let content;
  10263. const quote = context.source[0];
  10264. const isQuoted = quote === `"` || quote === `'`;
  10265. if (isQuoted) {
  10266. // Quoted value.
  10267. advanceBy(context, 1);
  10268. const endIndex = context.source.indexOf(quote);
  10269. if (endIndex === -1) {
  10270. content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
  10271. }
  10272. else {
  10273. content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
  10274. advanceBy(context, 1);
  10275. }
  10276. }
  10277. else {
  10278. // Unquoted
  10279. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  10280. if (!match) {
  10281. return undefined;
  10282. }
  10283. const unexpectedChars = /["'<=`]/g;
  10284. let m;
  10285. while ((m = unexpectedChars.exec(match[0]))) {
  10286. emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  10287. }
  10288. content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
  10289. }
  10290. return { content, isQuoted, loc: getSelection(context, start) };
  10291. }
  10292. function parseInterpolation(context, mode) {
  10293. const [open, close] = context.options.delimiters;
  10294. const closeIndex = context.source.indexOf(close, open.length);
  10295. if (closeIndex === -1) {
  10296. emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
  10297. return undefined;
  10298. }
  10299. const start = getCursor(context);
  10300. advanceBy(context, open.length);
  10301. const innerStart = getCursor(context);
  10302. const innerEnd = getCursor(context);
  10303. const rawContentLength = closeIndex - open.length;
  10304. const rawContent = context.source.slice(0, rawContentLength);
  10305. const preTrimContent = parseTextData(context, rawContentLength, mode);
  10306. const content = preTrimContent.trim();
  10307. const startOffset = preTrimContent.indexOf(content);
  10308. if (startOffset > 0) {
  10309. advancePositionWithMutation(innerStart, rawContent, startOffset);
  10310. }
  10311. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  10312. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  10313. advanceBy(context, close.length);
  10314. return {
  10315. type: 5 /* INTERPOLATION */,
  10316. content: {
  10317. type: 4 /* SIMPLE_EXPRESSION */,
  10318. isStatic: false,
  10319. // Set `isConstant` to false by default and will decide in transformExpression
  10320. constType: 0 /* NOT_CONSTANT */,
  10321. content,
  10322. loc: getSelection(context, innerStart, innerEnd)
  10323. },
  10324. loc: getSelection(context, start)
  10325. };
  10326. }
  10327. function parseText(context, mode) {
  10328. const endTokens = ['<', context.options.delimiters[0]];
  10329. if (mode === 3 /* CDATA */) {
  10330. endTokens.push(']]>');
  10331. }
  10332. let endIndex = context.source.length;
  10333. for (let i = 0; i < endTokens.length; i++) {
  10334. const index = context.source.indexOf(endTokens[i], 1);
  10335. if (index !== -1 && endIndex > index) {
  10336. endIndex = index;
  10337. }
  10338. }
  10339. const start = getCursor(context);
  10340. const content = parseTextData(context, endIndex, mode);
  10341. return {
  10342. type: 2 /* TEXT */,
  10343. content,
  10344. loc: getSelection(context, start)
  10345. };
  10346. }
  10347. /**
  10348. * Get text data with a given length from the current location.
  10349. * This translates HTML entities in the text data.
  10350. */
  10351. function parseTextData(context, length, mode) {
  10352. const rawText = context.source.slice(0, length);
  10353. advanceBy(context, length);
  10354. if (mode === 2 /* RAWTEXT */ ||
  10355. mode === 3 /* CDATA */ ||
  10356. rawText.indexOf('&') === -1) {
  10357. return rawText;
  10358. }
  10359. else {
  10360. // DATA or RCDATA containing "&"". Entity decoding required.
  10361. return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
  10362. }
  10363. }
  10364. function getCursor(context) {
  10365. const { column, line, offset } = context;
  10366. return { column, line, offset };
  10367. }
  10368. function getSelection(context, start, end) {
  10369. end = end || getCursor(context);
  10370. return {
  10371. start,
  10372. end,
  10373. source: context.originalSource.slice(start.offset, end.offset)
  10374. };
  10375. }
  10376. function last(xs) {
  10377. return xs[xs.length - 1];
  10378. }
  10379. function startsWith(source, searchString) {
  10380. return source.startsWith(searchString);
  10381. }
  10382. function advanceBy(context, numberOfCharacters) {
  10383. const { source } = context;
  10384. advancePositionWithMutation(context, source, numberOfCharacters);
  10385. context.source = source.slice(numberOfCharacters);
  10386. }
  10387. function advanceSpaces(context) {
  10388. const match = /^[\t\r\n\f ]+/.exec(context.source);
  10389. if (match) {
  10390. advanceBy(context, match[0].length);
  10391. }
  10392. }
  10393. function getNewPosition(context, start, numberOfCharacters) {
  10394. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  10395. }
  10396. function emitError(context, code, offset, loc = getCursor(context)) {
  10397. if (offset) {
  10398. loc.offset += offset;
  10399. loc.column += offset;
  10400. }
  10401. context.options.onError(createCompilerError(code, {
  10402. start: loc,
  10403. end: loc,
  10404. source: ''
  10405. }));
  10406. }
  10407. function isEnd(context, mode, ancestors) {
  10408. const s = context.source;
  10409. switch (mode) {
  10410. case 0 /* DATA */:
  10411. if (startsWith(s, '</')) {
  10412. // TODO: probably bad performance
  10413. for (let i = ancestors.length - 1; i >= 0; --i) {
  10414. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  10415. return true;
  10416. }
  10417. }
  10418. }
  10419. break;
  10420. case 1 /* RCDATA */:
  10421. case 2 /* RAWTEXT */: {
  10422. const parent = last(ancestors);
  10423. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  10424. return true;
  10425. }
  10426. break;
  10427. }
  10428. case 3 /* CDATA */:
  10429. if (startsWith(s, ']]>')) {
  10430. return true;
  10431. }
  10432. break;
  10433. }
  10434. return !s;
  10435. }
  10436. function startsWithEndTagOpen(source, tag) {
  10437. return (startsWith(source, '</') &&
  10438. source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
  10439. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  10440. }
  10441. function hoistStatic(root, context) {
  10442. walk(root, context,
  10443. // Root node is unfortunately non-hoistable due to potential parent
  10444. // fallthrough attributes.
  10445. isSingleElementRoot(root, root.children[0]));
  10446. }
  10447. function isSingleElementRoot(root, child) {
  10448. const { children } = root;
  10449. return (children.length === 1 &&
  10450. child.type === 1 /* ELEMENT */ &&
  10451. !isSlotOutlet(child));
  10452. }
  10453. function walk(node, context, doNotHoistNode = false) {
  10454. let hasHoistedNode = false;
  10455. // Some transforms, e.g. transformAssetUrls from @vue/compiler-sfc, replaces
  10456. // static bindings with expressions. These expressions are guaranteed to be
  10457. // constant so they are still eligible for hoisting, but they are only
  10458. // available at runtime and therefore cannot be evaluated ahead of time.
  10459. // This is only a concern for pre-stringification (via transformHoist by
  10460. // @vue/compiler-dom), but doing it here allows us to perform only one full
  10461. // walk of the AST and allow `stringifyStatic` to stop walking as soon as its
  10462. // stringficiation threshold is met.
  10463. let canStringify = true;
  10464. const { children } = node;
  10465. for (let i = 0; i < children.length; i++) {
  10466. const child = children[i];
  10467. // only plain elements & text calls are eligible for hoisting.
  10468. if (child.type === 1 /* ELEMENT */ &&
  10469. child.tagType === 0 /* ELEMENT */) {
  10470. const constantType = doNotHoistNode
  10471. ? 0 /* NOT_CONSTANT */
  10472. : getConstantType(child, context);
  10473. if (constantType > 0 /* NOT_CONSTANT */) {
  10474. if (constantType < 3 /* CAN_STRINGIFY */) {
  10475. canStringify = false;
  10476. }
  10477. if (constantType >= 2 /* CAN_HOIST */) {
  10478. child.codegenNode.patchFlag =
  10479. -1 /* HOISTED */ + (` /* HOISTED */` );
  10480. child.codegenNode = context.hoist(child.codegenNode);
  10481. hasHoistedNode = true;
  10482. continue;
  10483. }
  10484. }
  10485. else {
  10486. // node may contain dynamic children, but its props may be eligible for
  10487. // hoisting.
  10488. const codegenNode = child.codegenNode;
  10489. if (codegenNode.type === 13 /* VNODE_CALL */) {
  10490. const flag = getPatchFlag(codegenNode);
  10491. if ((!flag ||
  10492. flag === 512 /* NEED_PATCH */ ||
  10493. flag === 1 /* TEXT */) &&
  10494. getGeneratedPropsConstantType(child, context) >=
  10495. 2 /* CAN_HOIST */) {
  10496. const props = getNodeProps(child);
  10497. if (props) {
  10498. codegenNode.props = context.hoist(props);
  10499. }
  10500. }
  10501. }
  10502. }
  10503. }
  10504. else if (child.type === 12 /* TEXT_CALL */) {
  10505. const contentType = getConstantType(child.content, context);
  10506. if (contentType > 0) {
  10507. if (contentType < 3 /* CAN_STRINGIFY */) {
  10508. canStringify = false;
  10509. }
  10510. if (contentType >= 2 /* CAN_HOIST */) {
  10511. child.codegenNode = context.hoist(child.codegenNode);
  10512. hasHoistedNode = true;
  10513. }
  10514. }
  10515. }
  10516. // walk further
  10517. if (child.type === 1 /* ELEMENT */) {
  10518. walk(child, context);
  10519. }
  10520. else if (child.type === 11 /* FOR */) {
  10521. // Do not hoist v-for single child because it has to be a block
  10522. walk(child, context, child.children.length === 1);
  10523. }
  10524. else if (child.type === 9 /* IF */) {
  10525. for (let i = 0; i < child.branches.length; i++) {
  10526. // Do not hoist v-if single child because it has to be a block
  10527. walk(child.branches[i], context, child.branches[i].children.length === 1);
  10528. }
  10529. }
  10530. }
  10531. if (canStringify && hasHoistedNode && context.transformHoist) {
  10532. context.transformHoist(children, context, node);
  10533. }
  10534. }
  10535. function getConstantType(node, context) {
  10536. const { constantCache } = context;
  10537. switch (node.type) {
  10538. case 1 /* ELEMENT */:
  10539. if (node.tagType !== 0 /* ELEMENT */) {
  10540. return 0 /* NOT_CONSTANT */;
  10541. }
  10542. const cached = constantCache.get(node);
  10543. if (cached !== undefined) {
  10544. return cached;
  10545. }
  10546. const codegenNode = node.codegenNode;
  10547. if (codegenNode.type !== 13 /* VNODE_CALL */) {
  10548. return 0 /* NOT_CONSTANT */;
  10549. }
  10550. const flag = getPatchFlag(codegenNode);
  10551. if (!flag) {
  10552. let returnType = 3 /* CAN_STRINGIFY */;
  10553. // Element itself has no patch flag. However we still need to check:
  10554. // 1. Even for a node with no patch flag, it is possible for it to contain
  10555. // non-hoistable expressions that refers to scope variables, e.g. compiler
  10556. // injected keys or cached event handlers. Therefore we need to always
  10557. // check the codegenNode's props to be sure.
  10558. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  10559. if (generatedPropsType === 0 /* NOT_CONSTANT */) {
  10560. constantCache.set(node, 0 /* NOT_CONSTANT */);
  10561. return 0 /* NOT_CONSTANT */;
  10562. }
  10563. if (generatedPropsType < returnType) {
  10564. returnType = generatedPropsType;
  10565. }
  10566. // 2. its children.
  10567. for (let i = 0; i < node.children.length; i++) {
  10568. const childType = getConstantType(node.children[i], context);
  10569. if (childType === 0 /* NOT_CONSTANT */) {
  10570. constantCache.set(node, 0 /* NOT_CONSTANT */);
  10571. return 0 /* NOT_CONSTANT */;
  10572. }
  10573. if (childType < returnType) {
  10574. returnType = childType;
  10575. }
  10576. }
  10577. // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
  10578. // type, check if any of the props can cause the type to be lowered
  10579. // we can skip can_patch because it's guaranteed by the absence of a
  10580. // patchFlag.
  10581. if (returnType > 1 /* CAN_SKIP_PATCH */) {
  10582. for (let i = 0; i < node.props.length; i++) {
  10583. const p = node.props[i];
  10584. if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
  10585. const expType = getConstantType(p.exp, context);
  10586. if (expType === 0 /* NOT_CONSTANT */) {
  10587. constantCache.set(node, 0 /* NOT_CONSTANT */);
  10588. return 0 /* NOT_CONSTANT */;
  10589. }
  10590. if (expType < returnType) {
  10591. returnType = expType;
  10592. }
  10593. }
  10594. }
  10595. }
  10596. // only svg/foreignObject could be block here, however if they are
  10597. // static then they don't need to be blocks since there will be no
  10598. // nested updates.
  10599. if (codegenNode.isBlock) {
  10600. codegenNode.isBlock = false;
  10601. context.helper(CREATE_VNODE);
  10602. }
  10603. constantCache.set(node, returnType);
  10604. return returnType;
  10605. }
  10606. else {
  10607. constantCache.set(node, 0 /* NOT_CONSTANT */);
  10608. return 0 /* NOT_CONSTANT */;
  10609. }
  10610. case 2 /* TEXT */:
  10611. case 3 /* COMMENT */:
  10612. return 3 /* CAN_STRINGIFY */;
  10613. case 9 /* IF */:
  10614. case 11 /* FOR */:
  10615. case 10 /* IF_BRANCH */:
  10616. return 0 /* NOT_CONSTANT */;
  10617. case 5 /* INTERPOLATION */:
  10618. case 12 /* TEXT_CALL */:
  10619. return getConstantType(node.content, context);
  10620. case 4 /* SIMPLE_EXPRESSION */:
  10621. return node.constType;
  10622. case 8 /* COMPOUND_EXPRESSION */:
  10623. let returnType = 3 /* CAN_STRINGIFY */;
  10624. for (let i = 0; i < node.children.length; i++) {
  10625. const child = node.children[i];
  10626. if (isString(child) || isSymbol(child)) {
  10627. continue;
  10628. }
  10629. const childType = getConstantType(child, context);
  10630. if (childType === 0 /* NOT_CONSTANT */) {
  10631. return 0 /* NOT_CONSTANT */;
  10632. }
  10633. else if (childType < returnType) {
  10634. returnType = childType;
  10635. }
  10636. }
  10637. return returnType;
  10638. default:
  10639. return 0 /* NOT_CONSTANT */;
  10640. }
  10641. }
  10642. function getGeneratedPropsConstantType(node, context) {
  10643. let returnType = 3 /* CAN_STRINGIFY */;
  10644. const props = getNodeProps(node);
  10645. if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  10646. const { properties } = props;
  10647. for (let i = 0; i < properties.length; i++) {
  10648. const { key, value } = properties[i];
  10649. const keyType = getConstantType(key, context);
  10650. if (keyType === 0 /* NOT_CONSTANT */) {
  10651. return keyType;
  10652. }
  10653. if (keyType < returnType) {
  10654. returnType = keyType;
  10655. }
  10656. if (value.type !== 4 /* SIMPLE_EXPRESSION */) {
  10657. return 0 /* NOT_CONSTANT */;
  10658. }
  10659. const valueType = getConstantType(value, context);
  10660. if (valueType === 0 /* NOT_CONSTANT */) {
  10661. return valueType;
  10662. }
  10663. if (valueType < returnType) {
  10664. returnType = valueType;
  10665. }
  10666. }
  10667. }
  10668. return returnType;
  10669. }
  10670. function getNodeProps(node) {
  10671. const codegenNode = node.codegenNode;
  10672. if (codegenNode.type === 13 /* VNODE_CALL */) {
  10673. return codegenNode.props;
  10674. }
  10675. }
  10676. function getPatchFlag(node) {
  10677. const flag = node.patchFlag;
  10678. return flag ? parseInt(flag, 10) : undefined;
  10679. }
  10680. function createTransformContext(root, { filename = '', prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = NOOP, isCustomElement = NOOP, expressionPlugins = [], scopeId = null, ssr = false, ssrCssVars = ``, bindingMetadata = EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError }) {
  10681. const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
  10682. const context = {
  10683. // options
  10684. selfName: nameMatch && capitalize(camelize(nameMatch[1])),
  10685. prefixIdentifiers,
  10686. hoistStatic,
  10687. cacheHandlers,
  10688. nodeTransforms,
  10689. directiveTransforms,
  10690. transformHoist,
  10691. isBuiltInComponent,
  10692. isCustomElement,
  10693. expressionPlugins,
  10694. scopeId,
  10695. ssr,
  10696. ssrCssVars,
  10697. bindingMetadata,
  10698. inline,
  10699. isTS,
  10700. onError,
  10701. // state
  10702. root,
  10703. helpers: new Set(),
  10704. components: new Set(),
  10705. directives: new Set(),
  10706. hoists: [],
  10707. imports: [],
  10708. constantCache: new Map(),
  10709. temps: 0,
  10710. cached: 0,
  10711. identifiers: Object.create(null),
  10712. scopes: {
  10713. vFor: 0,
  10714. vSlot: 0,
  10715. vPre: 0,
  10716. vOnce: 0
  10717. },
  10718. parent: null,
  10719. currentNode: root,
  10720. childIndex: 0,
  10721. // methods
  10722. helper(name) {
  10723. context.helpers.add(name);
  10724. return name;
  10725. },
  10726. helperString(name) {
  10727. return `_${helperNameMap[context.helper(name)]}`;
  10728. },
  10729. replaceNode(node) {
  10730. /* istanbul ignore if */
  10731. {
  10732. if (!context.currentNode) {
  10733. throw new Error(`Node being replaced is already removed.`);
  10734. }
  10735. if (!context.parent) {
  10736. throw new Error(`Cannot replace root node.`);
  10737. }
  10738. }
  10739. context.parent.children[context.childIndex] = context.currentNode = node;
  10740. },
  10741. removeNode(node) {
  10742. if (!context.parent) {
  10743. throw new Error(`Cannot remove root node.`);
  10744. }
  10745. const list = context.parent.children;
  10746. const removalIndex = node
  10747. ? list.indexOf(node)
  10748. : context.currentNode
  10749. ? context.childIndex
  10750. : -1;
  10751. /* istanbul ignore if */
  10752. if (removalIndex < 0) {
  10753. throw new Error(`node being removed is not a child of current parent`);
  10754. }
  10755. if (!node || node === context.currentNode) {
  10756. // current node removed
  10757. context.currentNode = null;
  10758. context.onNodeRemoved();
  10759. }
  10760. else {
  10761. // sibling node removed
  10762. if (context.childIndex > removalIndex) {
  10763. context.childIndex--;
  10764. context.onNodeRemoved();
  10765. }
  10766. }
  10767. context.parent.children.splice(removalIndex, 1);
  10768. },
  10769. onNodeRemoved: () => { },
  10770. addIdentifiers(exp) {
  10771. },
  10772. removeIdentifiers(exp) {
  10773. },
  10774. hoist(exp) {
  10775. context.hoists.push(exp);
  10776. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
  10777. identifier.hoisted = exp;
  10778. return identifier;
  10779. },
  10780. cache(exp, isVNode = false) {
  10781. return createCacheExpression(++context.cached, exp, isVNode);
  10782. }
  10783. };
  10784. return context;
  10785. }
  10786. function transform(root, options) {
  10787. const context = createTransformContext(root, options);
  10788. traverseNode(root, context);
  10789. if (options.hoistStatic) {
  10790. hoistStatic(root, context);
  10791. }
  10792. if (!options.ssr) {
  10793. createRootCodegen(root, context);
  10794. }
  10795. // finalize meta information
  10796. root.helpers = [...context.helpers];
  10797. root.components = [...context.components];
  10798. root.directives = [...context.directives];
  10799. root.imports = context.imports;
  10800. root.hoists = context.hoists;
  10801. root.temps = context.temps;
  10802. root.cached = context.cached;
  10803. }
  10804. function createRootCodegen(root, context) {
  10805. const { helper } = context;
  10806. const { children } = root;
  10807. if (children.length === 1) {
  10808. const child = children[0];
  10809. // if the single child is an element, turn it into a block.
  10810. if (isSingleElementRoot(root, child) && child.codegenNode) {
  10811. // single element root is never hoisted so codegenNode will never be
  10812. // SimpleExpressionNode
  10813. const codegenNode = child.codegenNode;
  10814. if (codegenNode.type === 13 /* VNODE_CALL */) {
  10815. codegenNode.isBlock = true;
  10816. helper(OPEN_BLOCK);
  10817. helper(CREATE_BLOCK);
  10818. }
  10819. root.codegenNode = codegenNode;
  10820. }
  10821. else {
  10822. // - single <slot/>, IfNode, ForNode: already blocks.
  10823. // - single text node: always patched.
  10824. // root codegen falls through via genNode()
  10825. root.codegenNode = child;
  10826. }
  10827. }
  10828. else if (children.length > 1) {
  10829. // root has multiple nodes - return a fragment block.
  10830. let patchFlag = 64 /* STABLE_FRAGMENT */;
  10831. let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
  10832. // check if the fragment actually contains a single valid child with
  10833. // the rest being comments
  10834. if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
  10835. patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
  10836. patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
  10837. }
  10838. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true);
  10839. }
  10840. else ;
  10841. }
  10842. function traverseChildren(parent, context) {
  10843. let i = 0;
  10844. const nodeRemoved = () => {
  10845. i--;
  10846. };
  10847. for (; i < parent.children.length; i++) {
  10848. const child = parent.children[i];
  10849. if (isString(child))
  10850. continue;
  10851. context.parent = parent;
  10852. context.childIndex = i;
  10853. context.onNodeRemoved = nodeRemoved;
  10854. traverseNode(child, context);
  10855. }
  10856. }
  10857. function traverseNode(node, context) {
  10858. context.currentNode = node;
  10859. // apply transform plugins
  10860. const { nodeTransforms } = context;
  10861. const exitFns = [];
  10862. for (let i = 0; i < nodeTransforms.length; i++) {
  10863. const onExit = nodeTransforms[i](node, context);
  10864. if (onExit) {
  10865. if (isArray(onExit)) {
  10866. exitFns.push(...onExit);
  10867. }
  10868. else {
  10869. exitFns.push(onExit);
  10870. }
  10871. }
  10872. if (!context.currentNode) {
  10873. // node was removed
  10874. return;
  10875. }
  10876. else {
  10877. // node may have been replaced
  10878. node = context.currentNode;
  10879. }
  10880. }
  10881. switch (node.type) {
  10882. case 3 /* COMMENT */:
  10883. if (!context.ssr) {
  10884. // inject import for the Comment symbol, which is needed for creating
  10885. // comment nodes with `createVNode`
  10886. context.helper(CREATE_COMMENT);
  10887. }
  10888. break;
  10889. case 5 /* INTERPOLATION */:
  10890. // no need to traverse, but we need to inject toString helper
  10891. if (!context.ssr) {
  10892. context.helper(TO_DISPLAY_STRING);
  10893. }
  10894. break;
  10895. // for container types, further traverse downwards
  10896. case 9 /* IF */:
  10897. for (let i = 0; i < node.branches.length; i++) {
  10898. traverseNode(node.branches[i], context);
  10899. }
  10900. break;
  10901. case 10 /* IF_BRANCH */:
  10902. case 11 /* FOR */:
  10903. case 1 /* ELEMENT */:
  10904. case 0 /* ROOT */:
  10905. traverseChildren(node, context);
  10906. break;
  10907. }
  10908. // exit transforms
  10909. context.currentNode = node;
  10910. let i = exitFns.length;
  10911. while (i--) {
  10912. exitFns[i]();
  10913. }
  10914. }
  10915. function createStructuralDirectiveTransform(name, fn) {
  10916. const matches = isString(name)
  10917. ? (n) => n === name
  10918. : (n) => name.test(n);
  10919. return (node, context) => {
  10920. if (node.type === 1 /* ELEMENT */) {
  10921. const { props } = node;
  10922. // structural directive transforms are not concerned with slots
  10923. // as they are handled separately in vSlot.ts
  10924. if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
  10925. return;
  10926. }
  10927. const exitFns = [];
  10928. for (let i = 0; i < props.length; i++) {
  10929. const prop = props[i];
  10930. if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
  10931. // structural directives are removed to avoid infinite recursion
  10932. // also we remove them *before* applying so that it can further
  10933. // traverse itself in case it moves the node around
  10934. props.splice(i, 1);
  10935. i--;
  10936. const onExit = fn(node, prop, context);
  10937. if (onExit)
  10938. exitFns.push(onExit);
  10939. }
  10940. }
  10941. return exitFns;
  10942. }
  10943. };
  10944. }
  10945. const PURE_ANNOTATION = `/*#__PURE__*/`;
  10946. function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssr = false }) {
  10947. const context = {
  10948. mode,
  10949. prefixIdentifiers,
  10950. sourceMap,
  10951. filename,
  10952. scopeId,
  10953. optimizeImports,
  10954. runtimeGlobalName,
  10955. runtimeModuleName,
  10956. ssr,
  10957. source: ast.loc.source,
  10958. code: ``,
  10959. column: 1,
  10960. line: 1,
  10961. offset: 0,
  10962. indentLevel: 0,
  10963. pure: false,
  10964. map: undefined,
  10965. helper(key) {
  10966. return `_${helperNameMap[key]}`;
  10967. },
  10968. push(code, node) {
  10969. context.code += code;
  10970. },
  10971. indent() {
  10972. newline(++context.indentLevel);
  10973. },
  10974. deindent(withoutNewLine = false) {
  10975. if (withoutNewLine) {
  10976. --context.indentLevel;
  10977. }
  10978. else {
  10979. newline(--context.indentLevel);
  10980. }
  10981. },
  10982. newline() {
  10983. newline(context.indentLevel);
  10984. }
  10985. };
  10986. function newline(n) {
  10987. context.push('\n' + ` `.repeat(n));
  10988. }
  10989. return context;
  10990. }
  10991. function generate(ast, options = {}) {
  10992. const context = createCodegenContext(ast, options);
  10993. if (options.onContextCreated)
  10994. options.onContextCreated(context);
  10995. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  10996. const hasHelpers = ast.helpers.length > 0;
  10997. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  10998. // preambles
  10999. // in setup() inline mode, the preamble is generated in a sub context
  11000. // and returned separately.
  11001. const preambleContext = context;
  11002. {
  11003. genFunctionPreamble(ast, preambleContext);
  11004. }
  11005. // enter render function
  11006. const functionName = ssr ? `ssrRender` : `render`;
  11007. const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
  11008. const signature = args.join(', ');
  11009. {
  11010. push(`function ${functionName}(${signature}) {`);
  11011. }
  11012. indent();
  11013. if (useWithBlock) {
  11014. push(`with (_ctx) {`);
  11015. indent();
  11016. // function mode const declarations should be inside with block
  11017. // also they should be renamed to avoid collision with user properties
  11018. if (hasHelpers) {
  11019. push(`const { ${ast.helpers
  11020. .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
  11021. .join(', ')} } = _Vue`);
  11022. push(`\n`);
  11023. newline();
  11024. }
  11025. }
  11026. // generate asset resolution statements
  11027. if (ast.components.length) {
  11028. genAssets(ast.components, 'component', context);
  11029. if (ast.directives.length || ast.temps > 0) {
  11030. newline();
  11031. }
  11032. }
  11033. if (ast.directives.length) {
  11034. genAssets(ast.directives, 'directive', context);
  11035. if (ast.temps > 0) {
  11036. newline();
  11037. }
  11038. }
  11039. if (ast.temps > 0) {
  11040. push(`let `);
  11041. for (let i = 0; i < ast.temps; i++) {
  11042. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  11043. }
  11044. }
  11045. if (ast.components.length || ast.directives.length || ast.temps) {
  11046. push(`\n`);
  11047. newline();
  11048. }
  11049. // generate the VNode tree expression
  11050. if (!ssr) {
  11051. push(`return `);
  11052. }
  11053. if (ast.codegenNode) {
  11054. genNode(ast.codegenNode, context);
  11055. }
  11056. else {
  11057. push(`null`);
  11058. }
  11059. if (useWithBlock) {
  11060. deindent();
  11061. push(`}`);
  11062. }
  11063. deindent();
  11064. push(`}`);
  11065. return {
  11066. ast,
  11067. code: context.code,
  11068. preamble: ``,
  11069. // SourceMapGenerator does have toJSON() method but it's not in the types
  11070. map: context.map ? context.map.toJSON() : undefined
  11071. };
  11072. }
  11073. function genFunctionPreamble(ast, context) {
  11074. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context;
  11075. const VueBinding = runtimeGlobalName;
  11076. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  11077. // Generate const declaration for helpers
  11078. // In prefix mode, we place the const declaration at top so it's done
  11079. // only once; But if we not prefixing, we place the declaration inside the
  11080. // with block so it doesn't incur the `in` check cost for every helper access.
  11081. if (ast.helpers.length > 0) {
  11082. {
  11083. // "with" mode.
  11084. // save Vue in a separate variable to avoid collision
  11085. push(`const _Vue = ${VueBinding}\n`);
  11086. // in "with" mode, helpers are declared inside the with block to avoid
  11087. // has check cost, but hoists are lifted out of the function - we need
  11088. // to provide the helper here.
  11089. if (ast.hoists.length) {
  11090. const staticHelpers = [
  11091. CREATE_VNODE,
  11092. CREATE_COMMENT,
  11093. CREATE_TEXT,
  11094. CREATE_STATIC
  11095. ]
  11096. .filter(helper => ast.helpers.includes(helper))
  11097. .map(aliasHelper)
  11098. .join(', ');
  11099. push(`const { ${staticHelpers} } = _Vue\n`);
  11100. }
  11101. }
  11102. }
  11103. genHoists(ast.hoists, context);
  11104. newline();
  11105. push(`return `);
  11106. }
  11107. function genAssets(assets, type, { helper, push, newline }) {
  11108. const resolver = helper(type === 'component' ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE);
  11109. for (let i = 0; i < assets.length; i++) {
  11110. const id = assets[i];
  11111. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)})`);
  11112. if (i < assets.length - 1) {
  11113. newline();
  11114. }
  11115. }
  11116. }
  11117. function genHoists(hoists, context) {
  11118. if (!hoists.length) {
  11119. return;
  11120. }
  11121. context.pure = true;
  11122. const { push, newline, helper, scopeId, mode } = context;
  11123. newline();
  11124. hoists.forEach((exp, i) => {
  11125. if (exp) {
  11126. push(`const _hoisted_${i + 1} = `);
  11127. genNode(exp, context);
  11128. newline();
  11129. }
  11130. });
  11131. context.pure = false;
  11132. }
  11133. function isText$1(n) {
  11134. return (isString(n) ||
  11135. n.type === 4 /* SIMPLE_EXPRESSION */ ||
  11136. n.type === 2 /* TEXT */ ||
  11137. n.type === 5 /* INTERPOLATION */ ||
  11138. n.type === 8 /* COMPOUND_EXPRESSION */);
  11139. }
  11140. function genNodeListAsArray(nodes, context) {
  11141. const multilines = nodes.length > 3 ||
  11142. (nodes.some(n => isArray(n) || !isText$1(n)));
  11143. context.push(`[`);
  11144. multilines && context.indent();
  11145. genNodeList(nodes, context, multilines);
  11146. multilines && context.deindent();
  11147. context.push(`]`);
  11148. }
  11149. function genNodeList(nodes, context, multilines = false, comma = true) {
  11150. const { push, newline } = context;
  11151. for (let i = 0; i < nodes.length; i++) {
  11152. const node = nodes[i];
  11153. if (isString(node)) {
  11154. push(node);
  11155. }
  11156. else if (isArray(node)) {
  11157. genNodeListAsArray(node, context);
  11158. }
  11159. else {
  11160. genNode(node, context);
  11161. }
  11162. if (i < nodes.length - 1) {
  11163. if (multilines) {
  11164. comma && push(',');
  11165. newline();
  11166. }
  11167. else {
  11168. comma && push(', ');
  11169. }
  11170. }
  11171. }
  11172. }
  11173. function genNode(node, context) {
  11174. if (isString(node)) {
  11175. context.push(node);
  11176. return;
  11177. }
  11178. if (isSymbol(node)) {
  11179. context.push(context.helper(node));
  11180. return;
  11181. }
  11182. switch (node.type) {
  11183. case 1 /* ELEMENT */:
  11184. case 9 /* IF */:
  11185. case 11 /* FOR */:
  11186. assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  11187. `Apply appropriate transforms first.`);
  11188. genNode(node.codegenNode, context);
  11189. break;
  11190. case 2 /* TEXT */:
  11191. genText(node, context);
  11192. break;
  11193. case 4 /* SIMPLE_EXPRESSION */:
  11194. genExpression(node, context);
  11195. break;
  11196. case 5 /* INTERPOLATION */:
  11197. genInterpolation(node, context);
  11198. break;
  11199. case 12 /* TEXT_CALL */:
  11200. genNode(node.codegenNode, context);
  11201. break;
  11202. case 8 /* COMPOUND_EXPRESSION */:
  11203. genCompoundExpression(node, context);
  11204. break;
  11205. case 3 /* COMMENT */:
  11206. genComment(node, context);
  11207. break;
  11208. case 13 /* VNODE_CALL */:
  11209. genVNodeCall(node, context);
  11210. break;
  11211. case 14 /* JS_CALL_EXPRESSION */:
  11212. genCallExpression(node, context);
  11213. break;
  11214. case 15 /* JS_OBJECT_EXPRESSION */:
  11215. genObjectExpression(node, context);
  11216. break;
  11217. case 17 /* JS_ARRAY_EXPRESSION */:
  11218. genArrayExpression(node, context);
  11219. break;
  11220. case 18 /* JS_FUNCTION_EXPRESSION */:
  11221. genFunctionExpression(node, context);
  11222. break;
  11223. case 19 /* JS_CONDITIONAL_EXPRESSION */:
  11224. genConditionalExpression(node, context);
  11225. break;
  11226. case 20 /* JS_CACHE_EXPRESSION */:
  11227. genCacheExpression(node, context);
  11228. break;
  11229. // SSR only types
  11230. case 21 /* JS_BLOCK_STATEMENT */:
  11231. break;
  11232. case 22 /* JS_TEMPLATE_LITERAL */:
  11233. break;
  11234. case 23 /* JS_IF_STATEMENT */:
  11235. break;
  11236. case 24 /* JS_ASSIGNMENT_EXPRESSION */:
  11237. break;
  11238. case 25 /* JS_SEQUENCE_EXPRESSION */:
  11239. break;
  11240. case 26 /* JS_RETURN_STATEMENT */:
  11241. break;
  11242. /* istanbul ignore next */
  11243. case 10 /* IF_BRANCH */:
  11244. // noop
  11245. break;
  11246. default:
  11247. {
  11248. assert(false, `unhandled codegen node type: ${node.type}`);
  11249. // make sure we exhaust all possible types
  11250. const exhaustiveCheck = node;
  11251. return exhaustiveCheck;
  11252. }
  11253. }
  11254. }
  11255. function genText(node, context) {
  11256. context.push(JSON.stringify(node.content), node);
  11257. }
  11258. function genExpression(node, context) {
  11259. const { content, isStatic } = node;
  11260. context.push(isStatic ? JSON.stringify(content) : content, node);
  11261. }
  11262. function genInterpolation(node, context) {
  11263. const { push, helper, pure } = context;
  11264. if (pure)
  11265. push(PURE_ANNOTATION);
  11266. push(`${helper(TO_DISPLAY_STRING)}(`);
  11267. genNode(node.content, context);
  11268. push(`)`);
  11269. }
  11270. function genCompoundExpression(node, context) {
  11271. for (let i = 0; i < node.children.length; i++) {
  11272. const child = node.children[i];
  11273. if (isString(child)) {
  11274. context.push(child);
  11275. }
  11276. else {
  11277. genNode(child, context);
  11278. }
  11279. }
  11280. }
  11281. function genExpressionAsPropertyKey(node, context) {
  11282. const { push } = context;
  11283. if (node.type === 8 /* COMPOUND_EXPRESSION */) {
  11284. push(`[`);
  11285. genCompoundExpression(node, context);
  11286. push(`]`);
  11287. }
  11288. else if (node.isStatic) {
  11289. // only quote keys if necessary
  11290. const text = isSimpleIdentifier(node.content)
  11291. ? node.content
  11292. : JSON.stringify(node.content);
  11293. push(text, node);
  11294. }
  11295. else {
  11296. push(`[${node.content}]`, node);
  11297. }
  11298. }
  11299. function genComment(node, context) {
  11300. {
  11301. const { push, helper, pure } = context;
  11302. if (pure) {
  11303. push(PURE_ANNOTATION);
  11304. }
  11305. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  11306. }
  11307. }
  11308. function genVNodeCall(node, context) {
  11309. const { push, helper, pure } = context;
  11310. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking } = node;
  11311. if (directives) {
  11312. push(helper(WITH_DIRECTIVES) + `(`);
  11313. }
  11314. if (isBlock) {
  11315. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  11316. }
  11317. if (pure) {
  11318. push(PURE_ANNOTATION);
  11319. }
  11320. push(helper(isBlock ? CREATE_BLOCK : CREATE_VNODE) + `(`, node);
  11321. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  11322. push(`)`);
  11323. if (isBlock) {
  11324. push(`)`);
  11325. }
  11326. if (directives) {
  11327. push(`, `);
  11328. genNode(directives, context);
  11329. push(`)`);
  11330. }
  11331. }
  11332. function genNullableArgs(args) {
  11333. let i = args.length;
  11334. while (i--) {
  11335. if (args[i] != null)
  11336. break;
  11337. }
  11338. return args.slice(0, i + 1).map(arg => arg || `null`);
  11339. }
  11340. // JavaScript
  11341. function genCallExpression(node, context) {
  11342. const { push, helper, pure } = context;
  11343. const callee = isString(node.callee) ? node.callee : helper(node.callee);
  11344. if (pure) {
  11345. push(PURE_ANNOTATION);
  11346. }
  11347. push(callee + `(`, node);
  11348. genNodeList(node.arguments, context);
  11349. push(`)`);
  11350. }
  11351. function genObjectExpression(node, context) {
  11352. const { push, indent, deindent, newline } = context;
  11353. const { properties } = node;
  11354. if (!properties.length) {
  11355. push(`{}`, node);
  11356. return;
  11357. }
  11358. const multilines = properties.length > 1 ||
  11359. (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
  11360. push(multilines ? `{` : `{ `);
  11361. multilines && indent();
  11362. for (let i = 0; i < properties.length; i++) {
  11363. const { key, value } = properties[i];
  11364. // key
  11365. genExpressionAsPropertyKey(key, context);
  11366. push(`: `);
  11367. // value
  11368. genNode(value, context);
  11369. if (i < properties.length - 1) {
  11370. // will only reach this if it's multilines
  11371. push(`,`);
  11372. newline();
  11373. }
  11374. }
  11375. multilines && deindent();
  11376. push(multilines ? `}` : ` }`);
  11377. }
  11378. function genArrayExpression(node, context) {
  11379. genNodeListAsArray(node.elements, context);
  11380. }
  11381. function genFunctionExpression(node, context) {
  11382. const { push, indent, deindent, scopeId, mode } = context;
  11383. const { params, returns, body, newline, isSlot } = node;
  11384. if (isSlot) {
  11385. push(`_${helperNameMap[WITH_CTX]}(`);
  11386. }
  11387. push(`(`, node);
  11388. if (isArray(params)) {
  11389. genNodeList(params, context);
  11390. }
  11391. else if (params) {
  11392. genNode(params, context);
  11393. }
  11394. push(`) => `);
  11395. if (newline || body) {
  11396. push(`{`);
  11397. indent();
  11398. }
  11399. if (returns) {
  11400. if (newline) {
  11401. push(`return `);
  11402. }
  11403. if (isArray(returns)) {
  11404. genNodeListAsArray(returns, context);
  11405. }
  11406. else {
  11407. genNode(returns, context);
  11408. }
  11409. }
  11410. else if (body) {
  11411. genNode(body, context);
  11412. }
  11413. if (newline || body) {
  11414. deindent();
  11415. push(`}`);
  11416. }
  11417. if (isSlot) {
  11418. push(`)`);
  11419. }
  11420. }
  11421. function genConditionalExpression(node, context) {
  11422. const { test, consequent, alternate, newline: needNewline } = node;
  11423. const { push, indent, deindent, newline } = context;
  11424. if (test.type === 4 /* SIMPLE_EXPRESSION */) {
  11425. const needsParens = !isSimpleIdentifier(test.content);
  11426. needsParens && push(`(`);
  11427. genExpression(test, context);
  11428. needsParens && push(`)`);
  11429. }
  11430. else {
  11431. push(`(`);
  11432. genNode(test, context);
  11433. push(`)`);
  11434. }
  11435. needNewline && indent();
  11436. context.indentLevel++;
  11437. needNewline || push(` `);
  11438. push(`? `);
  11439. genNode(consequent, context);
  11440. context.indentLevel--;
  11441. needNewline && newline();
  11442. needNewline || push(` `);
  11443. push(`: `);
  11444. const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
  11445. if (!isNested) {
  11446. context.indentLevel++;
  11447. }
  11448. genNode(alternate, context);
  11449. if (!isNested) {
  11450. context.indentLevel--;
  11451. }
  11452. needNewline && deindent(true /* without newline */);
  11453. }
  11454. function genCacheExpression(node, context) {
  11455. const { push, helper, indent, deindent, newline } = context;
  11456. push(`_cache[${node.index}] || (`);
  11457. if (node.isVNode) {
  11458. indent();
  11459. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  11460. newline();
  11461. }
  11462. push(`_cache[${node.index}] = `);
  11463. genNode(node.value, context);
  11464. if (node.isVNode) {
  11465. push(`,`);
  11466. newline();
  11467. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  11468. newline();
  11469. push(`_cache[${node.index}]`);
  11470. deindent();
  11471. }
  11472. push(`)`);
  11473. }
  11474. // these keywords should not appear inside expressions, but operators like
  11475. // typeof, instanceof and in are allowed
  11476. const prohibitedKeywordRE = new RegExp('\\b' +
  11477. ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
  11478. 'super,throw,while,yield,delete,export,import,return,switch,default,' +
  11479. 'extends,finally,continue,debugger,function,arguments,typeof,void')
  11480. .split(',')
  11481. .join('\\b|\\b') +
  11482. '\\b');
  11483. // strip strings in expressions
  11484. const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
  11485. /**
  11486. * Validate a non-prefixed expression.
  11487. * This is only called when using the in-browser runtime compiler since it
  11488. * doesn't prefix expressions.
  11489. */
  11490. function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
  11491. const exp = node.content;
  11492. // empty expressions are validated per-directive since some directives
  11493. // do allow empty expressions.
  11494. if (!exp.trim()) {
  11495. return;
  11496. }
  11497. try {
  11498. new Function(asRawStatements
  11499. ? ` ${exp} `
  11500. : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
  11501. }
  11502. catch (e) {
  11503. let message = e.message;
  11504. const keywordMatch = exp
  11505. .replace(stripStringRE, '')
  11506. .match(prohibitedKeywordRE);
  11507. if (keywordMatch) {
  11508. message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
  11509. }
  11510. context.onError(createCompilerError(43 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
  11511. }
  11512. }
  11513. const transformExpression = (node, context) => {
  11514. if (node.type === 5 /* INTERPOLATION */) {
  11515. node.content = processExpression(node.content, context);
  11516. }
  11517. else if (node.type === 1 /* ELEMENT */) {
  11518. // handle directives on element
  11519. for (let i = 0; i < node.props.length; i++) {
  11520. const dir = node.props[i];
  11521. // do not process for v-on & v-for since they are special handled
  11522. if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
  11523. const exp = dir.exp;
  11524. const arg = dir.arg;
  11525. // do not process exp if this is v-on:arg - we need special handling
  11526. // for wrapping inline statements.
  11527. if (exp &&
  11528. exp.type === 4 /* SIMPLE_EXPRESSION */ &&
  11529. !(dir.name === 'on' && arg)) {
  11530. dir.exp = processExpression(exp, context,
  11531. // slot args must be processed as function params
  11532. dir.name === 'slot');
  11533. }
  11534. if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
  11535. dir.arg = processExpression(arg, context);
  11536. }
  11537. }
  11538. }
  11539. }
  11540. };
  11541. // Important: since this function uses Node.js only dependencies, it should
  11542. // always be used with a leading !true check so that it can be
  11543. // tree-shaken from the browser build.
  11544. function processExpression(node, context,
  11545. // some expressions like v-slot props & v-for aliases should be parsed as
  11546. // function params
  11547. asParams = false,
  11548. // v-on handler values may contain multiple statements
  11549. asRawStatements = false) {
  11550. {
  11551. {
  11552. // simple in-browser validation (same logic in 2.x)
  11553. validateBrowserExpression(node, context, asParams, asRawStatements);
  11554. }
  11555. return node;
  11556. }
  11557. }
  11558. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  11559. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  11560. // #1587: We need to dynamically increment the key based on the current
  11561. // node's sibling nodes, since chained v-if/else branches are
  11562. // rendered at the same depth
  11563. const siblings = context.parent.children;
  11564. let i = siblings.indexOf(ifNode);
  11565. let key = 0;
  11566. while (i-- >= 0) {
  11567. const sibling = siblings[i];
  11568. if (sibling && sibling.type === 9 /* IF */) {
  11569. key += sibling.branches.length;
  11570. }
  11571. }
  11572. // Exit callback. Complete the codegenNode when all children have been
  11573. // transformed.
  11574. return () => {
  11575. if (isRoot) {
  11576. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  11577. }
  11578. else {
  11579. // attach this branch's codegen node to the v-if root.
  11580. const parentCondition = getParentCondition(ifNode.codegenNode);
  11581. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  11582. }
  11583. };
  11584. });
  11585. });
  11586. // target-agnostic transform used for both Client and SSR
  11587. function processIf(node, dir, context, processCodegen) {
  11588. if (dir.name !== 'else' &&
  11589. (!dir.exp || !dir.exp.content.trim())) {
  11590. const loc = dir.exp ? dir.exp.loc : node.loc;
  11591. context.onError(createCompilerError(27 /* X_V_IF_NO_EXPRESSION */, dir.loc));
  11592. dir.exp = createSimpleExpression(`true`, false, loc);
  11593. }
  11594. if (dir.exp) {
  11595. validateBrowserExpression(dir.exp, context);
  11596. }
  11597. if (dir.name === 'if') {
  11598. const branch = createIfBranch(node, dir);
  11599. const ifNode = {
  11600. type: 9 /* IF */,
  11601. loc: node.loc,
  11602. branches: [branch]
  11603. };
  11604. context.replaceNode(ifNode);
  11605. if (processCodegen) {
  11606. return processCodegen(ifNode, branch, true);
  11607. }
  11608. }
  11609. else {
  11610. // locate the adjacent v-if
  11611. const siblings = context.parent.children;
  11612. const comments = [];
  11613. let i = siblings.indexOf(node);
  11614. while (i-- >= -1) {
  11615. const sibling = siblings[i];
  11616. if (sibling && sibling.type === 3 /* COMMENT */) {
  11617. context.removeNode(sibling);
  11618. comments.unshift(sibling);
  11619. continue;
  11620. }
  11621. if (sibling &&
  11622. sibling.type === 2 /* TEXT */ &&
  11623. !sibling.content.trim().length) {
  11624. context.removeNode(sibling);
  11625. continue;
  11626. }
  11627. if (sibling && sibling.type === 9 /* IF */) {
  11628. // move the node to the if node's branches
  11629. context.removeNode();
  11630. const branch = createIfBranch(node, dir);
  11631. if (comments.length) {
  11632. branch.children = [...comments, ...branch.children];
  11633. }
  11634. // check if user is forcing same key on different branches
  11635. {
  11636. const key = branch.userKey;
  11637. if (key) {
  11638. sibling.branches.forEach(({ userKey }) => {
  11639. if (isSameKey(userKey, key)) {
  11640. context.onError(createCompilerError(28 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
  11641. }
  11642. });
  11643. }
  11644. }
  11645. sibling.branches.push(branch);
  11646. const onExit = processCodegen && processCodegen(sibling, branch, false);
  11647. // since the branch was removed, it will not be traversed.
  11648. // make sure to traverse here.
  11649. traverseNode(branch, context);
  11650. // call on exit
  11651. if (onExit)
  11652. onExit();
  11653. // make sure to reset currentNode after traversal to indicate this
  11654. // node has been removed.
  11655. context.currentNode = null;
  11656. }
  11657. else {
  11658. context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  11659. }
  11660. break;
  11661. }
  11662. }
  11663. }
  11664. function createIfBranch(node, dir) {
  11665. return {
  11666. type: 10 /* IF_BRANCH */,
  11667. loc: node.loc,
  11668. condition: dir.name === 'else' ? undefined : dir.exp,
  11669. children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
  11670. ? node.children
  11671. : [node],
  11672. userKey: findProp(node, `key`)
  11673. };
  11674. }
  11675. function createCodegenNodeForBranch(branch, keyIndex, context) {
  11676. if (branch.condition) {
  11677. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  11678. // make sure to pass in asBlock: true so that the comment node call
  11679. // closes the current block.
  11680. createCallExpression(context.helper(CREATE_COMMENT), [
  11681. '"v-if"' ,
  11682. 'true'
  11683. ]));
  11684. }
  11685. else {
  11686. return createChildrenCodegenNode(branch, keyIndex, context);
  11687. }
  11688. }
  11689. function createChildrenCodegenNode(branch, keyIndex, context) {
  11690. const { helper } = context;
  11691. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
  11692. const { children } = branch;
  11693. const firstChild = children[0];
  11694. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
  11695. if (needFragmentWrapper) {
  11696. if (children.length === 1 && firstChild.type === 11 /* FOR */) {
  11697. // optimize away nested fragments when child is a ForNode
  11698. const vnodeCall = firstChild.codegenNode;
  11699. injectProp(vnodeCall, keyProperty, context);
  11700. return vnodeCall;
  11701. }
  11702. else {
  11703. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, 64 /* STABLE_FRAGMENT */ +
  11704. (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
  11705. ), undefined, undefined, true, false, branch.loc);
  11706. }
  11707. }
  11708. else {
  11709. const vnodeCall = firstChild
  11710. .codegenNode;
  11711. // Change createVNode to createBlock.
  11712. if (vnodeCall.type === 13 /* VNODE_CALL */) {
  11713. vnodeCall.isBlock = true;
  11714. helper(OPEN_BLOCK);
  11715. helper(CREATE_BLOCK);
  11716. }
  11717. // inject branch key
  11718. injectProp(vnodeCall, keyProperty, context);
  11719. return vnodeCall;
  11720. }
  11721. }
  11722. function isSameKey(a, b) {
  11723. if (!a || a.type !== b.type) {
  11724. return false;
  11725. }
  11726. if (a.type === 6 /* ATTRIBUTE */) {
  11727. if (a.value.content !== b.value.content) {
  11728. return false;
  11729. }
  11730. }
  11731. else {
  11732. // directive
  11733. const exp = a.exp;
  11734. const branchExp = b.exp;
  11735. if (exp.type !== branchExp.type) {
  11736. return false;
  11737. }
  11738. if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
  11739. (exp.isStatic !== branchExp.isStatic ||
  11740. exp.content !== branchExp.content)) {
  11741. return false;
  11742. }
  11743. }
  11744. return true;
  11745. }
  11746. function getParentCondition(node) {
  11747. while (true) {
  11748. if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  11749. if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  11750. node = node.alternate;
  11751. }
  11752. else {
  11753. return node;
  11754. }
  11755. }
  11756. else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
  11757. node = node.value;
  11758. }
  11759. }
  11760. }
  11761. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  11762. const { helper } = context;
  11763. return processFor(node, dir, context, forNode => {
  11764. // create the loop render function expression now, and add the
  11765. // iterator on exit after all children have been traversed
  11766. const renderExp = createCallExpression(helper(RENDER_LIST), [
  11767. forNode.source
  11768. ]);
  11769. const keyProp = findProp(node, `key`);
  11770. const keyProperty = keyProp
  11771. ? createObjectProperty(`key`, keyProp.type === 6 /* ATTRIBUTE */
  11772. ? createSimpleExpression(keyProp.value.content, true)
  11773. : keyProp.exp)
  11774. : null;
  11775. const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
  11776. forNode.source.constType > 0 /* NOT_CONSTANT */;
  11777. const fragmentFlag = isStableFragment
  11778. ? 64 /* STABLE_FRAGMENT */
  11779. : keyProp
  11780. ? 128 /* KEYED_FRAGMENT */
  11781. : 256 /* UNKEYED_FRAGMENT */;
  11782. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
  11783. (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, node.loc);
  11784. return () => {
  11785. // finish the codegen now that all children have been traversed
  11786. let childBlock;
  11787. const isTemplate = isTemplateNode(node);
  11788. const { children } = forNode;
  11789. // check <template v-for> key placement
  11790. if (isTemplate) {
  11791. node.children.some(c => {
  11792. if (c.type === 1 /* ELEMENT */) {
  11793. const key = findProp(c, 'key');
  11794. if (key) {
  11795. context.onError(createCompilerError(32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  11796. return true;
  11797. }
  11798. }
  11799. });
  11800. }
  11801. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
  11802. const slotOutlet = isSlotOutlet(node)
  11803. ? node
  11804. : isTemplate &&
  11805. node.children.length === 1 &&
  11806. isSlotOutlet(node.children[0])
  11807. ? node.children[0] // api-extractor somehow fails to infer this
  11808. : null;
  11809. if (slotOutlet) {
  11810. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  11811. childBlock = slotOutlet.codegenNode;
  11812. if (isTemplate && keyProperty) {
  11813. // <template v-for="..." :key="..."><slot/></template>
  11814. // we need to inject the key to the renderSlot() call.
  11815. // the props for renderSlot is passed as the 3rd argument.
  11816. injectProp(childBlock, keyProperty, context);
  11817. }
  11818. }
  11819. else if (needFragmentWrapper) {
  11820. // <template v-for="..."> with text or multi-elements
  11821. // should generate a fragment block for each loop
  11822. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
  11823. (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
  11824. ), undefined, undefined, true);
  11825. }
  11826. else {
  11827. // Normal element v-for. Directly use the child's codegenNode
  11828. // but mark it as a block.
  11829. childBlock = children[0]
  11830. .codegenNode;
  11831. if (isTemplate && keyProperty) {
  11832. injectProp(childBlock, keyProperty, context);
  11833. }
  11834. childBlock.isBlock = !isStableFragment;
  11835. if (childBlock.isBlock) {
  11836. helper(OPEN_BLOCK);
  11837. helper(CREATE_BLOCK);
  11838. }
  11839. else {
  11840. helper(CREATE_VNODE);
  11841. }
  11842. }
  11843. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  11844. };
  11845. });
  11846. });
  11847. // target-agnostic transform used for both Client and SSR
  11848. function processFor(node, dir, context, processCodegen) {
  11849. if (!dir.exp) {
  11850. context.onError(createCompilerError(30 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
  11851. return;
  11852. }
  11853. const parseResult = parseForExpression(
  11854. // can only be simple expression because vFor transform is applied
  11855. // before expression transform.
  11856. dir.exp, context);
  11857. if (!parseResult) {
  11858. context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  11859. return;
  11860. }
  11861. const { addIdentifiers, removeIdentifiers, scopes } = context;
  11862. const { source, value, key, index } = parseResult;
  11863. const forNode = {
  11864. type: 11 /* FOR */,
  11865. loc: dir.loc,
  11866. source,
  11867. valueAlias: value,
  11868. keyAlias: key,
  11869. objectIndexAlias: index,
  11870. parseResult,
  11871. children: isTemplateNode(node) ? node.children : [node]
  11872. };
  11873. context.replaceNode(forNode);
  11874. // bookkeeping
  11875. scopes.vFor++;
  11876. const onExit = processCodegen && processCodegen(forNode);
  11877. return () => {
  11878. scopes.vFor--;
  11879. if (onExit)
  11880. onExit();
  11881. };
  11882. }
  11883. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  11884. // This regex doesn't cover the case if key or index aliases have destructuring,
  11885. // but those do not make sense in the first place, so this works in practice.
  11886. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  11887. const stripParensRE = /^\(|\)$/g;
  11888. function parseForExpression(input, context) {
  11889. const loc = input.loc;
  11890. const exp = input.content;
  11891. const inMatch = exp.match(forAliasRE);
  11892. if (!inMatch)
  11893. return;
  11894. const [, LHS, RHS] = inMatch;
  11895. const result = {
  11896. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  11897. value: undefined,
  11898. key: undefined,
  11899. index: undefined
  11900. };
  11901. {
  11902. validateBrowserExpression(result.source, context);
  11903. }
  11904. let valueContent = LHS.trim()
  11905. .replace(stripParensRE, '')
  11906. .trim();
  11907. const trimmedOffset = LHS.indexOf(valueContent);
  11908. const iteratorMatch = valueContent.match(forIteratorRE);
  11909. if (iteratorMatch) {
  11910. valueContent = valueContent.replace(forIteratorRE, '').trim();
  11911. const keyContent = iteratorMatch[1].trim();
  11912. let keyOffset;
  11913. if (keyContent) {
  11914. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  11915. result.key = createAliasExpression(loc, keyContent, keyOffset);
  11916. {
  11917. validateBrowserExpression(result.key, context, true);
  11918. }
  11919. }
  11920. if (iteratorMatch[2]) {
  11921. const indexContent = iteratorMatch[2].trim();
  11922. if (indexContent) {
  11923. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  11924. ? keyOffset + keyContent.length
  11925. : trimmedOffset + valueContent.length));
  11926. {
  11927. validateBrowserExpression(result.index, context, true);
  11928. }
  11929. }
  11930. }
  11931. }
  11932. if (valueContent) {
  11933. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  11934. {
  11935. validateBrowserExpression(result.value, context, true);
  11936. }
  11937. }
  11938. return result;
  11939. }
  11940. function createAliasExpression(range, content, offset) {
  11941. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  11942. }
  11943. function createForLoopParams({ value, key, index }) {
  11944. const params = [];
  11945. if (value) {
  11946. params.push(value);
  11947. }
  11948. if (key) {
  11949. if (!value) {
  11950. params.push(createSimpleExpression(`_`, false));
  11951. }
  11952. params.push(key);
  11953. }
  11954. if (index) {
  11955. if (!key) {
  11956. if (!value) {
  11957. params.push(createSimpleExpression(`_`, false));
  11958. }
  11959. params.push(createSimpleExpression(`__`, false));
  11960. }
  11961. params.push(index);
  11962. }
  11963. return params;
  11964. }
  11965. const defaultFallback = createSimpleExpression(`undefined`, false);
  11966. // A NodeTransform that:
  11967. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  11968. // by transformExpression. This is only applied in non-browser builds with
  11969. // { prefixIdentifiers: true }.
  11970. // 2. Track v-slot depths so that we know a slot is inside another slot.
  11971. // Note the exit callback is executed before buildSlots() on the same node,
  11972. // so only nested slots see positive numbers.
  11973. const trackSlotScopes = (node, context) => {
  11974. if (node.type === 1 /* ELEMENT */ &&
  11975. (node.tagType === 1 /* COMPONENT */ ||
  11976. node.tagType === 3 /* TEMPLATE */)) {
  11977. // We are only checking non-empty v-slot here
  11978. // since we only care about slots that introduce scope variables.
  11979. const vSlot = findDir(node, 'slot');
  11980. if (vSlot) {
  11981. vSlot.exp;
  11982. context.scopes.vSlot++;
  11983. return () => {
  11984. context.scopes.vSlot--;
  11985. };
  11986. }
  11987. }
  11988. };
  11989. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  11990. // Instead of being a DirectiveTransform, v-slot processing is called during
  11991. // transformElement to build the slots object for a component.
  11992. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  11993. context.helper(WITH_CTX);
  11994. const { children, loc } = node;
  11995. const slotsProperties = [];
  11996. const dynamicSlots = [];
  11997. const buildDefaultSlotProperty = (props, children) => createObjectProperty(`default`, buildSlotFn(props, children, loc));
  11998. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  11999. // since it likely uses a scope variable.
  12000. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  12001. // 1. Check for slot with slotProps on component itself.
  12002. // <Comp v-slot="{ prop }"/>
  12003. const onComponentSlot = findDir(node, 'slot', true);
  12004. if (onComponentSlot) {
  12005. const { arg, exp } = onComponentSlot;
  12006. if (arg && !isStaticExp(arg)) {
  12007. hasDynamicSlots = true;
  12008. }
  12009. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  12010. }
  12011. // 2. Iterate through children and check for template slots
  12012. // <template v-slot:foo="{ prop }">
  12013. let hasTemplateSlots = false;
  12014. let hasNamedDefaultSlot = false;
  12015. const implicitDefaultChildren = [];
  12016. const seenSlotNames = new Set();
  12017. for (let i = 0; i < children.length; i++) {
  12018. const slotElement = children[i];
  12019. let slotDir;
  12020. if (!isTemplateNode(slotElement) ||
  12021. !(slotDir = findDir(slotElement, 'slot', true))) {
  12022. // not a <template v-slot>, skip.
  12023. if (slotElement.type !== 3 /* COMMENT */) {
  12024. implicitDefaultChildren.push(slotElement);
  12025. }
  12026. continue;
  12027. }
  12028. if (onComponentSlot) {
  12029. // already has on-component slot - this is incorrect usage.
  12030. context.onError(createCompilerError(36 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  12031. break;
  12032. }
  12033. hasTemplateSlots = true;
  12034. const { children: slotChildren, loc: slotLoc } = slotElement;
  12035. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  12036. // check if name is dynamic.
  12037. let staticSlotName;
  12038. if (isStaticExp(slotName)) {
  12039. staticSlotName = slotName ? slotName.content : `default`;
  12040. }
  12041. else {
  12042. hasDynamicSlots = true;
  12043. }
  12044. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  12045. // check if this slot is conditional (v-if/v-for)
  12046. let vIf;
  12047. let vElse;
  12048. let vFor;
  12049. if ((vIf = findDir(slotElement, 'if'))) {
  12050. hasDynamicSlots = true;
  12051. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
  12052. }
  12053. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  12054. // find adjacent v-if
  12055. let j = i;
  12056. let prev;
  12057. while (j--) {
  12058. prev = children[j];
  12059. if (prev.type !== 3 /* COMMENT */) {
  12060. break;
  12061. }
  12062. }
  12063. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  12064. // remove node
  12065. children.splice(i, 1);
  12066. i--;
  12067. // attach this slot to previous conditional
  12068. let conditional = dynamicSlots[dynamicSlots.length - 1];
  12069. while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  12070. conditional = conditional.alternate;
  12071. }
  12072. conditional.alternate = vElse.exp
  12073. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
  12074. : buildDynamicSlot(slotName, slotFunction);
  12075. }
  12076. else {
  12077. context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  12078. }
  12079. }
  12080. else if ((vFor = findDir(slotElement, 'for'))) {
  12081. hasDynamicSlots = true;
  12082. const parseResult = vFor.parseResult ||
  12083. parseForExpression(vFor.exp, context);
  12084. if (parseResult) {
  12085. // Render the dynamic slots as an array and add it to the createSlot()
  12086. // args. The runtime knows how to handle it appropriately.
  12087. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  12088. parseResult.source,
  12089. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  12090. ]));
  12091. }
  12092. else {
  12093. context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  12094. }
  12095. }
  12096. else {
  12097. // check duplicate static names
  12098. if (staticSlotName) {
  12099. if (seenSlotNames.has(staticSlotName)) {
  12100. context.onError(createCompilerError(37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  12101. continue;
  12102. }
  12103. seenSlotNames.add(staticSlotName);
  12104. if (staticSlotName === 'default') {
  12105. hasNamedDefaultSlot = true;
  12106. }
  12107. }
  12108. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  12109. }
  12110. }
  12111. if (!onComponentSlot) {
  12112. if (!hasTemplateSlots) {
  12113. // implicit default slot (on component)
  12114. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  12115. }
  12116. else if (implicitDefaultChildren.length) {
  12117. // implicit default slot (mixed with named slots)
  12118. if (hasNamedDefaultSlot) {
  12119. context.onError(createCompilerError(38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  12120. }
  12121. else {
  12122. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  12123. }
  12124. }
  12125. }
  12126. const slotFlag = hasDynamicSlots
  12127. ? 2 /* DYNAMIC */
  12128. : hasForwardedSlots(node.children)
  12129. ? 3 /* FORWARDED */
  12130. : 1 /* STABLE */;
  12131. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  12132. // 2 = compiled but dynamic = can skip normalization, but must run diff
  12133. // 1 = compiled and static = can skip normalization AND diff as optimized
  12134. createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
  12135. if (dynamicSlots.length) {
  12136. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  12137. slots,
  12138. createArrayExpression(dynamicSlots)
  12139. ]);
  12140. }
  12141. return {
  12142. slots,
  12143. hasDynamicSlots
  12144. };
  12145. }
  12146. function buildDynamicSlot(name, fn) {
  12147. return createObjectExpression([
  12148. createObjectProperty(`name`, name),
  12149. createObjectProperty(`fn`, fn)
  12150. ]);
  12151. }
  12152. function hasForwardedSlots(children) {
  12153. for (let i = 0; i < children.length; i++) {
  12154. const child = children[i];
  12155. if (child.type === 1 /* ELEMENT */) {
  12156. if (child.tagType === 2 /* SLOT */ ||
  12157. (child.tagType === 0 /* ELEMENT */ &&
  12158. hasForwardedSlots(child.children))) {
  12159. return true;
  12160. }
  12161. }
  12162. }
  12163. return false;
  12164. }
  12165. // some directive transforms (e.g. v-model) may return a symbol for runtime
  12166. // import, which should be used instead of a resolveDirective call.
  12167. const directiveImportMap = new WeakMap();
  12168. // generate a JavaScript AST for this element's codegen
  12169. const transformElement = (node, context) => {
  12170. if (!(node.type === 1 /* ELEMENT */ &&
  12171. (node.tagType === 0 /* ELEMENT */ ||
  12172. node.tagType === 1 /* COMPONENT */))) {
  12173. return;
  12174. }
  12175. // perform the work on exit, after all child expressions have been
  12176. // processed and merged.
  12177. return function postTransformElement() {
  12178. const { tag, props } = node;
  12179. const isComponent = node.tagType === 1 /* COMPONENT */;
  12180. // The goal of the transform is to create a codegenNode implementing the
  12181. // VNodeCall interface.
  12182. const vnodeTag = isComponent
  12183. ? resolveComponentType(node, context)
  12184. : `"${tag}"`;
  12185. const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  12186. let vnodeProps;
  12187. let vnodeChildren;
  12188. let vnodePatchFlag;
  12189. let patchFlag = 0;
  12190. let vnodeDynamicProps;
  12191. let dynamicPropNames;
  12192. let vnodeDirectives;
  12193. let shouldUseBlock =
  12194. // dynamic component may resolve to plain elements
  12195. isDynamicComponent ||
  12196. vnodeTag === TELEPORT ||
  12197. vnodeTag === SUSPENSE ||
  12198. (!isComponent &&
  12199. // <svg> and <foreignObject> must be forced into blocks so that block
  12200. // updates inside get proper isSVG flag at runtime. (#639, #643)
  12201. // This is technically web-specific, but splitting the logic out of core
  12202. // leads to too much unnecessary complexity.
  12203. (tag === 'svg' ||
  12204. tag === 'foreignObject' ||
  12205. // #938: elements with dynamic keys should be forced into blocks
  12206. findProp(node, 'key', true)));
  12207. // props
  12208. if (props.length > 0) {
  12209. const propsBuildResult = buildProps(node, context);
  12210. vnodeProps = propsBuildResult.props;
  12211. patchFlag = propsBuildResult.patchFlag;
  12212. dynamicPropNames = propsBuildResult.dynamicPropNames;
  12213. const directives = propsBuildResult.directives;
  12214. vnodeDirectives =
  12215. directives && directives.length
  12216. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  12217. : undefined;
  12218. }
  12219. // children
  12220. if (node.children.length > 0) {
  12221. if (vnodeTag === KEEP_ALIVE) {
  12222. // Although a built-in component, we compile KeepAlive with raw children
  12223. // instead of slot functions so that it can be used inside Transition
  12224. // or other Transition-wrapping HOCs.
  12225. // To ensure correct updates with block optimizations, we need to:
  12226. // 1. Force keep-alive into a block. This avoids its children being
  12227. // collected by a parent block.
  12228. shouldUseBlock = true;
  12229. // 2. Force keep-alive to always be updated, since it uses raw children.
  12230. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  12231. if (node.children.length > 1) {
  12232. context.onError(createCompilerError(44 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
  12233. start: node.children[0].loc.start,
  12234. end: node.children[node.children.length - 1].loc.end,
  12235. source: ''
  12236. }));
  12237. }
  12238. }
  12239. const shouldBuildAsSlots = isComponent &&
  12240. // Teleport is not a real component and has dedicated runtime handling
  12241. vnodeTag !== TELEPORT &&
  12242. // explained above.
  12243. vnodeTag !== KEEP_ALIVE;
  12244. if (shouldBuildAsSlots) {
  12245. const { slots, hasDynamicSlots } = buildSlots(node, context);
  12246. vnodeChildren = slots;
  12247. if (hasDynamicSlots) {
  12248. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  12249. }
  12250. }
  12251. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  12252. const child = node.children[0];
  12253. const type = child.type;
  12254. // check for dynamic text children
  12255. const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
  12256. type === 8 /* COMPOUND_EXPRESSION */;
  12257. if (hasDynamicTextChild &&
  12258. getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
  12259. patchFlag |= 1 /* TEXT */;
  12260. }
  12261. // pass directly if the only child is a text node
  12262. // (plain / interpolation / expression)
  12263. if (hasDynamicTextChild || type === 2 /* TEXT */) {
  12264. vnodeChildren = child;
  12265. }
  12266. else {
  12267. vnodeChildren = node.children;
  12268. }
  12269. }
  12270. else {
  12271. vnodeChildren = node.children;
  12272. }
  12273. }
  12274. // patchFlag & dynamicPropNames
  12275. if (patchFlag !== 0) {
  12276. {
  12277. if (patchFlag < 0) {
  12278. // special flags (negative and mutually exclusive)
  12279. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  12280. }
  12281. else {
  12282. // bitwise flags
  12283. const flagNames = Object.keys(PatchFlagNames)
  12284. .map(Number)
  12285. .filter(n => n > 0 && patchFlag & n)
  12286. .map(n => PatchFlagNames[n])
  12287. .join(`, `);
  12288. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  12289. }
  12290. }
  12291. if (dynamicPropNames && dynamicPropNames.length) {
  12292. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  12293. }
  12294. }
  12295. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, node.loc);
  12296. };
  12297. };
  12298. function resolveComponentType(node, context, ssr = false) {
  12299. const { tag } = node;
  12300. // 1. dynamic component
  12301. const isProp = node.tag === 'component' ? findProp(node, 'is') : findDir(node, 'is');
  12302. if (isProp) {
  12303. const exp = isProp.type === 6 /* ATTRIBUTE */
  12304. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  12305. : isProp.exp;
  12306. if (exp) {
  12307. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  12308. exp
  12309. ]);
  12310. }
  12311. }
  12312. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  12313. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  12314. if (builtIn) {
  12315. // built-ins are simply fallthroughs / have special handling during ssr
  12316. // so we don't need to import their runtime equivalents
  12317. if (!ssr)
  12318. context.helper(builtIn);
  12319. return builtIn;
  12320. }
  12321. // 5. user component (resolve)
  12322. context.helper(RESOLVE_COMPONENT);
  12323. context.components.add(tag);
  12324. return toValidAssetId(tag, `component`);
  12325. }
  12326. function buildProps(node, context, props = node.props, ssr = false) {
  12327. const { tag, loc: elementLoc } = node;
  12328. const isComponent = node.tagType === 1 /* COMPONENT */;
  12329. let properties = [];
  12330. const mergeArgs = [];
  12331. const runtimeDirectives = [];
  12332. // patchFlag analysis
  12333. let patchFlag = 0;
  12334. let hasRef = false;
  12335. let hasClassBinding = false;
  12336. let hasStyleBinding = false;
  12337. let hasHydrationEventBinding = false;
  12338. let hasDynamicKeys = false;
  12339. let hasVnodeHook = false;
  12340. const dynamicPropNames = [];
  12341. const analyzePatchFlag = ({ key, value }) => {
  12342. if (isStaticExp(key)) {
  12343. const name = key.content;
  12344. const isEventHandler = isOn(name);
  12345. if (!isComponent &&
  12346. isEventHandler &&
  12347. // omit the flag for click handlers because hydration gives click
  12348. // dedicated fast path.
  12349. name.toLowerCase() !== 'onclick' &&
  12350. // omit v-model handlers
  12351. name !== 'onUpdate:modelValue' &&
  12352. // omit onVnodeXXX hooks
  12353. !isReservedProp(name)) {
  12354. hasHydrationEventBinding = true;
  12355. }
  12356. if (isEventHandler && isReservedProp(name)) {
  12357. hasVnodeHook = true;
  12358. }
  12359. if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
  12360. ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
  12361. value.type === 8 /* COMPOUND_EXPRESSION */) &&
  12362. getConstantType(value, context) > 0)) {
  12363. // skip if the prop is a cached handler or has constant value
  12364. return;
  12365. }
  12366. if (name === 'ref') {
  12367. hasRef = true;
  12368. }
  12369. else if (name === 'class' && !isComponent) {
  12370. hasClassBinding = true;
  12371. }
  12372. else if (name === 'style' && !isComponent) {
  12373. hasStyleBinding = true;
  12374. }
  12375. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  12376. dynamicPropNames.push(name);
  12377. }
  12378. }
  12379. else {
  12380. hasDynamicKeys = true;
  12381. }
  12382. };
  12383. for (let i = 0; i < props.length; i++) {
  12384. // static attribute
  12385. const prop = props[i];
  12386. if (prop.type === 6 /* ATTRIBUTE */) {
  12387. const { loc, name, value } = prop;
  12388. let isStatic = true;
  12389. if (name === 'ref') {
  12390. hasRef = true;
  12391. }
  12392. // skip :is on <component>
  12393. if (name === 'is' && tag === 'component') {
  12394. continue;
  12395. }
  12396. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
  12397. }
  12398. else {
  12399. // directives
  12400. const { name, arg, exp, loc } = prop;
  12401. const isBind = name === 'bind';
  12402. const isOn = name === 'on';
  12403. // skip v-slot - it is handled by its dedicated transform.
  12404. if (name === 'slot') {
  12405. if (!isComponent) {
  12406. context.onError(createCompilerError(39 /* X_V_SLOT_MISPLACED */, loc));
  12407. }
  12408. continue;
  12409. }
  12410. // skip v-once - it is handled by its dedicated transform.
  12411. if (name === 'once') {
  12412. continue;
  12413. }
  12414. // skip v-is and :is on <component>
  12415. if (name === 'is' ||
  12416. (isBind && tag === 'component' && isBindKey(arg, 'is'))) {
  12417. continue;
  12418. }
  12419. // skip v-on in SSR compilation
  12420. if (isOn && ssr) {
  12421. continue;
  12422. }
  12423. // special case for v-bind and v-on with no argument
  12424. if (!arg && (isBind || isOn)) {
  12425. hasDynamicKeys = true;
  12426. if (exp) {
  12427. if (properties.length) {
  12428. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  12429. properties = [];
  12430. }
  12431. if (isBind) {
  12432. mergeArgs.push(exp);
  12433. }
  12434. else {
  12435. // v-on="obj" -> toHandlers(obj)
  12436. mergeArgs.push({
  12437. type: 14 /* JS_CALL_EXPRESSION */,
  12438. loc,
  12439. callee: context.helper(TO_HANDLERS),
  12440. arguments: [exp]
  12441. });
  12442. }
  12443. }
  12444. else {
  12445. context.onError(createCompilerError(isBind
  12446. ? 33 /* X_V_BIND_NO_EXPRESSION */
  12447. : 34 /* X_V_ON_NO_EXPRESSION */, loc));
  12448. }
  12449. continue;
  12450. }
  12451. const directiveTransform = context.directiveTransforms[name];
  12452. if (directiveTransform) {
  12453. // has built-in directive transform.
  12454. const { props, needRuntime } = directiveTransform(prop, node, context);
  12455. !ssr && props.forEach(analyzePatchFlag);
  12456. properties.push(...props);
  12457. if (needRuntime) {
  12458. runtimeDirectives.push(prop);
  12459. if (isSymbol(needRuntime)) {
  12460. directiveImportMap.set(prop, needRuntime);
  12461. }
  12462. }
  12463. }
  12464. else {
  12465. // no built-in transform, this is a user custom directive.
  12466. runtimeDirectives.push(prop);
  12467. }
  12468. }
  12469. }
  12470. let propsExpression = undefined;
  12471. // has v-bind="object" or v-on="object", wrap with mergeProps
  12472. if (mergeArgs.length) {
  12473. if (properties.length) {
  12474. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  12475. }
  12476. if (mergeArgs.length > 1) {
  12477. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  12478. }
  12479. else {
  12480. // single v-bind with nothing else - no need for a mergeProps call
  12481. propsExpression = mergeArgs[0];
  12482. }
  12483. }
  12484. else if (properties.length) {
  12485. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  12486. }
  12487. // patchFlag analysis
  12488. if (hasDynamicKeys) {
  12489. patchFlag |= 16 /* FULL_PROPS */;
  12490. }
  12491. else {
  12492. if (hasClassBinding) {
  12493. patchFlag |= 2 /* CLASS */;
  12494. }
  12495. if (hasStyleBinding) {
  12496. patchFlag |= 4 /* STYLE */;
  12497. }
  12498. if (dynamicPropNames.length) {
  12499. patchFlag |= 8 /* PROPS */;
  12500. }
  12501. if (hasHydrationEventBinding) {
  12502. patchFlag |= 32 /* HYDRATE_EVENTS */;
  12503. }
  12504. }
  12505. if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
  12506. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  12507. patchFlag |= 512 /* NEED_PATCH */;
  12508. }
  12509. return {
  12510. props: propsExpression,
  12511. directives: runtimeDirectives,
  12512. patchFlag,
  12513. dynamicPropNames
  12514. };
  12515. }
  12516. // Dedupe props in an object literal.
  12517. // Literal duplicated attributes would have been warned during the parse phase,
  12518. // however, it's possible to encounter duplicated `onXXX` handlers with different
  12519. // modifiers. We also need to merge static and dynamic class / style attributes.
  12520. // - onXXX handlers / style: merge into array
  12521. // - class: merge into single expression with concatenation
  12522. function dedupeProperties(properties) {
  12523. const knownProps = new Map();
  12524. const deduped = [];
  12525. for (let i = 0; i < properties.length; i++) {
  12526. const prop = properties[i];
  12527. // dynamic keys are always allowed
  12528. if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  12529. deduped.push(prop);
  12530. continue;
  12531. }
  12532. const name = prop.key.content;
  12533. const existing = knownProps.get(name);
  12534. if (existing) {
  12535. if (name === 'style' || name === 'class' || name.startsWith('on')) {
  12536. mergeAsArray(existing, prop);
  12537. }
  12538. // unexpected duplicate, should have emitted error during parse
  12539. }
  12540. else {
  12541. knownProps.set(name, prop);
  12542. deduped.push(prop);
  12543. }
  12544. }
  12545. return deduped;
  12546. }
  12547. function mergeAsArray(existing, incoming) {
  12548. if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
  12549. existing.value.elements.push(incoming.value);
  12550. }
  12551. else {
  12552. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  12553. }
  12554. }
  12555. function buildDirectiveArgs(dir, context) {
  12556. const dirArgs = [];
  12557. const runtime = directiveImportMap.get(dir);
  12558. if (runtime) {
  12559. // built-in directive with runtime
  12560. dirArgs.push(context.helperString(runtime));
  12561. }
  12562. else {
  12563. {
  12564. // inject statement for resolving directive
  12565. context.helper(RESOLVE_DIRECTIVE);
  12566. context.directives.add(dir.name);
  12567. dirArgs.push(toValidAssetId(dir.name, `directive`));
  12568. }
  12569. }
  12570. const { loc } = dir;
  12571. if (dir.exp)
  12572. dirArgs.push(dir.exp);
  12573. if (dir.arg) {
  12574. if (!dir.exp) {
  12575. dirArgs.push(`void 0`);
  12576. }
  12577. dirArgs.push(dir.arg);
  12578. }
  12579. if (Object.keys(dir.modifiers).length) {
  12580. if (!dir.arg) {
  12581. if (!dir.exp) {
  12582. dirArgs.push(`void 0`);
  12583. }
  12584. dirArgs.push(`void 0`);
  12585. }
  12586. const trueExpression = createSimpleExpression(`true`, false, loc);
  12587. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  12588. }
  12589. return createArrayExpression(dirArgs, dir.loc);
  12590. }
  12591. function stringifyDynamicPropNames(props) {
  12592. let propsNamesString = `[`;
  12593. for (let i = 0, l = props.length; i < l; i++) {
  12594. propsNamesString += JSON.stringify(props[i]);
  12595. if (i < l - 1)
  12596. propsNamesString += ', ';
  12597. }
  12598. return propsNamesString + `]`;
  12599. }
  12600. const transformSlotOutlet = (node, context) => {
  12601. if (isSlotOutlet(node)) {
  12602. const { children, loc } = node;
  12603. const { slotName, slotProps } = processSlotOutlet(node, context);
  12604. const slotArgs = [
  12605. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  12606. slotName
  12607. ];
  12608. if (slotProps) {
  12609. slotArgs.push(slotProps);
  12610. }
  12611. if (children.length) {
  12612. if (!slotProps) {
  12613. slotArgs.push(`{}`);
  12614. }
  12615. slotArgs.push(createFunctionExpression([], children, false, false, loc));
  12616. }
  12617. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  12618. }
  12619. };
  12620. function processSlotOutlet(node, context) {
  12621. let slotName = `"default"`;
  12622. let slotProps = undefined;
  12623. const nonNameProps = [];
  12624. for (let i = 0; i < node.props.length; i++) {
  12625. const p = node.props[i];
  12626. if (p.type === 6 /* ATTRIBUTE */) {
  12627. if (p.value) {
  12628. if (p.name === 'name') {
  12629. slotName = JSON.stringify(p.value.content);
  12630. }
  12631. else {
  12632. p.name = camelize(p.name);
  12633. nonNameProps.push(p);
  12634. }
  12635. }
  12636. }
  12637. else {
  12638. if (p.name === 'bind' && isBindKey(p.arg, 'name')) {
  12639. if (p.exp)
  12640. slotName = p.exp;
  12641. }
  12642. else {
  12643. if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
  12644. p.arg.content = camelize(p.arg.content);
  12645. }
  12646. nonNameProps.push(p);
  12647. }
  12648. }
  12649. }
  12650. if (nonNameProps.length > 0) {
  12651. const { props, directives } = buildProps(node, context, nonNameProps);
  12652. slotProps = props;
  12653. if (directives.length) {
  12654. context.onError(createCompilerError(35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  12655. }
  12656. }
  12657. return {
  12658. slotName,
  12659. slotProps
  12660. };
  12661. }
  12662. const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/;
  12663. const transformOn = (dir, node, context, augmentor) => {
  12664. const { loc, modifiers, arg } = dir;
  12665. if (!dir.exp && !modifiers.length) {
  12666. context.onError(createCompilerError(34 /* X_V_ON_NO_EXPRESSION */, loc));
  12667. }
  12668. let eventName;
  12669. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  12670. if (arg.isStatic) {
  12671. const rawName = arg.content;
  12672. // for all event listeners, auto convert it to camelCase. See issue #2249
  12673. eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
  12674. }
  12675. else {
  12676. // #2388
  12677. eventName = createCompoundExpression([
  12678. `${context.helperString(TO_HANDLER_KEY)}(`,
  12679. arg,
  12680. `)`
  12681. ]);
  12682. }
  12683. }
  12684. else {
  12685. // already a compound expression.
  12686. eventName = arg;
  12687. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  12688. eventName.children.push(`)`);
  12689. }
  12690. // handler processing
  12691. let exp = dir.exp;
  12692. if (exp && !exp.content.trim()) {
  12693. exp = undefined;
  12694. }
  12695. let shouldCache = context.cacheHandlers && !exp;
  12696. if (exp) {
  12697. const isMemberExp = isMemberExpression(exp.content);
  12698. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  12699. const hasMultipleStatements = exp.content.includes(`;`);
  12700. {
  12701. validateBrowserExpression(exp, context, false, hasMultipleStatements);
  12702. }
  12703. if (isInlineStatement || (shouldCache && isMemberExp)) {
  12704. // wrap inline statement in a function expression
  12705. exp = createCompoundExpression([
  12706. `${isInlineStatement
  12707. ? `$event`
  12708. : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  12709. exp,
  12710. hasMultipleStatements ? `}` : `)`
  12711. ]);
  12712. }
  12713. }
  12714. let ret = {
  12715. props: [
  12716. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  12717. ]
  12718. };
  12719. // apply extended compiler augmentor
  12720. if (augmentor) {
  12721. ret = augmentor(ret);
  12722. }
  12723. if (shouldCache) {
  12724. // cache handlers so that it's always the same handler being passed down.
  12725. // this avoids unnecessary re-renders when users use inline handlers on
  12726. // components.
  12727. ret.props[0].value = context.cache(ret.props[0].value);
  12728. }
  12729. return ret;
  12730. };
  12731. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  12732. // codegen for the entire props object. This transform here is only for v-bind
  12733. // *with* args.
  12734. const transformBind = (dir, node, context) => {
  12735. const { exp, modifiers, loc } = dir;
  12736. const arg = dir.arg;
  12737. if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
  12738. arg.children.unshift(`(`);
  12739. arg.children.push(`) || ""`);
  12740. }
  12741. else if (!arg.isStatic) {
  12742. arg.content = `${arg.content} || ""`;
  12743. }
  12744. // .prop is no longer necessary due to new patch behavior
  12745. // .sync is replaced by v-model:arg
  12746. if (modifiers.includes('camel')) {
  12747. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  12748. if (arg.isStatic) {
  12749. arg.content = camelize(arg.content);
  12750. }
  12751. else {
  12752. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  12753. }
  12754. }
  12755. else {
  12756. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  12757. arg.children.push(`)`);
  12758. }
  12759. }
  12760. if (!exp ||
  12761. (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  12762. context.onError(createCompilerError(33 /* X_V_BIND_NO_EXPRESSION */, loc));
  12763. return {
  12764. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  12765. };
  12766. }
  12767. return {
  12768. props: [createObjectProperty(arg, exp)]
  12769. };
  12770. };
  12771. // Merge adjacent text nodes and expressions into a single expression
  12772. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  12773. const transformText = (node, context) => {
  12774. if (node.type === 0 /* ROOT */ ||
  12775. node.type === 1 /* ELEMENT */ ||
  12776. node.type === 11 /* FOR */ ||
  12777. node.type === 10 /* IF_BRANCH */) {
  12778. // perform the transform on node exit so that all expressions have already
  12779. // been processed.
  12780. return () => {
  12781. const children = node.children;
  12782. let currentContainer = undefined;
  12783. let hasText = false;
  12784. for (let i = 0; i < children.length; i++) {
  12785. const child = children[i];
  12786. if (isText(child)) {
  12787. hasText = true;
  12788. for (let j = i + 1; j < children.length; j++) {
  12789. const next = children[j];
  12790. if (isText(next)) {
  12791. if (!currentContainer) {
  12792. currentContainer = children[i] = {
  12793. type: 8 /* COMPOUND_EXPRESSION */,
  12794. loc: child.loc,
  12795. children: [child]
  12796. };
  12797. }
  12798. // merge adjacent text node into current
  12799. currentContainer.children.push(` + `, next);
  12800. children.splice(j, 1);
  12801. j--;
  12802. }
  12803. else {
  12804. currentContainer = undefined;
  12805. break;
  12806. }
  12807. }
  12808. }
  12809. }
  12810. if (!hasText ||
  12811. // if this is a plain element with a single text child, leave it
  12812. // as-is since the runtime has dedicated fast path for this by directly
  12813. // setting textContent of the element.
  12814. // for component root it's always normalized anyway.
  12815. (children.length === 1 &&
  12816. (node.type === 0 /* ROOT */ ||
  12817. (node.type === 1 /* ELEMENT */ &&
  12818. node.tagType === 0 /* ELEMENT */)))) {
  12819. return;
  12820. }
  12821. // pre-convert text nodes into createTextVNode(text) calls to avoid
  12822. // runtime normalization.
  12823. for (let i = 0; i < children.length; i++) {
  12824. const child = children[i];
  12825. if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
  12826. const callArgs = [];
  12827. // createTextVNode defaults to single whitespace, so if it is a
  12828. // single space the code could be an empty call to save bytes.
  12829. if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
  12830. callArgs.push(child);
  12831. }
  12832. // mark dynamic text with flag so it gets patched inside a block
  12833. if (!context.ssr &&
  12834. getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
  12835. callArgs.push(1 /* TEXT */ +
  12836. (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
  12837. }
  12838. children[i] = {
  12839. type: 12 /* TEXT_CALL */,
  12840. content: child,
  12841. loc: child.loc,
  12842. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  12843. };
  12844. }
  12845. }
  12846. };
  12847. }
  12848. };
  12849. const seen = new WeakSet();
  12850. const transformOnce = (node, context) => {
  12851. if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
  12852. if (seen.has(node)) {
  12853. return;
  12854. }
  12855. seen.add(node);
  12856. context.helper(SET_BLOCK_TRACKING);
  12857. return () => {
  12858. const cur = context.currentNode;
  12859. if (cur.codegenNode) {
  12860. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  12861. }
  12862. };
  12863. }
  12864. };
  12865. const transformModel = (dir, node, context) => {
  12866. const { exp, arg } = dir;
  12867. if (!exp) {
  12868. context.onError(createCompilerError(40 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
  12869. return createTransformProps();
  12870. }
  12871. const rawExp = exp.loc.source;
  12872. const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
  12873. // im SFC <script setup> inline mode, the exp may have been transformed into
  12874. // _unref(exp)
  12875. context.bindingMetadata[rawExp];
  12876. const maybeRef = !true /* SETUP_CONST */;
  12877. if (!isMemberExpression(expString) && !maybeRef) {
  12878. context.onError(createCompilerError(41 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  12879. return createTransformProps();
  12880. }
  12881. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  12882. const eventName = arg
  12883. ? isStaticExp(arg)
  12884. ? `onUpdate:${arg.content}`
  12885. : createCompoundExpression(['"onUpdate:" + ', arg])
  12886. : `onUpdate:modelValue`;
  12887. let assignmentExp;
  12888. const eventArg = context.isTS ? `($event: any)` : `$event`;
  12889. {
  12890. assignmentExp = createCompoundExpression([
  12891. `${eventArg} => (`,
  12892. exp,
  12893. ` = $event)`
  12894. ]);
  12895. }
  12896. const props = [
  12897. // modelValue: foo
  12898. createObjectProperty(propName, dir.exp),
  12899. // "onUpdate:modelValue": $event => (foo = $event)
  12900. createObjectProperty(eventName, assignmentExp)
  12901. ];
  12902. // modelModifiers: { foo: true, "bar-baz": true }
  12903. if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
  12904. const modifiers = dir.modifiers
  12905. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  12906. .join(`, `);
  12907. const modifiersKey = arg
  12908. ? isStaticExp(arg)
  12909. ? `${arg.content}Modifiers`
  12910. : createCompoundExpression([arg, ' + "Modifiers"'])
  12911. : `modelModifiers`;
  12912. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
  12913. }
  12914. return createTransformProps(props);
  12915. };
  12916. function createTransformProps(props = []) {
  12917. return { props };
  12918. }
  12919. function getBaseTransformPreset(prefixIdentifiers) {
  12920. return [
  12921. [
  12922. transformOnce,
  12923. transformIf,
  12924. transformFor,
  12925. ...([transformExpression]
  12926. ),
  12927. transformSlotOutlet,
  12928. transformElement,
  12929. trackSlotScopes,
  12930. transformText
  12931. ],
  12932. {
  12933. on: transformOn,
  12934. bind: transformBind,
  12935. model: transformModel
  12936. }
  12937. ];
  12938. }
  12939. // we name it `baseCompile` so that higher order compilers like
  12940. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  12941. function baseCompile(template, options = {}) {
  12942. const onError = options.onError || defaultOnError;
  12943. const isModuleMode = options.mode === 'module';
  12944. /* istanbul ignore if */
  12945. {
  12946. if (options.prefixIdentifiers === true) {
  12947. onError(createCompilerError(45 /* X_PREFIX_ID_NOT_SUPPORTED */));
  12948. }
  12949. else if (isModuleMode) {
  12950. onError(createCompilerError(46 /* X_MODULE_MODE_NOT_SUPPORTED */));
  12951. }
  12952. }
  12953. const prefixIdentifiers = !true ;
  12954. if (options.cacheHandlers) {
  12955. onError(createCompilerError(47 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
  12956. }
  12957. if (options.scopeId && !isModuleMode) {
  12958. onError(createCompilerError(48 /* X_SCOPE_ID_NOT_SUPPORTED */));
  12959. }
  12960. const ast = isString(template) ? baseParse(template, options) : template;
  12961. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
  12962. transform(ast, extend({}, options, {
  12963. prefixIdentifiers,
  12964. nodeTransforms: [
  12965. ...nodeTransforms,
  12966. ...(options.nodeTransforms || []) // user transforms
  12967. ],
  12968. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  12969. )
  12970. }));
  12971. return generate(ast, extend({}, options, {
  12972. prefixIdentifiers
  12973. }));
  12974. }
  12975. const noopDirectiveTransform = () => ({ props: [] });
  12976. const V_MODEL_RADIO = Symbol(`vModelRadio` );
  12977. const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
  12978. const V_MODEL_TEXT = Symbol(`vModelText` );
  12979. const V_MODEL_SELECT = Symbol(`vModelSelect` );
  12980. const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
  12981. const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
  12982. const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
  12983. const V_SHOW = Symbol(`vShow` );
  12984. const TRANSITION$1 = Symbol(`Transition` );
  12985. const TRANSITION_GROUP = Symbol(`TransitionGroup` );
  12986. registerRuntimeHelpers({
  12987. [V_MODEL_RADIO]: `vModelRadio`,
  12988. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  12989. [V_MODEL_TEXT]: `vModelText`,
  12990. [V_MODEL_SELECT]: `vModelSelect`,
  12991. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  12992. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  12993. [V_ON_WITH_KEYS]: `withKeys`,
  12994. [V_SHOW]: `vShow`,
  12995. [TRANSITION$1]: `Transition`,
  12996. [TRANSITION_GROUP]: `TransitionGroup`
  12997. });
  12998. /* eslint-disable no-restricted-globals */
  12999. let decoder;
  13000. function decodeHtmlBrowser(raw) {
  13001. (decoder || (decoder = document.createElement('div'))).innerHTML = raw;
  13002. return decoder.textContent;
  13003. }
  13004. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  13005. const parserOptions = {
  13006. isVoidTag,
  13007. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  13008. isPreTag: tag => tag === 'pre',
  13009. decodeEntities: decodeHtmlBrowser ,
  13010. isBuiltInComponent: (tag) => {
  13011. if (isBuiltInType(tag, `Transition`)) {
  13012. return TRANSITION$1;
  13013. }
  13014. else if (isBuiltInType(tag, `TransitionGroup`)) {
  13015. return TRANSITION_GROUP;
  13016. }
  13017. },
  13018. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  13019. getNamespace(tag, parent) {
  13020. let ns = parent ? parent.ns : 0 /* HTML */;
  13021. if (parent && ns === 2 /* MATH_ML */) {
  13022. if (parent.tag === 'annotation-xml') {
  13023. if (tag === 'svg') {
  13024. return 1 /* SVG */;
  13025. }
  13026. if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
  13027. a.name === 'encoding' &&
  13028. a.value != null &&
  13029. (a.value.content === 'text/html' ||
  13030. a.value.content === 'application/xhtml+xml'))) {
  13031. ns = 0 /* HTML */;
  13032. }
  13033. }
  13034. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  13035. tag !== 'mglyph' &&
  13036. tag !== 'malignmark') {
  13037. ns = 0 /* HTML */;
  13038. }
  13039. }
  13040. else if (parent && ns === 1 /* SVG */) {
  13041. if (parent.tag === 'foreignObject' ||
  13042. parent.tag === 'desc' ||
  13043. parent.tag === 'title') {
  13044. ns = 0 /* HTML */;
  13045. }
  13046. }
  13047. if (ns === 0 /* HTML */) {
  13048. if (tag === 'svg') {
  13049. return 1 /* SVG */;
  13050. }
  13051. if (tag === 'math') {
  13052. return 2 /* MATH_ML */;
  13053. }
  13054. }
  13055. return ns;
  13056. },
  13057. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  13058. getTextMode({ tag, ns }) {
  13059. if (ns === 0 /* HTML */) {
  13060. if (tag === 'textarea' || tag === 'title') {
  13061. return 1 /* RCDATA */;
  13062. }
  13063. if (isRawTextContainer(tag)) {
  13064. return 2 /* RAWTEXT */;
  13065. }
  13066. }
  13067. return 0 /* DATA */;
  13068. }
  13069. };
  13070. // Parse inline CSS strings for static style attributes into an object.
  13071. // This is a NodeTransform since it works on the static `style` attribute and
  13072. // converts it into a dynamic equivalent:
  13073. // style="color: red" -> :style='{ "color": "red" }'
  13074. // It is then processed by `transformElement` and included in the generated
  13075. // props.
  13076. const transformStyle = node => {
  13077. if (node.type === 1 /* ELEMENT */) {
  13078. node.props.forEach((p, i) => {
  13079. if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
  13080. // replace p with an expression node
  13081. node.props[i] = {
  13082. type: 7 /* DIRECTIVE */,
  13083. name: `bind`,
  13084. arg: createSimpleExpression(`style`, true, p.loc),
  13085. exp: parseInlineCSS(p.value.content, p.loc),
  13086. modifiers: [],
  13087. loc: p.loc
  13088. };
  13089. }
  13090. });
  13091. }
  13092. };
  13093. const parseInlineCSS = (cssText, loc) => {
  13094. const normalized = parseStringStyle(cssText);
  13095. return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
  13096. };
  13097. function createDOMCompilerError(code, loc) {
  13098. return createCompilerError(code, loc, DOMErrorMessages );
  13099. }
  13100. const DOMErrorMessages = {
  13101. [49 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  13102. [50 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  13103. [51 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  13104. [52 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  13105. [53 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  13106. [54 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  13107. [55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
  13108. [56 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  13109. [57 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  13110. [58 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  13111. [59 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  13112. };
  13113. const transformVHtml = (dir, node, context) => {
  13114. const { exp, loc } = dir;
  13115. if (!exp) {
  13116. context.onError(createDOMCompilerError(49 /* X_V_HTML_NO_EXPRESSION */, loc));
  13117. }
  13118. if (node.children.length) {
  13119. context.onError(createDOMCompilerError(50 /* X_V_HTML_WITH_CHILDREN */, loc));
  13120. node.children.length = 0;
  13121. }
  13122. return {
  13123. props: [
  13124. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  13125. ]
  13126. };
  13127. };
  13128. const transformVText = (dir, node, context) => {
  13129. const { exp, loc } = dir;
  13130. if (!exp) {
  13131. context.onError(createDOMCompilerError(51 /* X_V_TEXT_NO_EXPRESSION */, loc));
  13132. }
  13133. if (node.children.length) {
  13134. context.onError(createDOMCompilerError(52 /* X_V_TEXT_WITH_CHILDREN */, loc));
  13135. node.children.length = 0;
  13136. }
  13137. return {
  13138. props: [
  13139. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  13140. ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  13141. : createSimpleExpression('', true))
  13142. ]
  13143. };
  13144. };
  13145. const transformModel$1 = (dir, node, context) => {
  13146. const baseResult = transformModel(dir, node, context);
  13147. // base transform has errors OR component v-model (only need props)
  13148. if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
  13149. return baseResult;
  13150. }
  13151. if (dir.arg) {
  13152. context.onError(createDOMCompilerError(54 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  13153. }
  13154. function checkDuplicatedValue() {
  13155. const value = findProp(node, 'value');
  13156. if (value) {
  13157. context.onError(createDOMCompilerError(56 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  13158. }
  13159. }
  13160. const { tag } = node;
  13161. const isCustomElement = context.isCustomElement(tag);
  13162. if (tag === 'input' ||
  13163. tag === 'textarea' ||
  13164. tag === 'select' ||
  13165. isCustomElement) {
  13166. let directiveToUse = V_MODEL_TEXT;
  13167. let isInvalidType = false;
  13168. if (tag === 'input' || isCustomElement) {
  13169. const type = findProp(node, `type`);
  13170. if (type) {
  13171. if (type.type === 7 /* DIRECTIVE */) {
  13172. // :type="foo"
  13173. directiveToUse = V_MODEL_DYNAMIC;
  13174. }
  13175. else if (type.value) {
  13176. switch (type.value.content) {
  13177. case 'radio':
  13178. directiveToUse = V_MODEL_RADIO;
  13179. break;
  13180. case 'checkbox':
  13181. directiveToUse = V_MODEL_CHECKBOX;
  13182. break;
  13183. case 'file':
  13184. isInvalidType = true;
  13185. context.onError(createDOMCompilerError(55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  13186. break;
  13187. default:
  13188. // text type
  13189. checkDuplicatedValue();
  13190. break;
  13191. }
  13192. }
  13193. }
  13194. else if (hasDynamicKeyVBind(node)) {
  13195. // element has bindings with dynamic keys, which can possibly contain
  13196. // "type".
  13197. directiveToUse = V_MODEL_DYNAMIC;
  13198. }
  13199. else {
  13200. // text type
  13201. checkDuplicatedValue();
  13202. }
  13203. }
  13204. else if (tag === 'select') {
  13205. directiveToUse = V_MODEL_SELECT;
  13206. }
  13207. else {
  13208. // textarea
  13209. checkDuplicatedValue();
  13210. }
  13211. // inject runtime directive
  13212. // by returning the helper symbol via needRuntime
  13213. // the import will replaced a resolveDirective call.
  13214. if (!isInvalidType) {
  13215. baseResult.needRuntime = context.helper(directiveToUse);
  13216. }
  13217. }
  13218. else {
  13219. context.onError(createDOMCompilerError(53 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  13220. }
  13221. // native vmodel doesn't need the `modelValue` props since they are also
  13222. // passed to the runtime as `binding.value`. removing it reduces code size.
  13223. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  13224. p.key.content === 'modelValue'));
  13225. return baseResult;
  13226. };
  13227. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  13228. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  13229. // event propagation management
  13230. `stop,prevent,self,` +
  13231. // system modifiers + exact
  13232. `ctrl,shift,alt,meta,exact,` +
  13233. // mouse
  13234. `middle`);
  13235. // left & right could be mouse or key modifiers based on event type
  13236. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  13237. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  13238. const resolveModifiers = (key, modifiers) => {
  13239. const keyModifiers = [];
  13240. const nonKeyModifiers = [];
  13241. const eventOptionModifiers = [];
  13242. for (let i = 0; i < modifiers.length; i++) {
  13243. const modifier = modifiers[i];
  13244. if (isEventOptionModifier(modifier)) {
  13245. // eventOptionModifiers: modifiers for addEventListener() options,
  13246. // e.g. .passive & .capture
  13247. eventOptionModifiers.push(modifier);
  13248. }
  13249. else {
  13250. // runtimeModifiers: modifiers that needs runtime guards
  13251. if (maybeKeyModifier(modifier)) {
  13252. if (isStaticExp(key)) {
  13253. if (isKeyboardEvent(key.content)) {
  13254. keyModifiers.push(modifier);
  13255. }
  13256. else {
  13257. nonKeyModifiers.push(modifier);
  13258. }
  13259. }
  13260. else {
  13261. keyModifiers.push(modifier);
  13262. nonKeyModifiers.push(modifier);
  13263. }
  13264. }
  13265. else {
  13266. if (isNonKeyModifier(modifier)) {
  13267. nonKeyModifiers.push(modifier);
  13268. }
  13269. else {
  13270. keyModifiers.push(modifier);
  13271. }
  13272. }
  13273. }
  13274. }
  13275. return {
  13276. keyModifiers,
  13277. nonKeyModifiers,
  13278. eventOptionModifiers
  13279. };
  13280. };
  13281. const transformClick = (key, event) => {
  13282. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  13283. return isStaticClick
  13284. ? createSimpleExpression(event, true)
  13285. : key.type !== 4 /* SIMPLE_EXPRESSION */
  13286. ? createCompoundExpression([
  13287. `(`,
  13288. key,
  13289. `) === "onClick" ? "${event}" : (`,
  13290. key,
  13291. `)`
  13292. ])
  13293. : key;
  13294. };
  13295. const transformOn$1 = (dir, node, context) => {
  13296. return transformOn(dir, node, context, baseResult => {
  13297. const { modifiers } = dir;
  13298. if (!modifiers.length)
  13299. return baseResult;
  13300. let { key, value: handlerExp } = baseResult.props[0];
  13301. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers);
  13302. // normalize click.right and click.middle since they don't actually fire
  13303. if (nonKeyModifiers.includes('right')) {
  13304. key = transformClick(key, `onContextmenu`);
  13305. }
  13306. if (nonKeyModifiers.includes('middle')) {
  13307. key = transformClick(key, `onMouseup`);
  13308. }
  13309. if (nonKeyModifiers.length) {
  13310. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  13311. handlerExp,
  13312. JSON.stringify(nonKeyModifiers)
  13313. ]);
  13314. }
  13315. if (keyModifiers.length &&
  13316. // if event name is dynamic, always wrap with keys guard
  13317. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  13318. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  13319. handlerExp,
  13320. JSON.stringify(keyModifiers)
  13321. ]);
  13322. }
  13323. if (eventOptionModifiers.length) {
  13324. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  13325. key = isStaticExp(key)
  13326. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  13327. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  13328. }
  13329. return {
  13330. props: [createObjectProperty(key, handlerExp)]
  13331. };
  13332. });
  13333. };
  13334. const transformShow = (dir, node, context) => {
  13335. const { exp, loc } = dir;
  13336. if (!exp) {
  13337. context.onError(createDOMCompilerError(57 /* X_V_SHOW_NO_EXPRESSION */, loc));
  13338. }
  13339. return {
  13340. props: [],
  13341. needRuntime: context.helper(V_SHOW)
  13342. };
  13343. };
  13344. const warnTransitionChildren = (node, context) => {
  13345. if (node.type === 1 /* ELEMENT */ &&
  13346. node.tagType === 1 /* COMPONENT */) {
  13347. const component = context.isBuiltInComponent(node.tag);
  13348. if (component === TRANSITION$1) {
  13349. return () => {
  13350. if (node.children.length && hasMultipleChildren(node)) {
  13351. context.onError(createDOMCompilerError(58 /* X_TRANSITION_INVALID_CHILDREN */, {
  13352. start: node.children[0].loc.start,
  13353. end: node.children[node.children.length - 1].loc.end,
  13354. source: ''
  13355. }));
  13356. }
  13357. };
  13358. }
  13359. }
  13360. };
  13361. function hasMultipleChildren(node) {
  13362. // #1352 filter out potential comment nodes.
  13363. const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */));
  13364. const child = children[0];
  13365. return (children.length !== 1 ||
  13366. child.type === 11 /* FOR */ ||
  13367. (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
  13368. }
  13369. const ignoreSideEffectTags = (node, context) => {
  13370. if (node.type === 1 /* ELEMENT */ &&
  13371. node.tagType === 0 /* ELEMENT */ &&
  13372. (node.tag === 'script' || node.tag === 'style')) {
  13373. context.onError(createDOMCompilerError(59 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  13374. context.removeNode();
  13375. }
  13376. };
  13377. const DOMNodeTransforms = [
  13378. transformStyle,
  13379. ...([warnTransitionChildren] )
  13380. ];
  13381. const DOMDirectiveTransforms = {
  13382. cloak: noopDirectiveTransform,
  13383. html: transformVHtml,
  13384. text: transformVText,
  13385. model: transformModel$1,
  13386. on: transformOn$1,
  13387. show: transformShow
  13388. };
  13389. function compile$1(template, options = {}) {
  13390. return baseCompile(template, extend({}, parserOptions, options, {
  13391. nodeTransforms: [
  13392. // ignore <script> and <tag>
  13393. // this is not put inside DOMNodeTransforms because that list is used
  13394. // by compiler-ssr to generate vnode fallback branches
  13395. ignoreSideEffectTags,
  13396. ...DOMNodeTransforms,
  13397. ...(options.nodeTransforms || [])
  13398. ],
  13399. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  13400. transformHoist: null
  13401. }));
  13402. }
  13403. // This entry is the "full-build" that includes both the runtime
  13404. {
  13405. initDev();
  13406. }
  13407. const compileCache = Object.create(null);
  13408. function compileToFunction(template, options) {
  13409. if (!isString(template)) {
  13410. if (template.nodeType) {
  13411. template = template.innerHTML;
  13412. }
  13413. else {
  13414. warn(`invalid template option: `, template);
  13415. return NOOP;
  13416. }
  13417. }
  13418. const key = template;
  13419. const cached = compileCache[key];
  13420. if (cached) {
  13421. return cached;
  13422. }
  13423. if (template[0] === '#') {
  13424. const el = document.querySelector(template);
  13425. if (!el) {
  13426. warn(`Template element not found or is empty: ${template}`);
  13427. }
  13428. // __UNSAFE__
  13429. // Reason: potential execution of JS expressions in in-DOM template.
  13430. // The user must make sure the in-DOM template is trusted. If it's rendered
  13431. // by the server, the template should not contain any user data.
  13432. template = el ? el.innerHTML : ``;
  13433. }
  13434. const { code } = compile$1(template, extend({
  13435. hoistStatic: true,
  13436. onError(err) {
  13437. {
  13438. const message = `Template compilation error: ${err.message}`;
  13439. const codeFrame = err.loc &&
  13440. generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
  13441. warn(codeFrame ? `${message}\n${codeFrame}` : message);
  13442. }
  13443. }
  13444. }, options));
  13445. // The wildcard import results in a huge object with every export
  13446. // with keys that cannot be mangled, and can be quite heavy size-wise.
  13447. // In the global build we know `Vue` is available globally so we can avoid
  13448. // the wildcard object.
  13449. const render = (new Function(code)()
  13450. );
  13451. render._rc = true;
  13452. return (compileCache[key] = render);
  13453. }
  13454. registerRuntimeCompiler(compileToFunction);
  13455. exports.BaseTransition = BaseTransition;
  13456. exports.Comment = Comment;
  13457. exports.Fragment = Fragment;
  13458. exports.KeepAlive = KeepAlive;
  13459. exports.Static = Static;
  13460. exports.Suspense = Suspense;
  13461. exports.Teleport = Teleport;
  13462. exports.Text = Text;
  13463. exports.Transition = Transition;
  13464. exports.TransitionGroup = TransitionGroup;
  13465. exports.callWithAsyncErrorHandling = callWithAsyncErrorHandling;
  13466. exports.callWithErrorHandling = callWithErrorHandling;
  13467. exports.camelize = camelize;
  13468. exports.capitalize = capitalize;
  13469. exports.cloneVNode = cloneVNode;
  13470. exports.compile = compileToFunction;
  13471. exports.computed = computed$1;
  13472. exports.createApp = createApp;
  13473. exports.createBlock = createBlock;
  13474. exports.createCommentVNode = createCommentVNode;
  13475. exports.createHydrationRenderer = createHydrationRenderer;
  13476. exports.createRenderer = createRenderer;
  13477. exports.createSSRApp = createSSRApp;
  13478. exports.createSlots = createSlots;
  13479. exports.createStaticVNode = createStaticVNode;
  13480. exports.createTextVNode = createTextVNode;
  13481. exports.createVNode = createVNode;
  13482. exports.customRef = customRef;
  13483. exports.defineAsyncComponent = defineAsyncComponent;
  13484. exports.defineComponent = defineComponent;
  13485. exports.defineEmit = defineEmit;
  13486. exports.defineProps = defineProps;
  13487. exports.getCurrentInstance = getCurrentInstance;
  13488. exports.getTransitionRawChildren = getTransitionRawChildren;
  13489. exports.h = h;
  13490. exports.handleError = handleError;
  13491. exports.hydrate = hydrate;
  13492. exports.initCustomFormatter = initCustomFormatter;
  13493. exports.inject = inject;
  13494. exports.isProxy = isProxy;
  13495. exports.isReactive = isReactive;
  13496. exports.isReadonly = isReadonly;
  13497. exports.isRef = isRef;
  13498. exports.isVNode = isVNode;
  13499. exports.markRaw = markRaw;
  13500. exports.mergeProps = mergeProps;
  13501. exports.nextTick = nextTick;
  13502. exports.onActivated = onActivated;
  13503. exports.onBeforeMount = onBeforeMount;
  13504. exports.onBeforeUnmount = onBeforeUnmount;
  13505. exports.onBeforeUpdate = onBeforeUpdate;
  13506. exports.onDeactivated = onDeactivated;
  13507. exports.onErrorCaptured = onErrorCaptured;
  13508. exports.onMounted = onMounted;
  13509. exports.onRenderTracked = onRenderTracked;
  13510. exports.onRenderTriggered = onRenderTriggered;
  13511. exports.onUnmounted = onUnmounted;
  13512. exports.onUpdated = onUpdated;
  13513. exports.openBlock = openBlock;
  13514. exports.popScopeId = popScopeId;
  13515. exports.provide = provide;
  13516. exports.proxyRefs = proxyRefs;
  13517. exports.pushScopeId = pushScopeId;
  13518. exports.queuePostFlushCb = queuePostFlushCb;
  13519. exports.reactive = reactive;
  13520. exports.readonly = readonly;
  13521. exports.ref = ref;
  13522. exports.registerRuntimeCompiler = registerRuntimeCompiler;
  13523. exports.render = render;
  13524. exports.renderList = renderList;
  13525. exports.renderSlot = renderSlot;
  13526. exports.resolveComponent = resolveComponent;
  13527. exports.resolveDirective = resolveDirective;
  13528. exports.resolveDynamicComponent = resolveDynamicComponent;
  13529. exports.resolveTransitionHooks = resolveTransitionHooks;
  13530. exports.setBlockTracking = setBlockTracking;
  13531. exports.setDevtoolsHook = setDevtoolsHook;
  13532. exports.setTransitionHooks = setTransitionHooks;
  13533. exports.shallowReactive = shallowReactive;
  13534. exports.shallowReadonly = shallowReadonly;
  13535. exports.shallowRef = shallowRef;
  13536. exports.ssrContextKey = ssrContextKey;
  13537. exports.ssrUtils = ssrUtils;
  13538. exports.toDisplayString = toDisplayString;
  13539. exports.toHandlerKey = toHandlerKey;
  13540. exports.toHandlers = toHandlers;
  13541. exports.toRaw = toRaw;
  13542. exports.toRef = toRef;
  13543. exports.toRefs = toRefs;
  13544. exports.transformVNodeArgs = transformVNodeArgs;
  13545. exports.triggerRef = triggerRef;
  13546. exports.unref = unref;
  13547. exports.useContext = useContext;
  13548. exports.useCssModule = useCssModule;
  13549. exports.useCssVars = useCssVars;
  13550. exports.useSSRContext = useSSRContext;
  13551. exports.useTransitionState = useTransitionState;
  13552. exports.vModelCheckbox = vModelCheckbox;
  13553. exports.vModelDynamic = vModelDynamic;
  13554. exports.vModelRadio = vModelRadio;
  13555. exports.vModelSelect = vModelSelect;
  13556. exports.vModelText = vModelText;
  13557. exports.vShow = vShow;
  13558. exports.version = version;
  13559. exports.warn = warn;
  13560. exports.watch = watch;
  13561. exports.watchEffect = watchEffect;
  13562. exports.withCtx = withCtx;
  13563. exports.withDirectives = withDirectives;
  13564. exports.withKeys = withKeys;
  13565. exports.withModifiers = withModifiers;
  13566. exports.withScopeId = withScopeId;
  13567. Object.defineProperty(exports, '__esModule', { value: true });
  13568. return exports;
  13569. }({}));