vue.esm-browser.js 596 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095
  1. /**
  2. * Make a map and return a function for checking if a key
  3. * is in that map.
  4. * IMPORTANT: all calls of this function must be prefixed with
  5. * \/\*#\_\_PURE\_\_\*\/
  6. * So that rollup can tree-shake them if necessary.
  7. */
  8. function makeMap(str, expectsLowerCase) {
  9. const map = Object.create(null);
  10. const list = str.split(',');
  11. for (let i = 0; i < list.length; i++) {
  12. map[list[i]] = true;
  13. }
  14. return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
  15. }
  16. /**
  17. * dev only flag -> name mapping
  18. */
  19. const PatchFlagNames = {
  20. [1 /* PatchFlags.TEXT */]: `TEXT`,
  21. [2 /* PatchFlags.CLASS */]: `CLASS`,
  22. [4 /* PatchFlags.STYLE */]: `STYLE`,
  23. [8 /* PatchFlags.PROPS */]: `PROPS`,
  24. [16 /* PatchFlags.FULL_PROPS */]: `FULL_PROPS`,
  25. [32 /* PatchFlags.HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
  26. [64 /* PatchFlags.STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
  27. [128 /* PatchFlags.KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
  28. [256 /* PatchFlags.UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
  29. [512 /* PatchFlags.NEED_PATCH */]: `NEED_PATCH`,
  30. [1024 /* PatchFlags.DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
  31. [2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
  32. [-1 /* PatchFlags.HOISTED */]: `HOISTED`,
  33. [-2 /* PatchFlags.BAIL */]: `BAIL`
  34. };
  35. /**
  36. * Dev only
  37. */
  38. const slotFlagsText = {
  39. [1 /* SlotFlags.STABLE */]: 'STABLE',
  40. [2 /* SlotFlags.DYNAMIC */]: 'DYNAMIC',
  41. [3 /* SlotFlags.FORWARDED */]: 'FORWARDED'
  42. };
  43. const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' +
  44. 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
  45. 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt';
  46. const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED);
  47. const range = 2;
  48. function generateCodeFrame(source, start = 0, end = source.length) {
  49. // Split the content into individual lines but capture the newline sequence
  50. // that separated each line. This is important because the actual sequence is
  51. // needed to properly take into account the full line length for offset
  52. // comparison
  53. let lines = source.split(/(\r?\n)/);
  54. // Separate the lines and newline sequences into separate arrays for easier referencing
  55. const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);
  56. lines = lines.filter((_, idx) => idx % 2 === 0);
  57. let count = 0;
  58. const res = [];
  59. for (let i = 0; i < lines.length; i++) {
  60. count +=
  61. lines[i].length +
  62. ((newlineSequences[i] && newlineSequences[i].length) || 0);
  63. if (count >= start) {
  64. for (let j = i - range; j <= i + range || end > count; j++) {
  65. if (j < 0 || j >= lines.length)
  66. continue;
  67. const line = j + 1;
  68. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  69. const lineLength = lines[j].length;
  70. const newLineSeqLength = (newlineSequences[j] && newlineSequences[j].length) || 0;
  71. if (j === i) {
  72. // push underline
  73. const pad = start - (count - (lineLength + newLineSeqLength));
  74. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  75. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  76. }
  77. else if (j > i) {
  78. if (end > count) {
  79. const length = Math.max(Math.min(end - count, lineLength), 1);
  80. res.push(` | ` + '^'.repeat(length));
  81. }
  82. count += lineLength + newLineSeqLength;
  83. }
  84. }
  85. break;
  86. }
  87. }
  88. return res.join('\n');
  89. }
  90. function normalizeStyle(value) {
  91. if (isArray(value)) {
  92. const res = {};
  93. for (let i = 0; i < value.length; i++) {
  94. const item = value[i];
  95. const normalized = isString(item)
  96. ? parseStringStyle(item)
  97. : normalizeStyle(item);
  98. if (normalized) {
  99. for (const key in normalized) {
  100. res[key] = normalized[key];
  101. }
  102. }
  103. }
  104. return res;
  105. }
  106. else if (isString(value)) {
  107. return value;
  108. }
  109. else if (isObject(value)) {
  110. return value;
  111. }
  112. }
  113. const listDelimiterRE = /;(?![^(]*\))/g;
  114. const propertyDelimiterRE = /:([^]+)/;
  115. const styleCommentRE = /\/\*.*?\*\//gs;
  116. function parseStringStyle(cssText) {
  117. const ret = {};
  118. cssText
  119. .replace(styleCommentRE, '')
  120. .split(listDelimiterRE)
  121. .forEach(item => {
  122. if (item) {
  123. const tmp = item.split(propertyDelimiterRE);
  124. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  125. }
  126. });
  127. return ret;
  128. }
  129. function normalizeClass(value) {
  130. let res = '';
  131. if (isString(value)) {
  132. res = value;
  133. }
  134. else if (isArray(value)) {
  135. for (let i = 0; i < value.length; i++) {
  136. const normalized = normalizeClass(value[i]);
  137. if (normalized) {
  138. res += normalized + ' ';
  139. }
  140. }
  141. }
  142. else if (isObject(value)) {
  143. for (const name in value) {
  144. if (value[name]) {
  145. res += name + ' ';
  146. }
  147. }
  148. }
  149. return res.trim();
  150. }
  151. function normalizeProps(props) {
  152. if (!props)
  153. return null;
  154. let { class: klass, style } = props;
  155. if (klass && !isString(klass)) {
  156. props.class = normalizeClass(klass);
  157. }
  158. if (style) {
  159. props.style = normalizeStyle(style);
  160. }
  161. return props;
  162. }
  163. // These tag configs are shared between compiler-dom and runtime-dom, so they
  164. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  165. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  166. 'header,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,' +
  167. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  168. 'data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,' +
  169. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  170. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  171. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  172. 'option,output,progress,select,textarea,details,dialog,menu,' +
  173. 'summary,template,blockquote,iframe,tfoot';
  174. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  175. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  176. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  177. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  178. 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  179. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  180. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  181. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  182. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  183. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  184. 'text,textPath,title,tspan,unknown,use,view';
  185. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  186. /**
  187. * Compiler only.
  188. * Do NOT use in runtime code paths unless behind `true` flag.
  189. */
  190. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  191. /**
  192. * Compiler only.
  193. * Do NOT use in runtime code paths unless behind `true` flag.
  194. */
  195. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  196. /**
  197. * Compiler only.
  198. * Do NOT use in runtime code paths unless behind `true` flag.
  199. */
  200. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  201. /**
  202. * On the client we only need to offer special cases for boolean attributes that
  203. * have different names from their corresponding dom properties:
  204. * - itemscope -> N/A
  205. * - allowfullscreen -> allowFullscreen
  206. * - formnovalidate -> formNoValidate
  207. * - ismap -> isMap
  208. * - nomodule -> noModule
  209. * - novalidate -> noValidate
  210. * - readonly -> readOnly
  211. */
  212. const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
  213. const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs);
  214. /**
  215. * Boolean attributes should be included if the value is truthy or ''.
  216. * e.g. `<select multiple>` compiles to `{ multiple: '' }`
  217. */
  218. function includeBooleanAttr(value) {
  219. return !!value || value === '';
  220. }
  221. function looseCompareArrays(a, b) {
  222. if (a.length !== b.length)
  223. return false;
  224. let equal = true;
  225. for (let i = 0; equal && i < a.length; i++) {
  226. equal = looseEqual(a[i], b[i]);
  227. }
  228. return equal;
  229. }
  230. function looseEqual(a, b) {
  231. if (a === b)
  232. return true;
  233. let aValidType = isDate(a);
  234. let bValidType = isDate(b);
  235. if (aValidType || bValidType) {
  236. return aValidType && bValidType ? a.getTime() === b.getTime() : false;
  237. }
  238. aValidType = isSymbol(a);
  239. bValidType = isSymbol(b);
  240. if (aValidType || bValidType) {
  241. return a === b;
  242. }
  243. aValidType = isArray(a);
  244. bValidType = isArray(b);
  245. if (aValidType || bValidType) {
  246. return aValidType && bValidType ? looseCompareArrays(a, b) : false;
  247. }
  248. aValidType = isObject(a);
  249. bValidType = isObject(b);
  250. if (aValidType || bValidType) {
  251. /* istanbul ignore if: this if will probably never be called */
  252. if (!aValidType || !bValidType) {
  253. return false;
  254. }
  255. const aKeysCount = Object.keys(a).length;
  256. const bKeysCount = Object.keys(b).length;
  257. if (aKeysCount !== bKeysCount) {
  258. return false;
  259. }
  260. for (const key in a) {
  261. const aHasKey = a.hasOwnProperty(key);
  262. const bHasKey = b.hasOwnProperty(key);
  263. if ((aHasKey && !bHasKey) ||
  264. (!aHasKey && bHasKey) ||
  265. !looseEqual(a[key], b[key])) {
  266. return false;
  267. }
  268. }
  269. }
  270. return String(a) === String(b);
  271. }
  272. function looseIndexOf(arr, val) {
  273. return arr.findIndex(item => looseEqual(item, val));
  274. }
  275. /**
  276. * For converting {{ interpolation }} values to displayed strings.
  277. * @private
  278. */
  279. const toDisplayString = (val) => {
  280. return isString(val)
  281. ? val
  282. : val == null
  283. ? ''
  284. : isArray(val) ||
  285. (isObject(val) &&
  286. (val.toString === objectToString || !isFunction(val.toString)))
  287. ? JSON.stringify(val, replacer, 2)
  288. : String(val);
  289. };
  290. const replacer = (_key, val) => {
  291. // can't use isRef here since @vue/shared has no deps
  292. if (val && val.__v_isRef) {
  293. return replacer(_key, val.value);
  294. }
  295. else if (isMap(val)) {
  296. return {
  297. [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
  298. entries[`${key} =>`] = val;
  299. return entries;
  300. }, {})
  301. };
  302. }
  303. else if (isSet(val)) {
  304. return {
  305. [`Set(${val.size})`]: [...val.values()]
  306. };
  307. }
  308. else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
  309. return String(val);
  310. }
  311. return val;
  312. };
  313. const EMPTY_OBJ = Object.freeze({})
  314. ;
  315. const EMPTY_ARR = Object.freeze([]) ;
  316. const NOOP = () => { };
  317. /**
  318. * Always return false.
  319. */
  320. const NO = () => false;
  321. const onRE = /^on[^a-z]/;
  322. const isOn = (key) => onRE.test(key);
  323. const isModelListener = (key) => key.startsWith('onUpdate:');
  324. const extend = Object.assign;
  325. const remove = (arr, el) => {
  326. const i = arr.indexOf(el);
  327. if (i > -1) {
  328. arr.splice(i, 1);
  329. }
  330. };
  331. const hasOwnProperty = Object.prototype.hasOwnProperty;
  332. const hasOwn = (val, key) => hasOwnProperty.call(val, key);
  333. const isArray = Array.isArray;
  334. const isMap = (val) => toTypeString(val) === '[object Map]';
  335. const isSet = (val) => toTypeString(val) === '[object Set]';
  336. const isDate = (val) => toTypeString(val) === '[object Date]';
  337. const isFunction = (val) => typeof val === 'function';
  338. const isString = (val) => typeof val === 'string';
  339. const isSymbol = (val) => typeof val === 'symbol';
  340. const isObject = (val) => val !== null && typeof val === 'object';
  341. const isPromise = (val) => {
  342. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  343. };
  344. const objectToString = Object.prototype.toString;
  345. const toTypeString = (value) => objectToString.call(value);
  346. const toRawType = (value) => {
  347. // extract "RawType" from strings like "[object RawType]"
  348. return toTypeString(value).slice(8, -1);
  349. };
  350. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  351. const isIntegerKey = (key) => isString(key) &&
  352. key !== 'NaN' &&
  353. key[0] !== '-' &&
  354. '' + parseInt(key, 10) === key;
  355. const isReservedProp = /*#__PURE__*/ makeMap(
  356. // the leading comma is intentional so empty string "" is also included
  357. ',key,ref,ref_for,ref_key,' +
  358. 'onVnodeBeforeMount,onVnodeMounted,' +
  359. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  360. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  361. const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo');
  362. const cacheStringFunction = (fn) => {
  363. const cache = Object.create(null);
  364. return ((str) => {
  365. const hit = cache[str];
  366. return hit || (cache[str] = fn(str));
  367. });
  368. };
  369. const camelizeRE = /-(\w)/g;
  370. /**
  371. * @private
  372. */
  373. const camelize = cacheStringFunction((str) => {
  374. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  375. });
  376. const hyphenateRE = /\B([A-Z])/g;
  377. /**
  378. * @private
  379. */
  380. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  381. /**
  382. * @private
  383. */
  384. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  385. /**
  386. * @private
  387. */
  388. const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
  389. // compare whether a value has changed, accounting for NaN.
  390. const hasChanged = (value, oldValue) => !Object.is(value, oldValue);
  391. const invokeArrayFns = (fns, arg) => {
  392. for (let i = 0; i < fns.length; i++) {
  393. fns[i](arg);
  394. }
  395. };
  396. const def = (obj, key, value) => {
  397. Object.defineProperty(obj, key, {
  398. configurable: true,
  399. enumerable: false,
  400. value
  401. });
  402. };
  403. const toNumber = (val) => {
  404. const n = parseFloat(val);
  405. return isNaN(n) ? val : n;
  406. };
  407. let _globalThis;
  408. const getGlobalThis = () => {
  409. return (_globalThis ||
  410. (_globalThis =
  411. typeof globalThis !== 'undefined'
  412. ? globalThis
  413. : typeof self !== 'undefined'
  414. ? self
  415. : typeof window !== 'undefined'
  416. ? window
  417. : typeof global !== 'undefined'
  418. ? global
  419. : {}));
  420. };
  421. function warn(msg, ...args) {
  422. console.warn(`[Vue warn] ${msg}`, ...args);
  423. }
  424. let activeEffectScope;
  425. class EffectScope {
  426. constructor(detached = false) {
  427. this.detached = detached;
  428. /**
  429. * @internal
  430. */
  431. this.active = true;
  432. /**
  433. * @internal
  434. */
  435. this.effects = [];
  436. /**
  437. * @internal
  438. */
  439. this.cleanups = [];
  440. this.parent = activeEffectScope;
  441. if (!detached && activeEffectScope) {
  442. this.index =
  443. (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1;
  444. }
  445. }
  446. run(fn) {
  447. if (this.active) {
  448. const currentEffectScope = activeEffectScope;
  449. try {
  450. activeEffectScope = this;
  451. return fn();
  452. }
  453. finally {
  454. activeEffectScope = currentEffectScope;
  455. }
  456. }
  457. else {
  458. warn(`cannot run an inactive effect scope.`);
  459. }
  460. }
  461. /**
  462. * This should only be called on non-detached scopes
  463. * @internal
  464. */
  465. on() {
  466. activeEffectScope = this;
  467. }
  468. /**
  469. * This should only be called on non-detached scopes
  470. * @internal
  471. */
  472. off() {
  473. activeEffectScope = this.parent;
  474. }
  475. stop(fromParent) {
  476. if (this.active) {
  477. let i, l;
  478. for (i = 0, l = this.effects.length; i < l; i++) {
  479. this.effects[i].stop();
  480. }
  481. for (i = 0, l = this.cleanups.length; i < l; i++) {
  482. this.cleanups[i]();
  483. }
  484. if (this.scopes) {
  485. for (i = 0, l = this.scopes.length; i < l; i++) {
  486. this.scopes[i].stop(true);
  487. }
  488. }
  489. // nested scope, dereference from parent to avoid memory leaks
  490. if (!this.detached && this.parent && !fromParent) {
  491. // optimized O(1) removal
  492. const last = this.parent.scopes.pop();
  493. if (last && last !== this) {
  494. this.parent.scopes[this.index] = last;
  495. last.index = this.index;
  496. }
  497. }
  498. this.parent = undefined;
  499. this.active = false;
  500. }
  501. }
  502. }
  503. function effectScope(detached) {
  504. return new EffectScope(detached);
  505. }
  506. function recordEffectScope(effect, scope = activeEffectScope) {
  507. if (scope && scope.active) {
  508. scope.effects.push(effect);
  509. }
  510. }
  511. function getCurrentScope() {
  512. return activeEffectScope;
  513. }
  514. function onScopeDispose(fn) {
  515. if (activeEffectScope) {
  516. activeEffectScope.cleanups.push(fn);
  517. }
  518. else {
  519. warn(`onScopeDispose() is called when there is no active effect scope` +
  520. ` to be associated with.`);
  521. }
  522. }
  523. const createDep = (effects) => {
  524. const dep = new Set(effects);
  525. dep.w = 0;
  526. dep.n = 0;
  527. return dep;
  528. };
  529. const wasTracked = (dep) => (dep.w & trackOpBit) > 0;
  530. const newTracked = (dep) => (dep.n & trackOpBit) > 0;
  531. const initDepMarkers = ({ deps }) => {
  532. if (deps.length) {
  533. for (let i = 0; i < deps.length; i++) {
  534. deps[i].w |= trackOpBit; // set was tracked
  535. }
  536. }
  537. };
  538. const finalizeDepMarkers = (effect) => {
  539. const { deps } = effect;
  540. if (deps.length) {
  541. let ptr = 0;
  542. for (let i = 0; i < deps.length; i++) {
  543. const dep = deps[i];
  544. if (wasTracked(dep) && !newTracked(dep)) {
  545. dep.delete(effect);
  546. }
  547. else {
  548. deps[ptr++] = dep;
  549. }
  550. // clear bits
  551. dep.w &= ~trackOpBit;
  552. dep.n &= ~trackOpBit;
  553. }
  554. deps.length = ptr;
  555. }
  556. };
  557. const targetMap = new WeakMap();
  558. // The number of effects currently being tracked recursively.
  559. let effectTrackDepth = 0;
  560. let trackOpBit = 1;
  561. /**
  562. * The bitwise track markers support at most 30 levels of recursion.
  563. * This value is chosen to enable modern JS engines to use a SMI on all platforms.
  564. * When recursion depth is greater, fall back to using a full cleanup.
  565. */
  566. const maxMarkerBits = 30;
  567. let activeEffect;
  568. const ITERATE_KEY = Symbol('iterate' );
  569. const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
  570. class ReactiveEffect {
  571. constructor(fn, scheduler = null, scope) {
  572. this.fn = fn;
  573. this.scheduler = scheduler;
  574. this.active = true;
  575. this.deps = [];
  576. this.parent = undefined;
  577. recordEffectScope(this, scope);
  578. }
  579. run() {
  580. if (!this.active) {
  581. return this.fn();
  582. }
  583. let parent = activeEffect;
  584. let lastShouldTrack = shouldTrack;
  585. while (parent) {
  586. if (parent === this) {
  587. return;
  588. }
  589. parent = parent.parent;
  590. }
  591. try {
  592. this.parent = activeEffect;
  593. activeEffect = this;
  594. shouldTrack = true;
  595. trackOpBit = 1 << ++effectTrackDepth;
  596. if (effectTrackDepth <= maxMarkerBits) {
  597. initDepMarkers(this);
  598. }
  599. else {
  600. cleanupEffect(this);
  601. }
  602. return this.fn();
  603. }
  604. finally {
  605. if (effectTrackDepth <= maxMarkerBits) {
  606. finalizeDepMarkers(this);
  607. }
  608. trackOpBit = 1 << --effectTrackDepth;
  609. activeEffect = this.parent;
  610. shouldTrack = lastShouldTrack;
  611. this.parent = undefined;
  612. if (this.deferStop) {
  613. this.stop();
  614. }
  615. }
  616. }
  617. stop() {
  618. // stopped while running itself - defer the cleanup
  619. if (activeEffect === this) {
  620. this.deferStop = true;
  621. }
  622. else if (this.active) {
  623. cleanupEffect(this);
  624. if (this.onStop) {
  625. this.onStop();
  626. }
  627. this.active = false;
  628. }
  629. }
  630. }
  631. function cleanupEffect(effect) {
  632. const { deps } = effect;
  633. if (deps.length) {
  634. for (let i = 0; i < deps.length; i++) {
  635. deps[i].delete(effect);
  636. }
  637. deps.length = 0;
  638. }
  639. }
  640. function effect(fn, options) {
  641. if (fn.effect) {
  642. fn = fn.effect.fn;
  643. }
  644. const _effect = new ReactiveEffect(fn);
  645. if (options) {
  646. extend(_effect, options);
  647. if (options.scope)
  648. recordEffectScope(_effect, options.scope);
  649. }
  650. if (!options || !options.lazy) {
  651. _effect.run();
  652. }
  653. const runner = _effect.run.bind(_effect);
  654. runner.effect = _effect;
  655. return runner;
  656. }
  657. function stop(runner) {
  658. runner.effect.stop();
  659. }
  660. let shouldTrack = true;
  661. const trackStack = [];
  662. function pauseTracking() {
  663. trackStack.push(shouldTrack);
  664. shouldTrack = false;
  665. }
  666. function resetTracking() {
  667. const last = trackStack.pop();
  668. shouldTrack = last === undefined ? true : last;
  669. }
  670. function track(target, type, key) {
  671. if (shouldTrack && activeEffect) {
  672. let depsMap = targetMap.get(target);
  673. if (!depsMap) {
  674. targetMap.set(target, (depsMap = new Map()));
  675. }
  676. let dep = depsMap.get(key);
  677. if (!dep) {
  678. depsMap.set(key, (dep = createDep()));
  679. }
  680. const eventInfo = { effect: activeEffect, target, type, key }
  681. ;
  682. trackEffects(dep, eventInfo);
  683. }
  684. }
  685. function trackEffects(dep, debuggerEventExtraInfo) {
  686. let shouldTrack = false;
  687. if (effectTrackDepth <= maxMarkerBits) {
  688. if (!newTracked(dep)) {
  689. dep.n |= trackOpBit; // set newly tracked
  690. shouldTrack = !wasTracked(dep);
  691. }
  692. }
  693. else {
  694. // Full cleanup mode.
  695. shouldTrack = !dep.has(activeEffect);
  696. }
  697. if (shouldTrack) {
  698. dep.add(activeEffect);
  699. activeEffect.deps.push(dep);
  700. if (activeEffect.onTrack) {
  701. activeEffect.onTrack(Object.assign({ effect: activeEffect }, debuggerEventExtraInfo));
  702. }
  703. }
  704. }
  705. function trigger(target, type, key, newValue, oldValue, oldTarget) {
  706. const depsMap = targetMap.get(target);
  707. if (!depsMap) {
  708. // never been tracked
  709. return;
  710. }
  711. let deps = [];
  712. if (type === "clear" /* TriggerOpTypes.CLEAR */) {
  713. // collection being cleared
  714. // trigger all effects for target
  715. deps = [...depsMap.values()];
  716. }
  717. else if (key === 'length' && isArray(target)) {
  718. const newLength = toNumber(newValue);
  719. depsMap.forEach((dep, key) => {
  720. if (key === 'length' || key >= newLength) {
  721. deps.push(dep);
  722. }
  723. });
  724. }
  725. else {
  726. // schedule runs for SET | ADD | DELETE
  727. if (key !== void 0) {
  728. deps.push(depsMap.get(key));
  729. }
  730. // also run for iteration key on ADD | DELETE | Map.SET
  731. switch (type) {
  732. case "add" /* TriggerOpTypes.ADD */:
  733. if (!isArray(target)) {
  734. deps.push(depsMap.get(ITERATE_KEY));
  735. if (isMap(target)) {
  736. deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
  737. }
  738. }
  739. else if (isIntegerKey(key)) {
  740. // new index added to array -> length changes
  741. deps.push(depsMap.get('length'));
  742. }
  743. break;
  744. case "delete" /* TriggerOpTypes.DELETE */:
  745. if (!isArray(target)) {
  746. deps.push(depsMap.get(ITERATE_KEY));
  747. if (isMap(target)) {
  748. deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
  749. }
  750. }
  751. break;
  752. case "set" /* TriggerOpTypes.SET */:
  753. if (isMap(target)) {
  754. deps.push(depsMap.get(ITERATE_KEY));
  755. }
  756. break;
  757. }
  758. }
  759. const eventInfo = { target, type, key, newValue, oldValue, oldTarget }
  760. ;
  761. if (deps.length === 1) {
  762. if (deps[0]) {
  763. {
  764. triggerEffects(deps[0], eventInfo);
  765. }
  766. }
  767. }
  768. else {
  769. const effects = [];
  770. for (const dep of deps) {
  771. if (dep) {
  772. effects.push(...dep);
  773. }
  774. }
  775. {
  776. triggerEffects(createDep(effects), eventInfo);
  777. }
  778. }
  779. }
  780. function triggerEffects(dep, debuggerEventExtraInfo) {
  781. // spread into array for stabilization
  782. const effects = isArray(dep) ? dep : [...dep];
  783. for (const effect of effects) {
  784. if (effect.computed) {
  785. triggerEffect(effect, debuggerEventExtraInfo);
  786. }
  787. }
  788. for (const effect of effects) {
  789. if (!effect.computed) {
  790. triggerEffect(effect, debuggerEventExtraInfo);
  791. }
  792. }
  793. }
  794. function triggerEffect(effect, debuggerEventExtraInfo) {
  795. if (effect !== activeEffect || effect.allowRecurse) {
  796. if (effect.onTrigger) {
  797. effect.onTrigger(extend({ effect }, debuggerEventExtraInfo));
  798. }
  799. if (effect.scheduler) {
  800. effect.scheduler();
  801. }
  802. else {
  803. effect.run();
  804. }
  805. }
  806. }
  807. const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
  808. const builtInSymbols = new Set(
  809. /*#__PURE__*/
  810. Object.getOwnPropertyNames(Symbol)
  811. // ios10.x Object.getOwnPropertyNames(Symbol) can enumerate 'arguments' and 'caller'
  812. // but accessing them on Symbol leads to TypeError because Symbol is a strict mode
  813. // function
  814. .filter(key => key !== 'arguments' && key !== 'caller')
  815. .map(key => Symbol[key])
  816. .filter(isSymbol));
  817. const get = /*#__PURE__*/ createGetter();
  818. const shallowGet = /*#__PURE__*/ createGetter(false, true);
  819. const readonlyGet = /*#__PURE__*/ createGetter(true);
  820. const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
  821. const arrayInstrumentations = /*#__PURE__*/ createArrayInstrumentations();
  822. function createArrayInstrumentations() {
  823. const instrumentations = {};
  824. ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
  825. instrumentations[key] = function (...args) {
  826. const arr = toRaw(this);
  827. for (let i = 0, l = this.length; i < l; i++) {
  828. track(arr, "get" /* TrackOpTypes.GET */, i + '');
  829. }
  830. // we run the method using the original args first (which may be reactive)
  831. const res = arr[key](...args);
  832. if (res === -1 || res === false) {
  833. // if that didn't work, run it again using raw values.
  834. return arr[key](...args.map(toRaw));
  835. }
  836. else {
  837. return res;
  838. }
  839. };
  840. });
  841. ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
  842. instrumentations[key] = function (...args) {
  843. pauseTracking();
  844. const res = toRaw(this)[key].apply(this, args);
  845. resetTracking();
  846. return res;
  847. };
  848. });
  849. return instrumentations;
  850. }
  851. function createGetter(isReadonly = false, shallow = false) {
  852. return function get(target, key, receiver) {
  853. if (key === "__v_isReactive" /* ReactiveFlags.IS_REACTIVE */) {
  854. return !isReadonly;
  855. }
  856. else if (key === "__v_isReadonly" /* ReactiveFlags.IS_READONLY */) {
  857. return isReadonly;
  858. }
  859. else if (key === "__v_isShallow" /* ReactiveFlags.IS_SHALLOW */) {
  860. return shallow;
  861. }
  862. else if (key === "__v_raw" /* ReactiveFlags.RAW */ &&
  863. receiver ===
  864. (isReadonly
  865. ? shallow
  866. ? shallowReadonlyMap
  867. : readonlyMap
  868. : shallow
  869. ? shallowReactiveMap
  870. : reactiveMap).get(target)) {
  871. return target;
  872. }
  873. const targetIsArray = isArray(target);
  874. if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
  875. return Reflect.get(arrayInstrumentations, key, receiver);
  876. }
  877. const res = Reflect.get(target, key, receiver);
  878. if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
  879. return res;
  880. }
  881. if (!isReadonly) {
  882. track(target, "get" /* TrackOpTypes.GET */, key);
  883. }
  884. if (shallow) {
  885. return res;
  886. }
  887. if (isRef(res)) {
  888. // ref unwrapping - skip unwrap for Array + integer key.
  889. return targetIsArray && isIntegerKey(key) ? res : res.value;
  890. }
  891. if (isObject(res)) {
  892. // Convert returned value into a proxy as well. we do the isObject check
  893. // here to avoid invalid value warning. Also need to lazy access readonly
  894. // and reactive here to avoid circular dependency.
  895. return isReadonly ? readonly(res) : reactive(res);
  896. }
  897. return res;
  898. };
  899. }
  900. const set = /*#__PURE__*/ createSetter();
  901. const shallowSet = /*#__PURE__*/ createSetter(true);
  902. function createSetter(shallow = false) {
  903. return function set(target, key, value, receiver) {
  904. let oldValue = target[key];
  905. if (isReadonly(oldValue) && isRef(oldValue) && !isRef(value)) {
  906. return false;
  907. }
  908. if (!shallow) {
  909. if (!isShallow(value) && !isReadonly(value)) {
  910. oldValue = toRaw(oldValue);
  911. value = toRaw(value);
  912. }
  913. if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
  914. oldValue.value = value;
  915. return true;
  916. }
  917. }
  918. const hadKey = isArray(target) && isIntegerKey(key)
  919. ? Number(key) < target.length
  920. : hasOwn(target, key);
  921. const result = Reflect.set(target, key, value, receiver);
  922. // don't trigger if target is something up in the prototype chain of original
  923. if (target === toRaw(receiver)) {
  924. if (!hadKey) {
  925. trigger(target, "add" /* TriggerOpTypes.ADD */, key, value);
  926. }
  927. else if (hasChanged(value, oldValue)) {
  928. trigger(target, "set" /* TriggerOpTypes.SET */, key, value, oldValue);
  929. }
  930. }
  931. return result;
  932. };
  933. }
  934. function deleteProperty(target, key) {
  935. const hadKey = hasOwn(target, key);
  936. const oldValue = target[key];
  937. const result = Reflect.deleteProperty(target, key);
  938. if (result && hadKey) {
  939. trigger(target, "delete" /* TriggerOpTypes.DELETE */, key, undefined, oldValue);
  940. }
  941. return result;
  942. }
  943. function has(target, key) {
  944. const result = Reflect.has(target, key);
  945. if (!isSymbol(key) || !builtInSymbols.has(key)) {
  946. track(target, "has" /* TrackOpTypes.HAS */, key);
  947. }
  948. return result;
  949. }
  950. function ownKeys(target) {
  951. track(target, "iterate" /* TrackOpTypes.ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
  952. return Reflect.ownKeys(target);
  953. }
  954. const mutableHandlers = {
  955. get,
  956. set,
  957. deleteProperty,
  958. has,
  959. ownKeys
  960. };
  961. const readonlyHandlers = {
  962. get: readonlyGet,
  963. set(target, key) {
  964. {
  965. warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
  966. }
  967. return true;
  968. },
  969. deleteProperty(target, key) {
  970. {
  971. warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
  972. }
  973. return true;
  974. }
  975. };
  976. const shallowReactiveHandlers = /*#__PURE__*/ extend({}, mutableHandlers, {
  977. get: shallowGet,
  978. set: shallowSet
  979. });
  980. // Props handlers are special in the sense that it should not unwrap top-level
  981. // refs (in order to allow refs to be explicitly passed down), but should
  982. // retain the reactivity of the normal readonly object.
  983. const shallowReadonlyHandlers = /*#__PURE__*/ extend({}, readonlyHandlers, {
  984. get: shallowReadonlyGet
  985. });
  986. const toShallow = (value) => value;
  987. const getProto = (v) => Reflect.getPrototypeOf(v);
  988. function get$1(target, key, isReadonly = false, isShallow = false) {
  989. // #1772: readonly(reactive(Map)) should return readonly + reactive version
  990. // of the value
  991. target = target["__v_raw" /* ReactiveFlags.RAW */];
  992. const rawTarget = toRaw(target);
  993. const rawKey = toRaw(key);
  994. if (!isReadonly) {
  995. if (key !== rawKey) {
  996. track(rawTarget, "get" /* TrackOpTypes.GET */, key);
  997. }
  998. track(rawTarget, "get" /* TrackOpTypes.GET */, rawKey);
  999. }
  1000. const { has } = getProto(rawTarget);
  1001. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  1002. if (has.call(rawTarget, key)) {
  1003. return wrap(target.get(key));
  1004. }
  1005. else if (has.call(rawTarget, rawKey)) {
  1006. return wrap(target.get(rawKey));
  1007. }
  1008. else if (target !== rawTarget) {
  1009. // #3602 readonly(reactive(Map))
  1010. // ensure that the nested reactive `Map` can do tracking for itself
  1011. target.get(key);
  1012. }
  1013. }
  1014. function has$1(key, isReadonly = false) {
  1015. const target = this["__v_raw" /* ReactiveFlags.RAW */];
  1016. const rawTarget = toRaw(target);
  1017. const rawKey = toRaw(key);
  1018. if (!isReadonly) {
  1019. if (key !== rawKey) {
  1020. track(rawTarget, "has" /* TrackOpTypes.HAS */, key);
  1021. }
  1022. track(rawTarget, "has" /* TrackOpTypes.HAS */, rawKey);
  1023. }
  1024. return key === rawKey
  1025. ? target.has(key)
  1026. : target.has(key) || target.has(rawKey);
  1027. }
  1028. function size(target, isReadonly = false) {
  1029. target = target["__v_raw" /* ReactiveFlags.RAW */];
  1030. !isReadonly && track(toRaw(target), "iterate" /* TrackOpTypes.ITERATE */, ITERATE_KEY);
  1031. return Reflect.get(target, 'size', target);
  1032. }
  1033. function add(value) {
  1034. value = toRaw(value);
  1035. const target = toRaw(this);
  1036. const proto = getProto(target);
  1037. const hadKey = proto.has.call(target, value);
  1038. if (!hadKey) {
  1039. target.add(value);
  1040. trigger(target, "add" /* TriggerOpTypes.ADD */, value, value);
  1041. }
  1042. return this;
  1043. }
  1044. function set$1(key, value) {
  1045. value = toRaw(value);
  1046. const target = toRaw(this);
  1047. const { has, get } = getProto(target);
  1048. let hadKey = has.call(target, key);
  1049. if (!hadKey) {
  1050. key = toRaw(key);
  1051. hadKey = has.call(target, key);
  1052. }
  1053. else {
  1054. checkIdentityKeys(target, has, key);
  1055. }
  1056. const oldValue = get.call(target, key);
  1057. target.set(key, value);
  1058. if (!hadKey) {
  1059. trigger(target, "add" /* TriggerOpTypes.ADD */, key, value);
  1060. }
  1061. else if (hasChanged(value, oldValue)) {
  1062. trigger(target, "set" /* TriggerOpTypes.SET */, key, value, oldValue);
  1063. }
  1064. return this;
  1065. }
  1066. function deleteEntry(key) {
  1067. const target = toRaw(this);
  1068. const { has, get } = getProto(target);
  1069. let hadKey = has.call(target, key);
  1070. if (!hadKey) {
  1071. key = toRaw(key);
  1072. hadKey = has.call(target, key);
  1073. }
  1074. else {
  1075. checkIdentityKeys(target, has, key);
  1076. }
  1077. const oldValue = get ? get.call(target, key) : undefined;
  1078. // forward the operation before queueing reactions
  1079. const result = target.delete(key);
  1080. if (hadKey) {
  1081. trigger(target, "delete" /* TriggerOpTypes.DELETE */, key, undefined, oldValue);
  1082. }
  1083. return result;
  1084. }
  1085. function clear() {
  1086. const target = toRaw(this);
  1087. const hadItems = target.size !== 0;
  1088. const oldTarget = isMap(target)
  1089. ? new Map(target)
  1090. : new Set(target)
  1091. ;
  1092. // forward the operation before queueing reactions
  1093. const result = target.clear();
  1094. if (hadItems) {
  1095. trigger(target, "clear" /* TriggerOpTypes.CLEAR */, undefined, undefined, oldTarget);
  1096. }
  1097. return result;
  1098. }
  1099. function createForEach(isReadonly, isShallow) {
  1100. return function forEach(callback, thisArg) {
  1101. const observed = this;
  1102. const target = observed["__v_raw" /* ReactiveFlags.RAW */];
  1103. const rawTarget = toRaw(target);
  1104. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  1105. !isReadonly && track(rawTarget, "iterate" /* TrackOpTypes.ITERATE */, ITERATE_KEY);
  1106. return target.forEach((value, key) => {
  1107. // important: make sure the callback is
  1108. // 1. invoked with the reactive map as `this` and 3rd arg
  1109. // 2. the value received should be a corresponding reactive/readonly.
  1110. return callback.call(thisArg, wrap(value), wrap(key), observed);
  1111. });
  1112. };
  1113. }
  1114. function createIterableMethod(method, isReadonly, isShallow) {
  1115. return function (...args) {
  1116. const target = this["__v_raw" /* ReactiveFlags.RAW */];
  1117. const rawTarget = toRaw(target);
  1118. const targetIsMap = isMap(rawTarget);
  1119. const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
  1120. const isKeyOnly = method === 'keys' && targetIsMap;
  1121. const innerIterator = target[method](...args);
  1122. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  1123. !isReadonly &&
  1124. track(rawTarget, "iterate" /* TrackOpTypes.ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
  1125. // return a wrapped iterator which returns observed versions of the
  1126. // values emitted from the real iterator
  1127. return {
  1128. // iterator protocol
  1129. next() {
  1130. const { value, done } = innerIterator.next();
  1131. return done
  1132. ? { value, done }
  1133. : {
  1134. value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
  1135. done
  1136. };
  1137. },
  1138. // iterable protocol
  1139. [Symbol.iterator]() {
  1140. return this;
  1141. }
  1142. };
  1143. };
  1144. }
  1145. function createReadonlyMethod(type) {
  1146. return function (...args) {
  1147. {
  1148. const key = args[0] ? `on key "${args[0]}" ` : ``;
  1149. console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
  1150. }
  1151. return type === "delete" /* TriggerOpTypes.DELETE */ ? false : this;
  1152. };
  1153. }
  1154. function createInstrumentations() {
  1155. const mutableInstrumentations = {
  1156. get(key) {
  1157. return get$1(this, key);
  1158. },
  1159. get size() {
  1160. return size(this);
  1161. },
  1162. has: has$1,
  1163. add,
  1164. set: set$1,
  1165. delete: deleteEntry,
  1166. clear,
  1167. forEach: createForEach(false, false)
  1168. };
  1169. const shallowInstrumentations = {
  1170. get(key) {
  1171. return get$1(this, key, false, true);
  1172. },
  1173. get size() {
  1174. return size(this);
  1175. },
  1176. has: has$1,
  1177. add,
  1178. set: set$1,
  1179. delete: deleteEntry,
  1180. clear,
  1181. forEach: createForEach(false, true)
  1182. };
  1183. const readonlyInstrumentations = {
  1184. get(key) {
  1185. return get$1(this, key, true);
  1186. },
  1187. get size() {
  1188. return size(this, true);
  1189. },
  1190. has(key) {
  1191. return has$1.call(this, key, true);
  1192. },
  1193. add: createReadonlyMethod("add" /* TriggerOpTypes.ADD */),
  1194. set: createReadonlyMethod("set" /* TriggerOpTypes.SET */),
  1195. delete: createReadonlyMethod("delete" /* TriggerOpTypes.DELETE */),
  1196. clear: createReadonlyMethod("clear" /* TriggerOpTypes.CLEAR */),
  1197. forEach: createForEach(true, false)
  1198. };
  1199. const shallowReadonlyInstrumentations = {
  1200. get(key) {
  1201. return get$1(this, key, true, true);
  1202. },
  1203. get size() {
  1204. return size(this, true);
  1205. },
  1206. has(key) {
  1207. return has$1.call(this, key, true);
  1208. },
  1209. add: createReadonlyMethod("add" /* TriggerOpTypes.ADD */),
  1210. set: createReadonlyMethod("set" /* TriggerOpTypes.SET */),
  1211. delete: createReadonlyMethod("delete" /* TriggerOpTypes.DELETE */),
  1212. clear: createReadonlyMethod("clear" /* TriggerOpTypes.CLEAR */),
  1213. forEach: createForEach(true, true)
  1214. };
  1215. const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
  1216. iteratorMethods.forEach(method => {
  1217. mutableInstrumentations[method] = createIterableMethod(method, false, false);
  1218. readonlyInstrumentations[method] = createIterableMethod(method, true, false);
  1219. shallowInstrumentations[method] = createIterableMethod(method, false, true);
  1220. shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
  1221. });
  1222. return [
  1223. mutableInstrumentations,
  1224. readonlyInstrumentations,
  1225. shallowInstrumentations,
  1226. shallowReadonlyInstrumentations
  1227. ];
  1228. }
  1229. const [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* #__PURE__*/ createInstrumentations();
  1230. function createInstrumentationGetter(isReadonly, shallow) {
  1231. const instrumentations = shallow
  1232. ? isReadonly
  1233. ? shallowReadonlyInstrumentations
  1234. : shallowInstrumentations
  1235. : isReadonly
  1236. ? readonlyInstrumentations
  1237. : mutableInstrumentations;
  1238. return (target, key, receiver) => {
  1239. if (key === "__v_isReactive" /* ReactiveFlags.IS_REACTIVE */) {
  1240. return !isReadonly;
  1241. }
  1242. else if (key === "__v_isReadonly" /* ReactiveFlags.IS_READONLY */) {
  1243. return isReadonly;
  1244. }
  1245. else if (key === "__v_raw" /* ReactiveFlags.RAW */) {
  1246. return target;
  1247. }
  1248. return Reflect.get(hasOwn(instrumentations, key) && key in target
  1249. ? instrumentations
  1250. : target, key, receiver);
  1251. };
  1252. }
  1253. const mutableCollectionHandlers = {
  1254. get: /*#__PURE__*/ createInstrumentationGetter(false, false)
  1255. };
  1256. const shallowCollectionHandlers = {
  1257. get: /*#__PURE__*/ createInstrumentationGetter(false, true)
  1258. };
  1259. const readonlyCollectionHandlers = {
  1260. get: /*#__PURE__*/ createInstrumentationGetter(true, false)
  1261. };
  1262. const shallowReadonlyCollectionHandlers = {
  1263. get: /*#__PURE__*/ createInstrumentationGetter(true, true)
  1264. };
  1265. function checkIdentityKeys(target, has, key) {
  1266. const rawKey = toRaw(key);
  1267. if (rawKey !== key && has.call(target, rawKey)) {
  1268. const type = toRawType(target);
  1269. console.warn(`Reactive ${type} contains both the raw and reactive ` +
  1270. `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
  1271. `which can lead to inconsistencies. ` +
  1272. `Avoid differentiating between the raw and reactive versions ` +
  1273. `of an object and only use the reactive version if possible.`);
  1274. }
  1275. }
  1276. const reactiveMap = new WeakMap();
  1277. const shallowReactiveMap = new WeakMap();
  1278. const readonlyMap = new WeakMap();
  1279. const shallowReadonlyMap = new WeakMap();
  1280. function targetTypeMap(rawType) {
  1281. switch (rawType) {
  1282. case 'Object':
  1283. case 'Array':
  1284. return 1 /* TargetType.COMMON */;
  1285. case 'Map':
  1286. case 'Set':
  1287. case 'WeakMap':
  1288. case 'WeakSet':
  1289. return 2 /* TargetType.COLLECTION */;
  1290. default:
  1291. return 0 /* TargetType.INVALID */;
  1292. }
  1293. }
  1294. function getTargetType(value) {
  1295. return value["__v_skip" /* ReactiveFlags.SKIP */] || !Object.isExtensible(value)
  1296. ? 0 /* TargetType.INVALID */
  1297. : targetTypeMap(toRawType(value));
  1298. }
  1299. function reactive(target) {
  1300. // if trying to observe a readonly proxy, return the readonly version.
  1301. if (isReadonly(target)) {
  1302. return target;
  1303. }
  1304. return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
  1305. }
  1306. /**
  1307. * Return a shallowly-reactive copy of the original object, where only the root
  1308. * level properties are reactive. It also does not auto-unwrap refs (even at the
  1309. * root level).
  1310. */
  1311. function shallowReactive(target) {
  1312. return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
  1313. }
  1314. /**
  1315. * Creates a readonly copy of the original object. Note the returned copy is not
  1316. * made reactive, but `readonly` can be called on an already reactive object.
  1317. */
  1318. function readonly(target) {
  1319. return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
  1320. }
  1321. /**
  1322. * Returns a reactive-copy of the original object, where only the root level
  1323. * properties are readonly, and does NOT unwrap refs nor recursively convert
  1324. * returned properties.
  1325. * This is used for creating the props proxy object for stateful components.
  1326. */
  1327. function shallowReadonly(target) {
  1328. return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
  1329. }
  1330. function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
  1331. if (!isObject(target)) {
  1332. {
  1333. console.warn(`value cannot be made reactive: ${String(target)}`);
  1334. }
  1335. return target;
  1336. }
  1337. // target is already a Proxy, return it.
  1338. // exception: calling readonly() on a reactive object
  1339. if (target["__v_raw" /* ReactiveFlags.RAW */] &&
  1340. !(isReadonly && target["__v_isReactive" /* ReactiveFlags.IS_REACTIVE */])) {
  1341. return target;
  1342. }
  1343. // target already has corresponding Proxy
  1344. const existingProxy = proxyMap.get(target);
  1345. if (existingProxy) {
  1346. return existingProxy;
  1347. }
  1348. // only specific value types can be observed.
  1349. const targetType = getTargetType(target);
  1350. if (targetType === 0 /* TargetType.INVALID */) {
  1351. return target;
  1352. }
  1353. const proxy = new Proxy(target, targetType === 2 /* TargetType.COLLECTION */ ? collectionHandlers : baseHandlers);
  1354. proxyMap.set(target, proxy);
  1355. return proxy;
  1356. }
  1357. function isReactive(value) {
  1358. if (isReadonly(value)) {
  1359. return isReactive(value["__v_raw" /* ReactiveFlags.RAW */]);
  1360. }
  1361. return !!(value && value["__v_isReactive" /* ReactiveFlags.IS_REACTIVE */]);
  1362. }
  1363. function isReadonly(value) {
  1364. return !!(value && value["__v_isReadonly" /* ReactiveFlags.IS_READONLY */]);
  1365. }
  1366. function isShallow(value) {
  1367. return !!(value && value["__v_isShallow" /* ReactiveFlags.IS_SHALLOW */]);
  1368. }
  1369. function isProxy(value) {
  1370. return isReactive(value) || isReadonly(value);
  1371. }
  1372. function toRaw(observed) {
  1373. const raw = observed && observed["__v_raw" /* ReactiveFlags.RAW */];
  1374. return raw ? toRaw(raw) : observed;
  1375. }
  1376. function markRaw(value) {
  1377. def(value, "__v_skip" /* ReactiveFlags.SKIP */, true);
  1378. return value;
  1379. }
  1380. const toReactive = (value) => isObject(value) ? reactive(value) : value;
  1381. const toReadonly = (value) => isObject(value) ? readonly(value) : value;
  1382. function trackRefValue(ref) {
  1383. if (shouldTrack && activeEffect) {
  1384. ref = toRaw(ref);
  1385. {
  1386. trackEffects(ref.dep || (ref.dep = createDep()), {
  1387. target: ref,
  1388. type: "get" /* TrackOpTypes.GET */,
  1389. key: 'value'
  1390. });
  1391. }
  1392. }
  1393. }
  1394. function triggerRefValue(ref, newVal) {
  1395. ref = toRaw(ref);
  1396. if (ref.dep) {
  1397. {
  1398. triggerEffects(ref.dep, {
  1399. target: ref,
  1400. type: "set" /* TriggerOpTypes.SET */,
  1401. key: 'value',
  1402. newValue: newVal
  1403. });
  1404. }
  1405. }
  1406. }
  1407. function isRef(r) {
  1408. return !!(r && r.__v_isRef === true);
  1409. }
  1410. function ref(value) {
  1411. return createRef(value, false);
  1412. }
  1413. function shallowRef(value) {
  1414. return createRef(value, true);
  1415. }
  1416. function createRef(rawValue, shallow) {
  1417. if (isRef(rawValue)) {
  1418. return rawValue;
  1419. }
  1420. return new RefImpl(rawValue, shallow);
  1421. }
  1422. class RefImpl {
  1423. constructor(value, __v_isShallow) {
  1424. this.__v_isShallow = __v_isShallow;
  1425. this.dep = undefined;
  1426. this.__v_isRef = true;
  1427. this._rawValue = __v_isShallow ? value : toRaw(value);
  1428. this._value = __v_isShallow ? value : toReactive(value);
  1429. }
  1430. get value() {
  1431. trackRefValue(this);
  1432. return this._value;
  1433. }
  1434. set value(newVal) {
  1435. const useDirectValue = this.__v_isShallow || isShallow(newVal) || isReadonly(newVal);
  1436. newVal = useDirectValue ? newVal : toRaw(newVal);
  1437. if (hasChanged(newVal, this._rawValue)) {
  1438. this._rawValue = newVal;
  1439. this._value = useDirectValue ? newVal : toReactive(newVal);
  1440. triggerRefValue(this, newVal);
  1441. }
  1442. }
  1443. }
  1444. function triggerRef(ref) {
  1445. triggerRefValue(ref, ref.value );
  1446. }
  1447. function unref(ref) {
  1448. return isRef(ref) ? ref.value : ref;
  1449. }
  1450. const shallowUnwrapHandlers = {
  1451. get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
  1452. set: (target, key, value, receiver) => {
  1453. const oldValue = target[key];
  1454. if (isRef(oldValue) && !isRef(value)) {
  1455. oldValue.value = value;
  1456. return true;
  1457. }
  1458. else {
  1459. return Reflect.set(target, key, value, receiver);
  1460. }
  1461. }
  1462. };
  1463. function proxyRefs(objectWithRefs) {
  1464. return isReactive(objectWithRefs)
  1465. ? objectWithRefs
  1466. : new Proxy(objectWithRefs, shallowUnwrapHandlers);
  1467. }
  1468. class CustomRefImpl {
  1469. constructor(factory) {
  1470. this.dep = undefined;
  1471. this.__v_isRef = true;
  1472. const { get, set } = factory(() => trackRefValue(this), () => triggerRefValue(this));
  1473. this._get = get;
  1474. this._set = set;
  1475. }
  1476. get value() {
  1477. return this._get();
  1478. }
  1479. set value(newVal) {
  1480. this._set(newVal);
  1481. }
  1482. }
  1483. function customRef(factory) {
  1484. return new CustomRefImpl(factory);
  1485. }
  1486. function toRefs(object) {
  1487. if (!isProxy(object)) {
  1488. console.warn(`toRefs() expects a reactive object but received a plain one.`);
  1489. }
  1490. const ret = isArray(object) ? new Array(object.length) : {};
  1491. for (const key in object) {
  1492. ret[key] = toRef(object, key);
  1493. }
  1494. return ret;
  1495. }
  1496. class ObjectRefImpl {
  1497. constructor(_object, _key, _defaultValue) {
  1498. this._object = _object;
  1499. this._key = _key;
  1500. this._defaultValue = _defaultValue;
  1501. this.__v_isRef = true;
  1502. }
  1503. get value() {
  1504. const val = this._object[this._key];
  1505. return val === undefined ? this._defaultValue : val;
  1506. }
  1507. set value(newVal) {
  1508. this._object[this._key] = newVal;
  1509. }
  1510. }
  1511. function toRef(object, key, defaultValue) {
  1512. const val = object[key];
  1513. return isRef(val)
  1514. ? val
  1515. : new ObjectRefImpl(object, key, defaultValue);
  1516. }
  1517. var _a;
  1518. class ComputedRefImpl {
  1519. constructor(getter, _setter, isReadonly, isSSR) {
  1520. this._setter = _setter;
  1521. this.dep = undefined;
  1522. this.__v_isRef = true;
  1523. this[_a] = false;
  1524. this._dirty = true;
  1525. this.effect = new ReactiveEffect(getter, () => {
  1526. if (!this._dirty) {
  1527. this._dirty = true;
  1528. triggerRefValue(this);
  1529. }
  1530. });
  1531. this.effect.computed = this;
  1532. this.effect.active = this._cacheable = !isSSR;
  1533. this["__v_isReadonly" /* ReactiveFlags.IS_READONLY */] = isReadonly;
  1534. }
  1535. get value() {
  1536. // the computed ref may get wrapped by other proxies e.g. readonly() #3376
  1537. const self = toRaw(this);
  1538. trackRefValue(self);
  1539. if (self._dirty || !self._cacheable) {
  1540. self._dirty = false;
  1541. self._value = self.effect.run();
  1542. }
  1543. return self._value;
  1544. }
  1545. set value(newValue) {
  1546. this._setter(newValue);
  1547. }
  1548. }
  1549. _a = "__v_isReadonly" /* ReactiveFlags.IS_READONLY */;
  1550. function computed(getterOrOptions, debugOptions, isSSR = false) {
  1551. let getter;
  1552. let setter;
  1553. const onlyGetter = isFunction(getterOrOptions);
  1554. if (onlyGetter) {
  1555. getter = getterOrOptions;
  1556. setter = () => {
  1557. console.warn('Write operation failed: computed value is readonly');
  1558. }
  1559. ;
  1560. }
  1561. else {
  1562. getter = getterOrOptions.get;
  1563. setter = getterOrOptions.set;
  1564. }
  1565. const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR);
  1566. if (debugOptions && !isSSR) {
  1567. cRef.effect.onTrack = debugOptions.onTrack;
  1568. cRef.effect.onTrigger = debugOptions.onTrigger;
  1569. }
  1570. return cRef;
  1571. }
  1572. const stack = [];
  1573. function pushWarningContext(vnode) {
  1574. stack.push(vnode);
  1575. }
  1576. function popWarningContext() {
  1577. stack.pop();
  1578. }
  1579. function warn$1(msg, ...args) {
  1580. // avoid props formatting or warn handler tracking deps that might be mutated
  1581. // during patch, leading to infinite recursion.
  1582. pauseTracking();
  1583. const instance = stack.length ? stack[stack.length - 1].component : null;
  1584. const appWarnHandler = instance && instance.appContext.config.warnHandler;
  1585. const trace = getComponentTrace();
  1586. if (appWarnHandler) {
  1587. callWithErrorHandling(appWarnHandler, instance, 11 /* ErrorCodes.APP_WARN_HANDLER */, [
  1588. msg + args.join(''),
  1589. instance && instance.proxy,
  1590. trace
  1591. .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
  1592. .join('\n'),
  1593. trace
  1594. ]);
  1595. }
  1596. else {
  1597. const warnArgs = [`[Vue warn]: ${msg}`, ...args];
  1598. /* istanbul ignore if */
  1599. if (trace.length &&
  1600. // avoid spamming console during tests
  1601. !false) {
  1602. warnArgs.push(`\n`, ...formatTrace(trace));
  1603. }
  1604. console.warn(...warnArgs);
  1605. }
  1606. resetTracking();
  1607. }
  1608. function getComponentTrace() {
  1609. let currentVNode = stack[stack.length - 1];
  1610. if (!currentVNode) {
  1611. return [];
  1612. }
  1613. // we can't just use the stack because it will be incomplete during updates
  1614. // that did not start from the root. Re-construct the parent chain using
  1615. // instance parent pointers.
  1616. const normalizedStack = [];
  1617. while (currentVNode) {
  1618. const last = normalizedStack[0];
  1619. if (last && last.vnode === currentVNode) {
  1620. last.recurseCount++;
  1621. }
  1622. else {
  1623. normalizedStack.push({
  1624. vnode: currentVNode,
  1625. recurseCount: 0
  1626. });
  1627. }
  1628. const parentInstance = currentVNode.component && currentVNode.component.parent;
  1629. currentVNode = parentInstance && parentInstance.vnode;
  1630. }
  1631. return normalizedStack;
  1632. }
  1633. /* istanbul ignore next */
  1634. function formatTrace(trace) {
  1635. const logs = [];
  1636. trace.forEach((entry, i) => {
  1637. logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
  1638. });
  1639. return logs;
  1640. }
  1641. function formatTraceEntry({ vnode, recurseCount }) {
  1642. const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
  1643. const isRoot = vnode.component ? vnode.component.parent == null : false;
  1644. const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
  1645. const close = `>` + postfix;
  1646. return vnode.props
  1647. ? [open, ...formatProps(vnode.props), close]
  1648. : [open + close];
  1649. }
  1650. /* istanbul ignore next */
  1651. function formatProps(props) {
  1652. const res = [];
  1653. const keys = Object.keys(props);
  1654. keys.slice(0, 3).forEach(key => {
  1655. res.push(...formatProp(key, props[key]));
  1656. });
  1657. if (keys.length > 3) {
  1658. res.push(` ...`);
  1659. }
  1660. return res;
  1661. }
  1662. /* istanbul ignore next */
  1663. function formatProp(key, value, raw) {
  1664. if (isString(value)) {
  1665. value = JSON.stringify(value);
  1666. return raw ? value : [`${key}=${value}`];
  1667. }
  1668. else if (typeof value === 'number' ||
  1669. typeof value === 'boolean' ||
  1670. value == null) {
  1671. return raw ? value : [`${key}=${value}`];
  1672. }
  1673. else if (isRef(value)) {
  1674. value = formatProp(key, toRaw(value.value), true);
  1675. return raw ? value : [`${key}=Ref<`, value, `>`];
  1676. }
  1677. else if (isFunction(value)) {
  1678. return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
  1679. }
  1680. else {
  1681. value = toRaw(value);
  1682. return raw ? value : [`${key}=`, value];
  1683. }
  1684. }
  1685. const ErrorTypeStrings = {
  1686. ["sp" /* LifecycleHooks.SERVER_PREFETCH */]: 'serverPrefetch hook',
  1687. ["bc" /* LifecycleHooks.BEFORE_CREATE */]: 'beforeCreate hook',
  1688. ["c" /* LifecycleHooks.CREATED */]: 'created hook',
  1689. ["bm" /* LifecycleHooks.BEFORE_MOUNT */]: 'beforeMount hook',
  1690. ["m" /* LifecycleHooks.MOUNTED */]: 'mounted hook',
  1691. ["bu" /* LifecycleHooks.BEFORE_UPDATE */]: 'beforeUpdate hook',
  1692. ["u" /* LifecycleHooks.UPDATED */]: 'updated',
  1693. ["bum" /* LifecycleHooks.BEFORE_UNMOUNT */]: 'beforeUnmount hook',
  1694. ["um" /* LifecycleHooks.UNMOUNTED */]: 'unmounted hook',
  1695. ["a" /* LifecycleHooks.ACTIVATED */]: 'activated hook',
  1696. ["da" /* LifecycleHooks.DEACTIVATED */]: 'deactivated hook',
  1697. ["ec" /* LifecycleHooks.ERROR_CAPTURED */]: 'errorCaptured hook',
  1698. ["rtc" /* LifecycleHooks.RENDER_TRACKED */]: 'renderTracked hook',
  1699. ["rtg" /* LifecycleHooks.RENDER_TRIGGERED */]: 'renderTriggered hook',
  1700. [0 /* ErrorCodes.SETUP_FUNCTION */]: 'setup function',
  1701. [1 /* ErrorCodes.RENDER_FUNCTION */]: 'render function',
  1702. [2 /* ErrorCodes.WATCH_GETTER */]: 'watcher getter',
  1703. [3 /* ErrorCodes.WATCH_CALLBACK */]: 'watcher callback',
  1704. [4 /* ErrorCodes.WATCH_CLEANUP */]: 'watcher cleanup function',
  1705. [5 /* ErrorCodes.NATIVE_EVENT_HANDLER */]: 'native event handler',
  1706. [6 /* ErrorCodes.COMPONENT_EVENT_HANDLER */]: 'component event handler',
  1707. [7 /* ErrorCodes.VNODE_HOOK */]: 'vnode hook',
  1708. [8 /* ErrorCodes.DIRECTIVE_HOOK */]: 'directive hook',
  1709. [9 /* ErrorCodes.TRANSITION_HOOK */]: 'transition hook',
  1710. [10 /* ErrorCodes.APP_ERROR_HANDLER */]: 'app errorHandler',
  1711. [11 /* ErrorCodes.APP_WARN_HANDLER */]: 'app warnHandler',
  1712. [12 /* ErrorCodes.FUNCTION_REF */]: 'ref function',
  1713. [13 /* ErrorCodes.ASYNC_COMPONENT_LOADER */]: 'async component loader',
  1714. [14 /* ErrorCodes.SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
  1715. 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core'
  1716. };
  1717. function callWithErrorHandling(fn, instance, type, args) {
  1718. let res;
  1719. try {
  1720. res = args ? fn(...args) : fn();
  1721. }
  1722. catch (err) {
  1723. handleError(err, instance, type);
  1724. }
  1725. return res;
  1726. }
  1727. function callWithAsyncErrorHandling(fn, instance, type, args) {
  1728. if (isFunction(fn)) {
  1729. const res = callWithErrorHandling(fn, instance, type, args);
  1730. if (res && isPromise(res)) {
  1731. res.catch(err => {
  1732. handleError(err, instance, type);
  1733. });
  1734. }
  1735. return res;
  1736. }
  1737. const values = [];
  1738. for (let i = 0; i < fn.length; i++) {
  1739. values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
  1740. }
  1741. return values;
  1742. }
  1743. function handleError(err, instance, type, throwInDev = true) {
  1744. const contextVNode = instance ? instance.vnode : null;
  1745. if (instance) {
  1746. let cur = instance.parent;
  1747. // the exposed instance is the render proxy to keep it consistent with 2.x
  1748. const exposedInstance = instance.proxy;
  1749. // in production the hook receives only the error code
  1750. const errorInfo = ErrorTypeStrings[type] ;
  1751. while (cur) {
  1752. const errorCapturedHooks = cur.ec;
  1753. if (errorCapturedHooks) {
  1754. for (let i = 0; i < errorCapturedHooks.length; i++) {
  1755. if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
  1756. return;
  1757. }
  1758. }
  1759. }
  1760. cur = cur.parent;
  1761. }
  1762. // app-level handling
  1763. const appErrorHandler = instance.appContext.config.errorHandler;
  1764. if (appErrorHandler) {
  1765. callWithErrorHandling(appErrorHandler, null, 10 /* ErrorCodes.APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
  1766. return;
  1767. }
  1768. }
  1769. logError(err, type, contextVNode, throwInDev);
  1770. }
  1771. function logError(err, type, contextVNode, throwInDev = true) {
  1772. {
  1773. const info = ErrorTypeStrings[type];
  1774. if (contextVNode) {
  1775. pushWarningContext(contextVNode);
  1776. }
  1777. warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
  1778. if (contextVNode) {
  1779. popWarningContext();
  1780. }
  1781. // crash in dev by default so it's more noticeable
  1782. if (throwInDev) {
  1783. throw err;
  1784. }
  1785. else {
  1786. console.error(err);
  1787. }
  1788. }
  1789. }
  1790. let isFlushing = false;
  1791. let isFlushPending = false;
  1792. const queue = [];
  1793. let flushIndex = 0;
  1794. const pendingPostFlushCbs = [];
  1795. let activePostFlushCbs = null;
  1796. let postFlushIndex = 0;
  1797. const resolvedPromise = /*#__PURE__*/ Promise.resolve();
  1798. let currentFlushPromise = null;
  1799. const RECURSION_LIMIT = 100;
  1800. function nextTick(fn) {
  1801. const p = currentFlushPromise || resolvedPromise;
  1802. return fn ? p.then(this ? fn.bind(this) : fn) : p;
  1803. }
  1804. // #2768
  1805. // Use binary-search to find a suitable position in the queue,
  1806. // so that the queue maintains the increasing order of job's id,
  1807. // which can prevent the job from being skipped and also can avoid repeated patching.
  1808. function findInsertionIndex(id) {
  1809. // the start index should be `flushIndex + 1`
  1810. let start = flushIndex + 1;
  1811. let end = queue.length;
  1812. while (start < end) {
  1813. const middle = (start + end) >>> 1;
  1814. const middleJobId = getId(queue[middle]);
  1815. middleJobId < id ? (start = middle + 1) : (end = middle);
  1816. }
  1817. return start;
  1818. }
  1819. function queueJob(job) {
  1820. // the dedupe search uses the startIndex argument of Array.includes()
  1821. // by default the search index includes the current job that is being run
  1822. // so it cannot recursively trigger itself again.
  1823. // if the job is a watch() callback, the search will start with a +1 index to
  1824. // allow it recursively trigger itself - it is the user's responsibility to
  1825. // ensure it doesn't end up in an infinite loop.
  1826. if (!queue.length ||
  1827. !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) {
  1828. if (job.id == null) {
  1829. queue.push(job);
  1830. }
  1831. else {
  1832. queue.splice(findInsertionIndex(job.id), 0, job);
  1833. }
  1834. queueFlush();
  1835. }
  1836. }
  1837. function queueFlush() {
  1838. if (!isFlushing && !isFlushPending) {
  1839. isFlushPending = true;
  1840. currentFlushPromise = resolvedPromise.then(flushJobs);
  1841. }
  1842. }
  1843. function invalidateJob(job) {
  1844. const i = queue.indexOf(job);
  1845. if (i > flushIndex) {
  1846. queue.splice(i, 1);
  1847. }
  1848. }
  1849. function queuePostFlushCb(cb) {
  1850. if (!isArray(cb)) {
  1851. if (!activePostFlushCbs ||
  1852. !activePostFlushCbs.includes(cb, cb.allowRecurse ? postFlushIndex + 1 : postFlushIndex)) {
  1853. pendingPostFlushCbs.push(cb);
  1854. }
  1855. }
  1856. else {
  1857. // if cb is an array, it is a component lifecycle hook which can only be
  1858. // triggered by a job, which is already deduped in the main queue, so
  1859. // we can skip duplicate check here to improve perf
  1860. pendingPostFlushCbs.push(...cb);
  1861. }
  1862. queueFlush();
  1863. }
  1864. function flushPreFlushCbs(seen,
  1865. // if currently flushing, skip the current job itself
  1866. i = isFlushing ? flushIndex + 1 : 0) {
  1867. {
  1868. seen = seen || new Map();
  1869. }
  1870. for (; i < queue.length; i++) {
  1871. const cb = queue[i];
  1872. if (cb && cb.pre) {
  1873. if (checkRecursiveUpdates(seen, cb)) {
  1874. continue;
  1875. }
  1876. queue.splice(i, 1);
  1877. i--;
  1878. cb();
  1879. }
  1880. }
  1881. }
  1882. function flushPostFlushCbs(seen) {
  1883. if (pendingPostFlushCbs.length) {
  1884. const deduped = [...new Set(pendingPostFlushCbs)];
  1885. pendingPostFlushCbs.length = 0;
  1886. // #1947 already has active queue, nested flushPostFlushCbs call
  1887. if (activePostFlushCbs) {
  1888. activePostFlushCbs.push(...deduped);
  1889. return;
  1890. }
  1891. activePostFlushCbs = deduped;
  1892. {
  1893. seen = seen || new Map();
  1894. }
  1895. activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
  1896. for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
  1897. if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) {
  1898. continue;
  1899. }
  1900. activePostFlushCbs[postFlushIndex]();
  1901. }
  1902. activePostFlushCbs = null;
  1903. postFlushIndex = 0;
  1904. }
  1905. }
  1906. const getId = (job) => job.id == null ? Infinity : job.id;
  1907. const comparator = (a, b) => {
  1908. const diff = getId(a) - getId(b);
  1909. if (diff === 0) {
  1910. if (a.pre && !b.pre)
  1911. return -1;
  1912. if (b.pre && !a.pre)
  1913. return 1;
  1914. }
  1915. return diff;
  1916. };
  1917. function flushJobs(seen) {
  1918. isFlushPending = false;
  1919. isFlushing = true;
  1920. {
  1921. seen = seen || new Map();
  1922. }
  1923. // Sort queue before flush.
  1924. // This ensures that:
  1925. // 1. Components are updated from parent to child. (because parent is always
  1926. // created before the child so its render effect will have smaller
  1927. // priority number)
  1928. // 2. If a component is unmounted during a parent component's update,
  1929. // its update can be skipped.
  1930. queue.sort(comparator);
  1931. // conditional usage of checkRecursiveUpdate must be determined out of
  1932. // try ... catch block since Rollup by default de-optimizes treeshaking
  1933. // inside try-catch. This can leave all warning code unshaked. Although
  1934. // they would get eventually shaken by a minifier like terser, some minifiers
  1935. // would fail to do that (e.g. https://github.com/evanw/esbuild/issues/1610)
  1936. const check = (job) => checkRecursiveUpdates(seen, job)
  1937. ;
  1938. try {
  1939. for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
  1940. const job = queue[flushIndex];
  1941. if (job && job.active !== false) {
  1942. if (true && check(job)) {
  1943. continue;
  1944. }
  1945. // console.log(`running:`, job.id)
  1946. callWithErrorHandling(job, null, 14 /* ErrorCodes.SCHEDULER */);
  1947. }
  1948. }
  1949. }
  1950. finally {
  1951. flushIndex = 0;
  1952. queue.length = 0;
  1953. flushPostFlushCbs(seen);
  1954. isFlushing = false;
  1955. currentFlushPromise = null;
  1956. // some postFlushCb queued jobs!
  1957. // keep flushing until it drains.
  1958. if (queue.length || pendingPostFlushCbs.length) {
  1959. flushJobs(seen);
  1960. }
  1961. }
  1962. }
  1963. function checkRecursiveUpdates(seen, fn) {
  1964. if (!seen.has(fn)) {
  1965. seen.set(fn, 1);
  1966. }
  1967. else {
  1968. const count = seen.get(fn);
  1969. if (count > RECURSION_LIMIT) {
  1970. const instance = fn.ownerInstance;
  1971. const componentName = instance && getComponentName(instance.type);
  1972. warn$1(`Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. ` +
  1973. `This means you have a reactive effect that is mutating its own ` +
  1974. `dependencies and thus recursively triggering itself. Possible sources ` +
  1975. `include component template, render function, updated hook or ` +
  1976. `watcher source function.`);
  1977. return true;
  1978. }
  1979. else {
  1980. seen.set(fn, count + 1);
  1981. }
  1982. }
  1983. }
  1984. /* eslint-disable no-restricted-globals */
  1985. let isHmrUpdating = false;
  1986. const hmrDirtyComponents = new Set();
  1987. // Expose the HMR runtime on the global object
  1988. // This makes it entirely tree-shakable without polluting the exports and makes
  1989. // it easier to be used in toolings like vue-loader
  1990. // Note: for a component to be eligible for HMR it also needs the __hmrId option
  1991. // to be set so that its instances can be registered / removed.
  1992. {
  1993. getGlobalThis().__VUE_HMR_RUNTIME__ = {
  1994. createRecord: tryWrap(createRecord),
  1995. rerender: tryWrap(rerender),
  1996. reload: tryWrap(reload)
  1997. };
  1998. }
  1999. const map = new Map();
  2000. function registerHMR(instance) {
  2001. const id = instance.type.__hmrId;
  2002. let record = map.get(id);
  2003. if (!record) {
  2004. createRecord(id, instance.type);
  2005. record = map.get(id);
  2006. }
  2007. record.instances.add(instance);
  2008. }
  2009. function unregisterHMR(instance) {
  2010. map.get(instance.type.__hmrId).instances.delete(instance);
  2011. }
  2012. function createRecord(id, initialDef) {
  2013. if (map.has(id)) {
  2014. return false;
  2015. }
  2016. map.set(id, {
  2017. initialDef: normalizeClassComponent(initialDef),
  2018. instances: new Set()
  2019. });
  2020. return true;
  2021. }
  2022. function normalizeClassComponent(component) {
  2023. return isClassComponent(component) ? component.__vccOpts : component;
  2024. }
  2025. function rerender(id, newRender) {
  2026. const record = map.get(id);
  2027. if (!record) {
  2028. return;
  2029. }
  2030. // update initial record (for not-yet-rendered component)
  2031. record.initialDef.render = newRender;
  2032. [...record.instances].forEach(instance => {
  2033. if (newRender) {
  2034. instance.render = newRender;
  2035. normalizeClassComponent(instance.type).render = newRender;
  2036. }
  2037. instance.renderCache = [];
  2038. // this flag forces child components with slot content to update
  2039. isHmrUpdating = true;
  2040. instance.update();
  2041. isHmrUpdating = false;
  2042. });
  2043. }
  2044. function reload(id, newComp) {
  2045. const record = map.get(id);
  2046. if (!record)
  2047. return;
  2048. newComp = normalizeClassComponent(newComp);
  2049. // update initial def (for not-yet-rendered components)
  2050. updateComponentDef(record.initialDef, newComp);
  2051. // create a snapshot which avoids the set being mutated during updates
  2052. const instances = [...record.instances];
  2053. for (const instance of instances) {
  2054. const oldComp = normalizeClassComponent(instance.type);
  2055. if (!hmrDirtyComponents.has(oldComp)) {
  2056. // 1. Update existing comp definition to match new one
  2057. if (oldComp !== record.initialDef) {
  2058. updateComponentDef(oldComp, newComp);
  2059. }
  2060. // 2. mark definition dirty. This forces the renderer to replace the
  2061. // component on patch.
  2062. hmrDirtyComponents.add(oldComp);
  2063. }
  2064. // 3. invalidate options resolution cache
  2065. instance.appContext.optionsCache.delete(instance.type);
  2066. // 4. actually update
  2067. if (instance.ceReload) {
  2068. // custom element
  2069. hmrDirtyComponents.add(oldComp);
  2070. instance.ceReload(newComp.styles);
  2071. hmrDirtyComponents.delete(oldComp);
  2072. }
  2073. else if (instance.parent) {
  2074. // 4. Force the parent instance to re-render. This will cause all updated
  2075. // components to be unmounted and re-mounted. Queue the update so that we
  2076. // don't end up forcing the same parent to re-render multiple times.
  2077. queueJob(instance.parent.update);
  2078. }
  2079. else if (instance.appContext.reload) {
  2080. // root instance mounted via createApp() has a reload method
  2081. instance.appContext.reload();
  2082. }
  2083. else if (typeof window !== 'undefined') {
  2084. // root instance inside tree created via raw render(). Force reload.
  2085. window.location.reload();
  2086. }
  2087. else {
  2088. console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
  2089. }
  2090. }
  2091. // 5. make sure to cleanup dirty hmr components after update
  2092. queuePostFlushCb(() => {
  2093. for (const instance of instances) {
  2094. hmrDirtyComponents.delete(normalizeClassComponent(instance.type));
  2095. }
  2096. });
  2097. }
  2098. function updateComponentDef(oldComp, newComp) {
  2099. extend(oldComp, newComp);
  2100. for (const key in oldComp) {
  2101. if (key !== '__file' && !(key in newComp)) {
  2102. delete oldComp[key];
  2103. }
  2104. }
  2105. }
  2106. function tryWrap(fn) {
  2107. return (id, arg) => {
  2108. try {
  2109. return fn(id, arg);
  2110. }
  2111. catch (e) {
  2112. console.error(e);
  2113. console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
  2114. `Full reload required.`);
  2115. }
  2116. };
  2117. }
  2118. let devtools;
  2119. let buffer = [];
  2120. let devtoolsNotInstalled = false;
  2121. function emit(event, ...args) {
  2122. if (devtools) {
  2123. devtools.emit(event, ...args);
  2124. }
  2125. else if (!devtoolsNotInstalled) {
  2126. buffer.push({ event, args });
  2127. }
  2128. }
  2129. function setDevtoolsHook(hook, target) {
  2130. var _a, _b;
  2131. devtools = hook;
  2132. if (devtools) {
  2133. devtools.enabled = true;
  2134. buffer.forEach(({ event, args }) => devtools.emit(event, ...args));
  2135. buffer = [];
  2136. }
  2137. else if (
  2138. // handle late devtools injection - only do this if we are in an actual
  2139. // browser environment to avoid the timer handle stalling test runner exit
  2140. // (#4815)
  2141. typeof window !== 'undefined' &&
  2142. // some envs mock window but not fully
  2143. window.HTMLElement &&
  2144. // also exclude jsdom
  2145. !((_b = (_a = window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent) === null || _b === void 0 ? void 0 : _b.includes('jsdom'))) {
  2146. const replay = (target.__VUE_DEVTOOLS_HOOK_REPLAY__ =
  2147. target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []);
  2148. replay.push((newHook) => {
  2149. setDevtoolsHook(newHook, target);
  2150. });
  2151. // clear buffer after 3s - the user probably doesn't have devtools installed
  2152. // at all, and keeping the buffer will cause memory leaks (#4738)
  2153. setTimeout(() => {
  2154. if (!devtools) {
  2155. target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null;
  2156. devtoolsNotInstalled = true;
  2157. buffer = [];
  2158. }
  2159. }, 3000);
  2160. }
  2161. else {
  2162. // non-browser env, assume not installed
  2163. devtoolsNotInstalled = true;
  2164. buffer = [];
  2165. }
  2166. }
  2167. function devtoolsInitApp(app, version) {
  2168. emit("app:init" /* DevtoolsHooks.APP_INIT */, app, version, {
  2169. Fragment,
  2170. Text,
  2171. Comment,
  2172. Static
  2173. });
  2174. }
  2175. function devtoolsUnmountApp(app) {
  2176. emit("app:unmount" /* DevtoolsHooks.APP_UNMOUNT */, app);
  2177. }
  2178. const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* DevtoolsHooks.COMPONENT_ADDED */);
  2179. const devtoolsComponentUpdated =
  2180. /*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* DevtoolsHooks.COMPONENT_UPDATED */);
  2181. const _devtoolsComponentRemoved = /*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* DevtoolsHooks.COMPONENT_REMOVED */);
  2182. const devtoolsComponentRemoved = (component) => {
  2183. if (devtools &&
  2184. typeof devtools.cleanupBuffer === 'function' &&
  2185. // remove the component if it wasn't buffered
  2186. !devtools.cleanupBuffer(component)) {
  2187. _devtoolsComponentRemoved(component);
  2188. }
  2189. };
  2190. function createDevtoolsComponentHook(hook) {
  2191. return (component) => {
  2192. emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
  2193. };
  2194. }
  2195. const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:start" /* DevtoolsHooks.PERFORMANCE_START */);
  2196. const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:end" /* DevtoolsHooks.PERFORMANCE_END */);
  2197. function createDevtoolsPerformanceHook(hook) {
  2198. return (component, type, time) => {
  2199. emit(hook, component.appContext.app, component.uid, component, type, time);
  2200. };
  2201. }
  2202. function devtoolsComponentEmit(component, event, params) {
  2203. emit("component:emit" /* DevtoolsHooks.COMPONENT_EMIT */, component.appContext.app, component, event, params);
  2204. }
  2205. function emit$1(instance, event, ...rawArgs) {
  2206. if (instance.isUnmounted)
  2207. return;
  2208. const props = instance.vnode.props || EMPTY_OBJ;
  2209. {
  2210. const { emitsOptions, propsOptions: [propsOptions] } = instance;
  2211. if (emitsOptions) {
  2212. if (!(event in emitsOptions) &&
  2213. !(false )) {
  2214. if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
  2215. warn$1(`Component emitted event "${event}" but it is neither declared in ` +
  2216. `the emits option nor as an "${toHandlerKey(event)}" prop.`);
  2217. }
  2218. }
  2219. else {
  2220. const validator = emitsOptions[event];
  2221. if (isFunction(validator)) {
  2222. const isValid = validator(...rawArgs);
  2223. if (!isValid) {
  2224. warn$1(`Invalid event arguments: event validation failed for event "${event}".`);
  2225. }
  2226. }
  2227. }
  2228. }
  2229. }
  2230. let args = rawArgs;
  2231. const isModelListener = event.startsWith('update:');
  2232. // for v-model update:xxx events, apply modifiers on args
  2233. const modelArg = isModelListener && event.slice(7);
  2234. if (modelArg && modelArg in props) {
  2235. const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
  2236. const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
  2237. if (trim) {
  2238. args = rawArgs.map(a => (isString(a) ? a.trim() : a));
  2239. }
  2240. if (number) {
  2241. args = rawArgs.map(toNumber);
  2242. }
  2243. }
  2244. {
  2245. devtoolsComponentEmit(instance, event, args);
  2246. }
  2247. {
  2248. const lowerCaseEvent = event.toLowerCase();
  2249. if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
  2250. warn$1(`Event "${lowerCaseEvent}" is emitted in component ` +
  2251. `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
  2252. `Note that HTML attributes are case-insensitive and you cannot use ` +
  2253. `v-on to listen to camelCase events when using in-DOM templates. ` +
  2254. `You should probably use "${hyphenate(event)}" instead of "${event}".`);
  2255. }
  2256. }
  2257. let handlerName;
  2258. let handler = props[(handlerName = toHandlerKey(event))] ||
  2259. // also try camelCase event handler (#2249)
  2260. props[(handlerName = toHandlerKey(camelize(event)))];
  2261. // for v-model update:xxx events, also trigger kebab-case equivalent
  2262. // for props passed via kebab-case
  2263. if (!handler && isModelListener) {
  2264. handler = props[(handlerName = toHandlerKey(hyphenate(event)))];
  2265. }
  2266. if (handler) {
  2267. callWithAsyncErrorHandling(handler, instance, 6 /* ErrorCodes.COMPONENT_EVENT_HANDLER */, args);
  2268. }
  2269. const onceHandler = props[handlerName + `Once`];
  2270. if (onceHandler) {
  2271. if (!instance.emitted) {
  2272. instance.emitted = {};
  2273. }
  2274. else if (instance.emitted[handlerName]) {
  2275. return;
  2276. }
  2277. instance.emitted[handlerName] = true;
  2278. callWithAsyncErrorHandling(onceHandler, instance, 6 /* ErrorCodes.COMPONENT_EVENT_HANDLER */, args);
  2279. }
  2280. }
  2281. function normalizeEmitsOptions(comp, appContext, asMixin = false) {
  2282. const cache = appContext.emitsCache;
  2283. const cached = cache.get(comp);
  2284. if (cached !== undefined) {
  2285. return cached;
  2286. }
  2287. const raw = comp.emits;
  2288. let normalized = {};
  2289. // apply mixin/extends props
  2290. let hasExtends = false;
  2291. if (!isFunction(comp)) {
  2292. const extendEmits = (raw) => {
  2293. const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true);
  2294. if (normalizedFromExtend) {
  2295. hasExtends = true;
  2296. extend(normalized, normalizedFromExtend);
  2297. }
  2298. };
  2299. if (!asMixin && appContext.mixins.length) {
  2300. appContext.mixins.forEach(extendEmits);
  2301. }
  2302. if (comp.extends) {
  2303. extendEmits(comp.extends);
  2304. }
  2305. if (comp.mixins) {
  2306. comp.mixins.forEach(extendEmits);
  2307. }
  2308. }
  2309. if (!raw && !hasExtends) {
  2310. if (isObject(comp)) {
  2311. cache.set(comp, null);
  2312. }
  2313. return null;
  2314. }
  2315. if (isArray(raw)) {
  2316. raw.forEach(key => (normalized[key] = null));
  2317. }
  2318. else {
  2319. extend(normalized, raw);
  2320. }
  2321. if (isObject(comp)) {
  2322. cache.set(comp, normalized);
  2323. }
  2324. return normalized;
  2325. }
  2326. // Check if an incoming prop key is a declared emit event listener.
  2327. // e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
  2328. // both considered matched listeners.
  2329. function isEmitListener(options, key) {
  2330. if (!options || !isOn(key)) {
  2331. return false;
  2332. }
  2333. key = key.slice(2).replace(/Once$/, '');
  2334. return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
  2335. hasOwn(options, hyphenate(key)) ||
  2336. hasOwn(options, key));
  2337. }
  2338. /**
  2339. * mark the current rendering instance for asset resolution (e.g.
  2340. * resolveComponent, resolveDirective) during render
  2341. */
  2342. let currentRenderingInstance = null;
  2343. let currentScopeId = null;
  2344. /**
  2345. * Note: rendering calls maybe nested. The function returns the parent rendering
  2346. * instance if present, which should be restored after the render is done:
  2347. *
  2348. * ```js
  2349. * const prev = setCurrentRenderingInstance(i)
  2350. * // ...render
  2351. * setCurrentRenderingInstance(prev)
  2352. * ```
  2353. */
  2354. function setCurrentRenderingInstance(instance) {
  2355. const prev = currentRenderingInstance;
  2356. currentRenderingInstance = instance;
  2357. currentScopeId = (instance && instance.type.__scopeId) || null;
  2358. return prev;
  2359. }
  2360. /**
  2361. * Set scope id when creating hoisted vnodes.
  2362. * @private compiler helper
  2363. */
  2364. function pushScopeId(id) {
  2365. currentScopeId = id;
  2366. }
  2367. /**
  2368. * Technically we no longer need this after 3.0.8 but we need to keep the same
  2369. * API for backwards compat w/ code generated by compilers.
  2370. * @private
  2371. */
  2372. function popScopeId() {
  2373. currentScopeId = null;
  2374. }
  2375. /**
  2376. * Only for backwards compat
  2377. * @private
  2378. */
  2379. const withScopeId = (_id) => withCtx;
  2380. /**
  2381. * Wrap a slot function to memoize current rendering instance
  2382. * @private compiler helper
  2383. */
  2384. function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot // false only
  2385. ) {
  2386. if (!ctx)
  2387. return fn;
  2388. // already normalized
  2389. if (fn._n) {
  2390. return fn;
  2391. }
  2392. const renderFnWithContext = (...args) => {
  2393. // If a user calls a compiled slot inside a template expression (#1745), it
  2394. // can mess up block tracking, so by default we disable block tracking and
  2395. // force bail out when invoking a compiled slot (indicated by the ._d flag).
  2396. // This isn't necessary if rendering a compiled `<slot>`, so we flip the
  2397. // ._d flag off when invoking the wrapped fn inside `renderSlot`.
  2398. if (renderFnWithContext._d) {
  2399. setBlockTracking(-1);
  2400. }
  2401. const prevInstance = setCurrentRenderingInstance(ctx);
  2402. let res;
  2403. try {
  2404. res = fn(...args);
  2405. }
  2406. finally {
  2407. setCurrentRenderingInstance(prevInstance);
  2408. if (renderFnWithContext._d) {
  2409. setBlockTracking(1);
  2410. }
  2411. }
  2412. {
  2413. devtoolsComponentUpdated(ctx);
  2414. }
  2415. return res;
  2416. };
  2417. // mark normalized to avoid duplicated wrapping
  2418. renderFnWithContext._n = true;
  2419. // mark this as compiled by default
  2420. // this is used in vnode.ts -> normalizeChildren() to set the slot
  2421. // rendering flag.
  2422. renderFnWithContext._c = true;
  2423. // disable block tracking by default
  2424. renderFnWithContext._d = true;
  2425. return renderFnWithContext;
  2426. }
  2427. /**
  2428. * dev only flag to track whether $attrs was used during render.
  2429. * If $attrs was used during render then the warning for failed attrs
  2430. * fallthrough can be suppressed.
  2431. */
  2432. let accessedAttrs = false;
  2433. function markAttrsAccessed() {
  2434. accessedAttrs = true;
  2435. }
  2436. function renderComponentRoot(instance) {
  2437. const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx, inheritAttrs } = instance;
  2438. let result;
  2439. let fallthroughAttrs;
  2440. const prev = setCurrentRenderingInstance(instance);
  2441. {
  2442. accessedAttrs = false;
  2443. }
  2444. try {
  2445. if (vnode.shapeFlag & 4 /* ShapeFlags.STATEFUL_COMPONENT */) {
  2446. // withProxy is a proxy with a different `has` trap only for
  2447. // runtime-compiled render functions using `with` block.
  2448. const proxyToUse = withProxy || proxy;
  2449. result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
  2450. fallthroughAttrs = attrs;
  2451. }
  2452. else {
  2453. // functional
  2454. const render = Component;
  2455. // in dev, mark attrs accessed if optional props (attrs === props)
  2456. if (true && attrs === props) {
  2457. markAttrsAccessed();
  2458. }
  2459. result = normalizeVNode(render.length > 1
  2460. ? render(props, true
  2461. ? {
  2462. get attrs() {
  2463. markAttrsAccessed();
  2464. return attrs;
  2465. },
  2466. slots,
  2467. emit
  2468. }
  2469. : { attrs, slots, emit })
  2470. : render(props, null /* we know it doesn't need it */));
  2471. fallthroughAttrs = Component.props
  2472. ? attrs
  2473. : getFunctionalFallthrough(attrs);
  2474. }
  2475. }
  2476. catch (err) {
  2477. blockStack.length = 0;
  2478. handleError(err, instance, 1 /* ErrorCodes.RENDER_FUNCTION */);
  2479. result = createVNode(Comment);
  2480. }
  2481. // attr merging
  2482. // in dev mode, comments are preserved, and it's possible for a template
  2483. // to have comments along side the root element which makes it a fragment
  2484. let root = result;
  2485. let setRoot = undefined;
  2486. if (result.patchFlag > 0 &&
  2487. result.patchFlag & 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */) {
  2488. [root, setRoot] = getChildRoot(result);
  2489. }
  2490. if (fallthroughAttrs && inheritAttrs !== false) {
  2491. const keys = Object.keys(fallthroughAttrs);
  2492. const { shapeFlag } = root;
  2493. if (keys.length) {
  2494. if (shapeFlag & (1 /* ShapeFlags.ELEMENT */ | 6 /* ShapeFlags.COMPONENT */)) {
  2495. if (propsOptions && keys.some(isModelListener)) {
  2496. // If a v-model listener (onUpdate:xxx) has a corresponding declared
  2497. // prop, it indicates this component expects to handle v-model and
  2498. // it should not fallthrough.
  2499. // related: #1543, #1643, #1989
  2500. fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
  2501. }
  2502. root = cloneVNode(root, fallthroughAttrs);
  2503. }
  2504. else if (!accessedAttrs && root.type !== Comment) {
  2505. const allAttrs = Object.keys(attrs);
  2506. const eventAttrs = [];
  2507. const extraAttrs = [];
  2508. for (let i = 0, l = allAttrs.length; i < l; i++) {
  2509. const key = allAttrs[i];
  2510. if (isOn(key)) {
  2511. // ignore v-model handlers when they fail to fallthrough
  2512. if (!isModelListener(key)) {
  2513. // remove `on`, lowercase first letter to reflect event casing
  2514. // accurately
  2515. eventAttrs.push(key[2].toLowerCase() + key.slice(3));
  2516. }
  2517. }
  2518. else {
  2519. extraAttrs.push(key);
  2520. }
  2521. }
  2522. if (extraAttrs.length) {
  2523. warn$1(`Extraneous non-props attributes (` +
  2524. `${extraAttrs.join(', ')}) ` +
  2525. `were passed to component but could not be automatically inherited ` +
  2526. `because component renders fragment or text root nodes.`);
  2527. }
  2528. if (eventAttrs.length) {
  2529. warn$1(`Extraneous non-emits event listeners (` +
  2530. `${eventAttrs.join(', ')}) ` +
  2531. `were passed to component but could not be automatically inherited ` +
  2532. `because component renders fragment or text root nodes. ` +
  2533. `If the listener is intended to be a component custom event listener only, ` +
  2534. `declare it using the "emits" option.`);
  2535. }
  2536. }
  2537. }
  2538. }
  2539. // inherit directives
  2540. if (vnode.dirs) {
  2541. if (!isElementRoot(root)) {
  2542. warn$1(`Runtime directive used on component with non-element root node. ` +
  2543. `The directives will not function as intended.`);
  2544. }
  2545. // clone before mutating since the root may be a hoisted vnode
  2546. root = cloneVNode(root);
  2547. root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
  2548. }
  2549. // inherit transition data
  2550. if (vnode.transition) {
  2551. if (!isElementRoot(root)) {
  2552. warn$1(`Component inside <Transition> renders non-element root node ` +
  2553. `that cannot be animated.`);
  2554. }
  2555. root.transition = vnode.transition;
  2556. }
  2557. if (setRoot) {
  2558. setRoot(root);
  2559. }
  2560. else {
  2561. result = root;
  2562. }
  2563. setCurrentRenderingInstance(prev);
  2564. return result;
  2565. }
  2566. /**
  2567. * dev only
  2568. * In dev mode, template root level comments are rendered, which turns the
  2569. * template into a fragment root, but we need to locate the single element
  2570. * root for attrs and scope id processing.
  2571. */
  2572. const getChildRoot = (vnode) => {
  2573. const rawChildren = vnode.children;
  2574. const dynamicChildren = vnode.dynamicChildren;
  2575. const childRoot = filterSingleRoot(rawChildren);
  2576. if (!childRoot) {
  2577. return [vnode, undefined];
  2578. }
  2579. const index = rawChildren.indexOf(childRoot);
  2580. const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
  2581. const setRoot = (updatedRoot) => {
  2582. rawChildren[index] = updatedRoot;
  2583. if (dynamicChildren) {
  2584. if (dynamicIndex > -1) {
  2585. dynamicChildren[dynamicIndex] = updatedRoot;
  2586. }
  2587. else if (updatedRoot.patchFlag > 0) {
  2588. vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
  2589. }
  2590. }
  2591. };
  2592. return [normalizeVNode(childRoot), setRoot];
  2593. };
  2594. function filterSingleRoot(children) {
  2595. let singleRoot;
  2596. for (let i = 0; i < children.length; i++) {
  2597. const child = children[i];
  2598. if (isVNode(child)) {
  2599. // ignore user comment
  2600. if (child.type !== Comment || child.children === 'v-if') {
  2601. if (singleRoot) {
  2602. // has more than 1 non-comment child, return now
  2603. return;
  2604. }
  2605. else {
  2606. singleRoot = child;
  2607. }
  2608. }
  2609. }
  2610. else {
  2611. return;
  2612. }
  2613. }
  2614. return singleRoot;
  2615. }
  2616. const getFunctionalFallthrough = (attrs) => {
  2617. let res;
  2618. for (const key in attrs) {
  2619. if (key === 'class' || key === 'style' || isOn(key)) {
  2620. (res || (res = {}))[key] = attrs[key];
  2621. }
  2622. }
  2623. return res;
  2624. };
  2625. const filterModelListeners = (attrs, props) => {
  2626. const res = {};
  2627. for (const key in attrs) {
  2628. if (!isModelListener(key) || !(key.slice(9) in props)) {
  2629. res[key] = attrs[key];
  2630. }
  2631. }
  2632. return res;
  2633. };
  2634. const isElementRoot = (vnode) => {
  2635. return (vnode.shapeFlag & (6 /* ShapeFlags.COMPONENT */ | 1 /* ShapeFlags.ELEMENT */) ||
  2636. vnode.type === Comment // potential v-if branch switch
  2637. );
  2638. };
  2639. function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
  2640. const { props: prevProps, children: prevChildren, component } = prevVNode;
  2641. const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
  2642. const emits = component.emitsOptions;
  2643. // Parent component's render function was hot-updated. Since this may have
  2644. // caused the child component's slots content to have changed, we need to
  2645. // force the child to update as well.
  2646. if ((prevChildren || nextChildren) && isHmrUpdating) {
  2647. return true;
  2648. }
  2649. // force child update for runtime directive or transition on component vnode.
  2650. if (nextVNode.dirs || nextVNode.transition) {
  2651. return true;
  2652. }
  2653. if (optimized && patchFlag >= 0) {
  2654. if (patchFlag & 1024 /* PatchFlags.DYNAMIC_SLOTS */) {
  2655. // slot content that references values that might have changed,
  2656. // e.g. in a v-for
  2657. return true;
  2658. }
  2659. if (patchFlag & 16 /* PatchFlags.FULL_PROPS */) {
  2660. if (!prevProps) {
  2661. return !!nextProps;
  2662. }
  2663. // presence of this flag indicates props are always non-null
  2664. return hasPropsChanged(prevProps, nextProps, emits);
  2665. }
  2666. else if (patchFlag & 8 /* PatchFlags.PROPS */) {
  2667. const dynamicProps = nextVNode.dynamicProps;
  2668. for (let i = 0; i < dynamicProps.length; i++) {
  2669. const key = dynamicProps[i];
  2670. if (nextProps[key] !== prevProps[key] &&
  2671. !isEmitListener(emits, key)) {
  2672. return true;
  2673. }
  2674. }
  2675. }
  2676. }
  2677. else {
  2678. // this path is only taken by manually written render functions
  2679. // so presence of any children leads to a forced update
  2680. if (prevChildren || nextChildren) {
  2681. if (!nextChildren || !nextChildren.$stable) {
  2682. return true;
  2683. }
  2684. }
  2685. if (prevProps === nextProps) {
  2686. return false;
  2687. }
  2688. if (!prevProps) {
  2689. return !!nextProps;
  2690. }
  2691. if (!nextProps) {
  2692. return true;
  2693. }
  2694. return hasPropsChanged(prevProps, nextProps, emits);
  2695. }
  2696. return false;
  2697. }
  2698. function hasPropsChanged(prevProps, nextProps, emitsOptions) {
  2699. const nextKeys = Object.keys(nextProps);
  2700. if (nextKeys.length !== Object.keys(prevProps).length) {
  2701. return true;
  2702. }
  2703. for (let i = 0; i < nextKeys.length; i++) {
  2704. const key = nextKeys[i];
  2705. if (nextProps[key] !== prevProps[key] &&
  2706. !isEmitListener(emitsOptions, key)) {
  2707. return true;
  2708. }
  2709. }
  2710. return false;
  2711. }
  2712. function updateHOCHostEl({ vnode, parent }, el // HostNode
  2713. ) {
  2714. while (parent && parent.subTree === vnode) {
  2715. (vnode = parent.vnode).el = el;
  2716. parent = parent.parent;
  2717. }
  2718. }
  2719. const isSuspense = (type) => type.__isSuspense;
  2720. // Suspense exposes a component-like API, and is treated like a component
  2721. // in the compiler, but internally it's a special built-in type that hooks
  2722. // directly into the renderer.
  2723. const SuspenseImpl = {
  2724. name: 'Suspense',
  2725. // In order to make Suspense tree-shakable, we need to avoid importing it
  2726. // directly in the renderer. The renderer checks for the __isSuspense flag
  2727. // on a vnode's type and calls the `process` method, passing in renderer
  2728. // internals.
  2729. __isSuspense: true,
  2730. process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized,
  2731. // platform-specific impl passed from renderer
  2732. rendererInternals) {
  2733. if (n1 == null) {
  2734. mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals);
  2735. }
  2736. else {
  2737. patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals);
  2738. }
  2739. },
  2740. hydrate: hydrateSuspense,
  2741. create: createSuspenseBoundary,
  2742. normalize: normalizeSuspenseChildren
  2743. };
  2744. // Force-casted public typing for h and TSX props inference
  2745. const Suspense = (SuspenseImpl
  2746. );
  2747. function triggerEvent(vnode, name) {
  2748. const eventListener = vnode.props && vnode.props[name];
  2749. if (isFunction(eventListener)) {
  2750. eventListener();
  2751. }
  2752. }
  2753. function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) {
  2754. const { p: patch, o: { createElement } } = rendererInternals;
  2755. const hiddenContainer = createElement('div');
  2756. const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals));
  2757. // start mounting the content subtree in an off-dom container
  2758. patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds);
  2759. // now check if we have encountered any async deps
  2760. if (suspense.deps > 0) {
  2761. // has async
  2762. // invoke @fallback event
  2763. triggerEvent(vnode, 'onPending');
  2764. triggerEvent(vnode, 'onFallback');
  2765. // mount the fallback tree
  2766. patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2767. isSVG, slotScopeIds);
  2768. setActiveBranch(suspense, vnode.ssFallback);
  2769. }
  2770. else {
  2771. // Suspense has no async deps. Just resolve.
  2772. suspense.resolve();
  2773. }
  2774. }
  2775. function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {
  2776. const suspense = (n2.suspense = n1.suspense);
  2777. suspense.vnode = n2;
  2778. n2.el = n1.el;
  2779. const newBranch = n2.ssContent;
  2780. const newFallback = n2.ssFallback;
  2781. const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
  2782. if (pendingBranch) {
  2783. suspense.pendingBranch = newBranch;
  2784. if (isSameVNodeType(newBranch, pendingBranch)) {
  2785. // same root type but content may have changed.
  2786. patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2787. if (suspense.deps <= 0) {
  2788. suspense.resolve();
  2789. }
  2790. else if (isInFallback) {
  2791. patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2792. isSVG, slotScopeIds, optimized);
  2793. setActiveBranch(suspense, newFallback);
  2794. }
  2795. }
  2796. else {
  2797. // toggled before pending tree is resolved
  2798. suspense.pendingId++;
  2799. if (isHydrating) {
  2800. // if toggled before hydration is finished, the current DOM tree is
  2801. // no longer valid. set it as the active branch so it will be unmounted
  2802. // when resolved
  2803. suspense.isHydrating = false;
  2804. suspense.activeBranch = pendingBranch;
  2805. }
  2806. else {
  2807. unmount(pendingBranch, parentComponent, suspense);
  2808. }
  2809. // increment pending ID. this is used to invalidate async callbacks
  2810. // reset suspense state
  2811. suspense.deps = 0;
  2812. // discard effects from pending branch
  2813. suspense.effects.length = 0;
  2814. // discard previous container
  2815. suspense.hiddenContainer = createElement('div');
  2816. if (isInFallback) {
  2817. // already in fallback state
  2818. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2819. if (suspense.deps <= 0) {
  2820. suspense.resolve();
  2821. }
  2822. else {
  2823. patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2824. isSVG, slotScopeIds, optimized);
  2825. setActiveBranch(suspense, newFallback);
  2826. }
  2827. }
  2828. else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
  2829. // toggled "back" to current active branch
  2830. patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2831. // force resolve
  2832. suspense.resolve(true);
  2833. }
  2834. else {
  2835. // switched to a 3rd branch
  2836. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2837. if (suspense.deps <= 0) {
  2838. suspense.resolve();
  2839. }
  2840. }
  2841. }
  2842. }
  2843. else {
  2844. if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
  2845. // root did not change, just normal patch
  2846. patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2847. setActiveBranch(suspense, newBranch);
  2848. }
  2849. else {
  2850. // root node toggled
  2851. // invoke @pending event
  2852. triggerEvent(n2, 'onPending');
  2853. // mount pending branch in off-dom container
  2854. suspense.pendingBranch = newBranch;
  2855. suspense.pendingId++;
  2856. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2857. if (suspense.deps <= 0) {
  2858. // incoming branch has no async deps, resolve now.
  2859. suspense.resolve();
  2860. }
  2861. else {
  2862. const { timeout, pendingId } = suspense;
  2863. if (timeout > 0) {
  2864. setTimeout(() => {
  2865. if (suspense.pendingId === pendingId) {
  2866. suspense.fallback(newFallback);
  2867. }
  2868. }, timeout);
  2869. }
  2870. else if (timeout === 0) {
  2871. suspense.fallback(newFallback);
  2872. }
  2873. }
  2874. }
  2875. }
  2876. }
  2877. let hasWarned = false;
  2878. function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
  2879. /* istanbul ignore if */
  2880. if (!hasWarned) {
  2881. hasWarned = true;
  2882. // @ts-ignore `console.info` cannot be null error
  2883. console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
  2884. }
  2885. const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
  2886. const timeout = toNumber(vnode.props && vnode.props.timeout);
  2887. const suspense = {
  2888. vnode,
  2889. parent,
  2890. parentComponent,
  2891. isSVG,
  2892. container,
  2893. hiddenContainer,
  2894. anchor,
  2895. deps: 0,
  2896. pendingId: 0,
  2897. timeout: typeof timeout === 'number' ? timeout : -1,
  2898. activeBranch: null,
  2899. pendingBranch: null,
  2900. isInFallback: true,
  2901. isHydrating,
  2902. isUnmounted: false,
  2903. effects: [],
  2904. resolve(resume = false) {
  2905. {
  2906. if (!resume && !suspense.pendingBranch) {
  2907. throw new Error(`suspense.resolve() is called without a pending branch.`);
  2908. }
  2909. if (suspense.isUnmounted) {
  2910. throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
  2911. }
  2912. }
  2913. const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
  2914. if (suspense.isHydrating) {
  2915. suspense.isHydrating = false;
  2916. }
  2917. else if (!resume) {
  2918. const delayEnter = activeBranch &&
  2919. pendingBranch.transition &&
  2920. pendingBranch.transition.mode === 'out-in';
  2921. if (delayEnter) {
  2922. activeBranch.transition.afterLeave = () => {
  2923. if (pendingId === suspense.pendingId) {
  2924. move(pendingBranch, container, anchor, 0 /* MoveType.ENTER */);
  2925. }
  2926. };
  2927. }
  2928. // this is initial anchor on mount
  2929. let { anchor } = suspense;
  2930. // unmount current active tree
  2931. if (activeBranch) {
  2932. // if the fallback tree was mounted, it may have been moved
  2933. // as part of a parent suspense. get the latest anchor for insertion
  2934. anchor = next(activeBranch);
  2935. unmount(activeBranch, parentComponent, suspense, true);
  2936. }
  2937. if (!delayEnter) {
  2938. // move content from off-dom container to actual container
  2939. move(pendingBranch, container, anchor, 0 /* MoveType.ENTER */);
  2940. }
  2941. }
  2942. setActiveBranch(suspense, pendingBranch);
  2943. suspense.pendingBranch = null;
  2944. suspense.isInFallback = false;
  2945. // flush buffered effects
  2946. // check if there is a pending parent suspense
  2947. let parent = suspense.parent;
  2948. let hasUnresolvedAncestor = false;
  2949. while (parent) {
  2950. if (parent.pendingBranch) {
  2951. // found a pending parent suspense, merge buffered post jobs
  2952. // into that parent
  2953. parent.effects.push(...effects);
  2954. hasUnresolvedAncestor = true;
  2955. break;
  2956. }
  2957. parent = parent.parent;
  2958. }
  2959. // no pending parent suspense, flush all jobs
  2960. if (!hasUnresolvedAncestor) {
  2961. queuePostFlushCb(effects);
  2962. }
  2963. suspense.effects = [];
  2964. // invoke @resolve event
  2965. triggerEvent(vnode, 'onResolve');
  2966. },
  2967. fallback(fallbackVNode) {
  2968. if (!suspense.pendingBranch) {
  2969. return;
  2970. }
  2971. const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
  2972. // invoke @fallback event
  2973. triggerEvent(vnode, 'onFallback');
  2974. const anchor = next(activeBranch);
  2975. const mountFallback = () => {
  2976. if (!suspense.isInFallback) {
  2977. return;
  2978. }
  2979. // mount the fallback tree
  2980. patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2981. isSVG, slotScopeIds, optimized);
  2982. setActiveBranch(suspense, fallbackVNode);
  2983. };
  2984. const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
  2985. if (delayEnter) {
  2986. activeBranch.transition.afterLeave = mountFallback;
  2987. }
  2988. suspense.isInFallback = true;
  2989. // unmount current active branch
  2990. unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
  2991. true // shouldRemove
  2992. );
  2993. if (!delayEnter) {
  2994. mountFallback();
  2995. }
  2996. },
  2997. move(container, anchor, type) {
  2998. suspense.activeBranch &&
  2999. move(suspense.activeBranch, container, anchor, type);
  3000. suspense.container = container;
  3001. },
  3002. next() {
  3003. return suspense.activeBranch && next(suspense.activeBranch);
  3004. },
  3005. registerDep(instance, setupRenderEffect) {
  3006. const isInPendingSuspense = !!suspense.pendingBranch;
  3007. if (isInPendingSuspense) {
  3008. suspense.deps++;
  3009. }
  3010. const hydratedEl = instance.vnode.el;
  3011. instance
  3012. .asyncDep.catch(err => {
  3013. handleError(err, instance, 0 /* ErrorCodes.SETUP_FUNCTION */);
  3014. })
  3015. .then(asyncSetupResult => {
  3016. // retry when the setup() promise resolves.
  3017. // component may have been unmounted before resolve.
  3018. if (instance.isUnmounted ||
  3019. suspense.isUnmounted ||
  3020. suspense.pendingId !== instance.suspenseId) {
  3021. return;
  3022. }
  3023. // retry from this component
  3024. instance.asyncResolved = true;
  3025. const { vnode } = instance;
  3026. {
  3027. pushWarningContext(vnode);
  3028. }
  3029. handleSetupResult(instance, asyncSetupResult, false);
  3030. if (hydratedEl) {
  3031. // vnode may have been replaced if an update happened before the
  3032. // async dep is resolved.
  3033. vnode.el = hydratedEl;
  3034. }
  3035. const placeholder = !hydratedEl && instance.subTree.el;
  3036. setupRenderEffect(instance, vnode,
  3037. // component may have been moved before resolve.
  3038. // if this is not a hydration, instance.subTree will be the comment
  3039. // placeholder.
  3040. parentNode(hydratedEl || instance.subTree.el),
  3041. // anchor will not be used if this is hydration, so only need to
  3042. // consider the comment placeholder case.
  3043. hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
  3044. if (placeholder) {
  3045. remove(placeholder);
  3046. }
  3047. updateHOCHostEl(instance, vnode.el);
  3048. {
  3049. popWarningContext();
  3050. }
  3051. // only decrease deps count if suspense is not already resolved
  3052. if (isInPendingSuspense && --suspense.deps === 0) {
  3053. suspense.resolve();
  3054. }
  3055. });
  3056. },
  3057. unmount(parentSuspense, doRemove) {
  3058. suspense.isUnmounted = true;
  3059. if (suspense.activeBranch) {
  3060. unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
  3061. }
  3062. if (suspense.pendingBranch) {
  3063. unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
  3064. }
  3065. }
  3066. };
  3067. return suspense;
  3068. }
  3069. function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) {
  3070. /* eslint-disable no-restricted-globals */
  3071. const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */));
  3072. // there are two possible scenarios for server-rendered suspense:
  3073. // - success: ssr content should be fully resolved
  3074. // - failure: ssr content should be the fallback branch.
  3075. // however, on the client we don't really know if it has failed or not
  3076. // attempt to hydrate the DOM assuming it has succeeded, but we still
  3077. // need to construct a suspense boundary first
  3078. const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, slotScopeIds, optimized);
  3079. if (suspense.deps === 0) {
  3080. suspense.resolve();
  3081. }
  3082. return result;
  3083. /* eslint-enable no-restricted-globals */
  3084. }
  3085. function normalizeSuspenseChildren(vnode) {
  3086. const { shapeFlag, children } = vnode;
  3087. const isSlotChildren = shapeFlag & 32 /* ShapeFlags.SLOTS_CHILDREN */;
  3088. vnode.ssContent = normalizeSuspenseSlot(isSlotChildren ? children.default : children);
  3089. vnode.ssFallback = isSlotChildren
  3090. ? normalizeSuspenseSlot(children.fallback)
  3091. : createVNode(Comment);
  3092. }
  3093. function normalizeSuspenseSlot(s) {
  3094. let block;
  3095. if (isFunction(s)) {
  3096. const trackBlock = isBlockTreeEnabled && s._c;
  3097. if (trackBlock) {
  3098. // disableTracking: false
  3099. // allow block tracking for compiled slots
  3100. // (see ./componentRenderContext.ts)
  3101. s._d = false;
  3102. openBlock();
  3103. }
  3104. s = s();
  3105. if (trackBlock) {
  3106. s._d = true;
  3107. block = currentBlock;
  3108. closeBlock();
  3109. }
  3110. }
  3111. if (isArray(s)) {
  3112. const singleChild = filterSingleRoot(s);
  3113. if (!singleChild) {
  3114. warn$1(`<Suspense> slots expect a single root node.`);
  3115. }
  3116. s = singleChild;
  3117. }
  3118. s = normalizeVNode(s);
  3119. if (block && !s.dynamicChildren) {
  3120. s.dynamicChildren = block.filter(c => c !== s);
  3121. }
  3122. return s;
  3123. }
  3124. function queueEffectWithSuspense(fn, suspense) {
  3125. if (suspense && suspense.pendingBranch) {
  3126. if (isArray(fn)) {
  3127. suspense.effects.push(...fn);
  3128. }
  3129. else {
  3130. suspense.effects.push(fn);
  3131. }
  3132. }
  3133. else {
  3134. queuePostFlushCb(fn);
  3135. }
  3136. }
  3137. function setActiveBranch(suspense, branch) {
  3138. suspense.activeBranch = branch;
  3139. const { vnode, parentComponent } = suspense;
  3140. const el = (vnode.el = branch.el);
  3141. // in case suspense is the root node of a component,
  3142. // recursively update the HOC el
  3143. if (parentComponent && parentComponent.subTree === vnode) {
  3144. parentComponent.vnode.el = el;
  3145. updateHOCHostEl(parentComponent, el);
  3146. }
  3147. }
  3148. function provide(key, value) {
  3149. if (!currentInstance) {
  3150. {
  3151. warn$1(`provide() can only be used inside setup().`);
  3152. }
  3153. }
  3154. else {
  3155. let provides = currentInstance.provides;
  3156. // by default an instance inherits its parent's provides object
  3157. // but when it needs to provide values of its own, it creates its
  3158. // own provides object using parent provides object as prototype.
  3159. // this way in `inject` we can simply look up injections from direct
  3160. // parent and let the prototype chain do the work.
  3161. const parentProvides = currentInstance.parent && currentInstance.parent.provides;
  3162. if (parentProvides === provides) {
  3163. provides = currentInstance.provides = Object.create(parentProvides);
  3164. }
  3165. // TS doesn't allow symbol as index type
  3166. provides[key] = value;
  3167. }
  3168. }
  3169. function inject(key, defaultValue, treatDefaultAsFactory = false) {
  3170. // fallback to `currentRenderingInstance` so that this can be called in
  3171. // a functional component
  3172. const instance = currentInstance || currentRenderingInstance;
  3173. if (instance) {
  3174. // #2400
  3175. // to support `app.use` plugins,
  3176. // fallback to appContext's `provides` if the instance is at root
  3177. const provides = instance.parent == null
  3178. ? instance.vnode.appContext && instance.vnode.appContext.provides
  3179. : instance.parent.provides;
  3180. if (provides && key in provides) {
  3181. // TS doesn't allow symbol as index type
  3182. return provides[key];
  3183. }
  3184. else if (arguments.length > 1) {
  3185. return treatDefaultAsFactory && isFunction(defaultValue)
  3186. ? defaultValue.call(instance.proxy)
  3187. : defaultValue;
  3188. }
  3189. else {
  3190. warn$1(`injection "${String(key)}" not found.`);
  3191. }
  3192. }
  3193. else {
  3194. warn$1(`inject() can only be used inside setup() or functional components.`);
  3195. }
  3196. }
  3197. // Simple effect.
  3198. function watchEffect(effect, options) {
  3199. return doWatch(effect, null, options);
  3200. }
  3201. function watchPostEffect(effect, options) {
  3202. return doWatch(effect, null, (Object.assign(Object.assign({}, options), { flush: 'post' }) ));
  3203. }
  3204. function watchSyncEffect(effect, options) {
  3205. return doWatch(effect, null, (Object.assign(Object.assign({}, options), { flush: 'sync' }) ));
  3206. }
  3207. // initial value for watchers to trigger on undefined initial values
  3208. const INITIAL_WATCHER_VALUE = {};
  3209. // implementation
  3210. function watch(source, cb, options) {
  3211. if (!isFunction(cb)) {
  3212. warn$1(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
  3213. `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
  3214. `supports \`watch(source, cb, options?) signature.`);
  3215. }
  3216. return doWatch(source, cb, options);
  3217. }
  3218. function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ) {
  3219. if (!cb) {
  3220. if (immediate !== undefined) {
  3221. warn$1(`watch() "immediate" option is only respected when using the ` +
  3222. `watch(source, callback, options?) signature.`);
  3223. }
  3224. if (deep !== undefined) {
  3225. warn$1(`watch() "deep" option is only respected when using the ` +
  3226. `watch(source, callback, options?) signature.`);
  3227. }
  3228. }
  3229. const warnInvalidSource = (s) => {
  3230. warn$1(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
  3231. `a reactive object, or an array of these types.`);
  3232. };
  3233. const instance = currentInstance;
  3234. let getter;
  3235. let forceTrigger = false;
  3236. let isMultiSource = false;
  3237. if (isRef(source)) {
  3238. getter = () => source.value;
  3239. forceTrigger = isShallow(source);
  3240. }
  3241. else if (isReactive(source)) {
  3242. getter = () => source;
  3243. deep = true;
  3244. }
  3245. else if (isArray(source)) {
  3246. isMultiSource = true;
  3247. forceTrigger = source.some(s => isReactive(s) || isShallow(s));
  3248. getter = () => source.map(s => {
  3249. if (isRef(s)) {
  3250. return s.value;
  3251. }
  3252. else if (isReactive(s)) {
  3253. return traverse(s);
  3254. }
  3255. else if (isFunction(s)) {
  3256. return callWithErrorHandling(s, instance, 2 /* ErrorCodes.WATCH_GETTER */);
  3257. }
  3258. else {
  3259. warnInvalidSource(s);
  3260. }
  3261. });
  3262. }
  3263. else if (isFunction(source)) {
  3264. if (cb) {
  3265. // getter with cb
  3266. getter = () => callWithErrorHandling(source, instance, 2 /* ErrorCodes.WATCH_GETTER */);
  3267. }
  3268. else {
  3269. // no cb -> simple effect
  3270. getter = () => {
  3271. if (instance && instance.isUnmounted) {
  3272. return;
  3273. }
  3274. if (cleanup) {
  3275. cleanup();
  3276. }
  3277. return callWithAsyncErrorHandling(source, instance, 3 /* ErrorCodes.WATCH_CALLBACK */, [onCleanup]);
  3278. };
  3279. }
  3280. }
  3281. else {
  3282. getter = NOOP;
  3283. warnInvalidSource(source);
  3284. }
  3285. if (cb && deep) {
  3286. const baseGetter = getter;
  3287. getter = () => traverse(baseGetter());
  3288. }
  3289. let cleanup;
  3290. let onCleanup = (fn) => {
  3291. cleanup = effect.onStop = () => {
  3292. callWithErrorHandling(fn, instance, 4 /* ErrorCodes.WATCH_CLEANUP */);
  3293. };
  3294. };
  3295. let oldValue = isMultiSource
  3296. ? new Array(source.length).fill(INITIAL_WATCHER_VALUE)
  3297. : INITIAL_WATCHER_VALUE;
  3298. const job = () => {
  3299. if (!effect.active) {
  3300. return;
  3301. }
  3302. if (cb) {
  3303. // watch(source, cb)
  3304. const newValue = effect.run();
  3305. if (deep ||
  3306. forceTrigger ||
  3307. (isMultiSource
  3308. ? newValue.some((v, i) => hasChanged(v, oldValue[i]))
  3309. : hasChanged(newValue, oldValue)) ||
  3310. (false )) {
  3311. // cleanup before running cb again
  3312. if (cleanup) {
  3313. cleanup();
  3314. }
  3315. callWithAsyncErrorHandling(cb, instance, 3 /* ErrorCodes.WATCH_CALLBACK */, [
  3316. newValue,
  3317. // pass undefined as the old value when it's changed for the first time
  3318. oldValue === INITIAL_WATCHER_VALUE
  3319. ? undefined
  3320. : (isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE)
  3321. ? []
  3322. : oldValue,
  3323. onCleanup
  3324. ]);
  3325. oldValue = newValue;
  3326. }
  3327. }
  3328. else {
  3329. // watchEffect
  3330. effect.run();
  3331. }
  3332. };
  3333. // important: mark the job as a watcher callback so that scheduler knows
  3334. // it is allowed to self-trigger (#1727)
  3335. job.allowRecurse = !!cb;
  3336. let scheduler;
  3337. if (flush === 'sync') {
  3338. scheduler = job; // the scheduler function gets called directly
  3339. }
  3340. else if (flush === 'post') {
  3341. scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
  3342. }
  3343. else {
  3344. // default: 'pre'
  3345. job.pre = true;
  3346. if (instance)
  3347. job.id = instance.uid;
  3348. scheduler = () => queueJob(job);
  3349. }
  3350. const effect = new ReactiveEffect(getter, scheduler);
  3351. {
  3352. effect.onTrack = onTrack;
  3353. effect.onTrigger = onTrigger;
  3354. }
  3355. // initial run
  3356. if (cb) {
  3357. if (immediate) {
  3358. job();
  3359. }
  3360. else {
  3361. oldValue = effect.run();
  3362. }
  3363. }
  3364. else if (flush === 'post') {
  3365. queuePostRenderEffect(effect.run.bind(effect), instance && instance.suspense);
  3366. }
  3367. else {
  3368. effect.run();
  3369. }
  3370. const unwatch = () => {
  3371. effect.stop();
  3372. if (instance && instance.scope) {
  3373. remove(instance.scope.effects, effect);
  3374. }
  3375. };
  3376. return unwatch;
  3377. }
  3378. // this.$watch
  3379. function instanceWatch(source, value, options) {
  3380. const publicThis = this.proxy;
  3381. const getter = isString(source)
  3382. ? source.includes('.')
  3383. ? createPathGetter(publicThis, source)
  3384. : () => publicThis[source]
  3385. : source.bind(publicThis, publicThis);
  3386. let cb;
  3387. if (isFunction(value)) {
  3388. cb = value;
  3389. }
  3390. else {
  3391. cb = value.handler;
  3392. options = value;
  3393. }
  3394. const cur = currentInstance;
  3395. setCurrentInstance(this);
  3396. const res = doWatch(getter, cb.bind(publicThis), options);
  3397. if (cur) {
  3398. setCurrentInstance(cur);
  3399. }
  3400. else {
  3401. unsetCurrentInstance();
  3402. }
  3403. return res;
  3404. }
  3405. function createPathGetter(ctx, path) {
  3406. const segments = path.split('.');
  3407. return () => {
  3408. let cur = ctx;
  3409. for (let i = 0; i < segments.length && cur; i++) {
  3410. cur = cur[segments[i]];
  3411. }
  3412. return cur;
  3413. };
  3414. }
  3415. function traverse(value, seen) {
  3416. if (!isObject(value) || value["__v_skip" /* ReactiveFlags.SKIP */]) {
  3417. return value;
  3418. }
  3419. seen = seen || new Set();
  3420. if (seen.has(value)) {
  3421. return value;
  3422. }
  3423. seen.add(value);
  3424. if (isRef(value)) {
  3425. traverse(value.value, seen);
  3426. }
  3427. else if (isArray(value)) {
  3428. for (let i = 0; i < value.length; i++) {
  3429. traverse(value[i], seen);
  3430. }
  3431. }
  3432. else if (isSet(value) || isMap(value)) {
  3433. value.forEach((v) => {
  3434. traverse(v, seen);
  3435. });
  3436. }
  3437. else if (isPlainObject(value)) {
  3438. for (const key in value) {
  3439. traverse(value[key], seen);
  3440. }
  3441. }
  3442. return value;
  3443. }
  3444. function useTransitionState() {
  3445. const state = {
  3446. isMounted: false,
  3447. isLeaving: false,
  3448. isUnmounting: false,
  3449. leavingVNodes: new Map()
  3450. };
  3451. onMounted(() => {
  3452. state.isMounted = true;
  3453. });
  3454. onBeforeUnmount(() => {
  3455. state.isUnmounting = true;
  3456. });
  3457. return state;
  3458. }
  3459. const TransitionHookValidator = [Function, Array];
  3460. const BaseTransitionImpl = {
  3461. name: `BaseTransition`,
  3462. props: {
  3463. mode: String,
  3464. appear: Boolean,
  3465. persisted: Boolean,
  3466. // enter
  3467. onBeforeEnter: TransitionHookValidator,
  3468. onEnter: TransitionHookValidator,
  3469. onAfterEnter: TransitionHookValidator,
  3470. onEnterCancelled: TransitionHookValidator,
  3471. // leave
  3472. onBeforeLeave: TransitionHookValidator,
  3473. onLeave: TransitionHookValidator,
  3474. onAfterLeave: TransitionHookValidator,
  3475. onLeaveCancelled: TransitionHookValidator,
  3476. // appear
  3477. onBeforeAppear: TransitionHookValidator,
  3478. onAppear: TransitionHookValidator,
  3479. onAfterAppear: TransitionHookValidator,
  3480. onAppearCancelled: TransitionHookValidator
  3481. },
  3482. setup(props, { slots }) {
  3483. const instance = getCurrentInstance();
  3484. const state = useTransitionState();
  3485. let prevTransitionKey;
  3486. return () => {
  3487. const children = slots.default && getTransitionRawChildren(slots.default(), true);
  3488. if (!children || !children.length) {
  3489. return;
  3490. }
  3491. let child = children[0];
  3492. if (children.length > 1) {
  3493. let hasFound = false;
  3494. // locate first non-comment child
  3495. for (const c of children) {
  3496. if (c.type !== Comment) {
  3497. if (hasFound) {
  3498. // warn more than one non-comment child
  3499. warn$1('<transition> can only be used on a single element or component. ' +
  3500. 'Use <transition-group> for lists.');
  3501. break;
  3502. }
  3503. child = c;
  3504. hasFound = true;
  3505. }
  3506. }
  3507. }
  3508. // there's no need to track reactivity for these props so use the raw
  3509. // props for a bit better perf
  3510. const rawProps = toRaw(props);
  3511. const { mode } = rawProps;
  3512. // check mode
  3513. if (mode &&
  3514. mode !== 'in-out' &&
  3515. mode !== 'out-in' &&
  3516. mode !== 'default') {
  3517. warn$1(`invalid <transition> mode: ${mode}`);
  3518. }
  3519. if (state.isLeaving) {
  3520. return emptyPlaceholder(child);
  3521. }
  3522. // in the case of <transition><keep-alive/></transition>, we need to
  3523. // compare the type of the kept-alive children.
  3524. const innerChild = getKeepAliveChild(child);
  3525. if (!innerChild) {
  3526. return emptyPlaceholder(child);
  3527. }
  3528. const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
  3529. setTransitionHooks(innerChild, enterHooks);
  3530. const oldChild = instance.subTree;
  3531. const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
  3532. let transitionKeyChanged = false;
  3533. const { getTransitionKey } = innerChild.type;
  3534. if (getTransitionKey) {
  3535. const key = getTransitionKey();
  3536. if (prevTransitionKey === undefined) {
  3537. prevTransitionKey = key;
  3538. }
  3539. else if (key !== prevTransitionKey) {
  3540. prevTransitionKey = key;
  3541. transitionKeyChanged = true;
  3542. }
  3543. }
  3544. // handle mode
  3545. if (oldInnerChild &&
  3546. oldInnerChild.type !== Comment &&
  3547. (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
  3548. const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
  3549. // update old tree's hooks in case of dynamic transition
  3550. setTransitionHooks(oldInnerChild, leavingHooks);
  3551. // switching between different views
  3552. if (mode === 'out-in') {
  3553. state.isLeaving = true;
  3554. // return placeholder node and queue update when leave finishes
  3555. leavingHooks.afterLeave = () => {
  3556. state.isLeaving = false;
  3557. // #6835
  3558. // it also needs to be updated when active is undefined
  3559. if (instance.update.active !== false) {
  3560. instance.update();
  3561. }
  3562. };
  3563. return emptyPlaceholder(child);
  3564. }
  3565. else if (mode === 'in-out' && innerChild.type !== Comment) {
  3566. leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
  3567. const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
  3568. leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
  3569. // early removal callback
  3570. el._leaveCb = () => {
  3571. earlyRemove();
  3572. el._leaveCb = undefined;
  3573. delete enterHooks.delayedLeave;
  3574. };
  3575. enterHooks.delayedLeave = delayedLeave;
  3576. };
  3577. }
  3578. }
  3579. return child;
  3580. };
  3581. }
  3582. };
  3583. // export the public type for h/tsx inference
  3584. // also to avoid inline import() in generated d.ts files
  3585. const BaseTransition = BaseTransitionImpl;
  3586. function getLeavingNodesForType(state, vnode) {
  3587. const { leavingVNodes } = state;
  3588. let leavingVNodesCache = leavingVNodes.get(vnode.type);
  3589. if (!leavingVNodesCache) {
  3590. leavingVNodesCache = Object.create(null);
  3591. leavingVNodes.set(vnode.type, leavingVNodesCache);
  3592. }
  3593. return leavingVNodesCache;
  3594. }
  3595. // The transition hooks are attached to the vnode as vnode.transition
  3596. // and will be called at appropriate timing in the renderer.
  3597. function resolveTransitionHooks(vnode, props, state, instance) {
  3598. const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
  3599. const key = String(vnode.key);
  3600. const leavingVNodesCache = getLeavingNodesForType(state, vnode);
  3601. const callHook = (hook, args) => {
  3602. hook &&
  3603. callWithAsyncErrorHandling(hook, instance, 9 /* ErrorCodes.TRANSITION_HOOK */, args);
  3604. };
  3605. const callAsyncHook = (hook, args) => {
  3606. const done = args[1];
  3607. callHook(hook, args);
  3608. if (isArray(hook)) {
  3609. if (hook.every(hook => hook.length <= 1))
  3610. done();
  3611. }
  3612. else if (hook.length <= 1) {
  3613. done();
  3614. }
  3615. };
  3616. const hooks = {
  3617. mode,
  3618. persisted,
  3619. beforeEnter(el) {
  3620. let hook = onBeforeEnter;
  3621. if (!state.isMounted) {
  3622. if (appear) {
  3623. hook = onBeforeAppear || onBeforeEnter;
  3624. }
  3625. else {
  3626. return;
  3627. }
  3628. }
  3629. // for same element (v-show)
  3630. if (el._leaveCb) {
  3631. el._leaveCb(true /* cancelled */);
  3632. }
  3633. // for toggled element with same key (v-if)
  3634. const leavingVNode = leavingVNodesCache[key];
  3635. if (leavingVNode &&
  3636. isSameVNodeType(vnode, leavingVNode) &&
  3637. leavingVNode.el._leaveCb) {
  3638. // force early removal (not cancelled)
  3639. leavingVNode.el._leaveCb();
  3640. }
  3641. callHook(hook, [el]);
  3642. },
  3643. enter(el) {
  3644. let hook = onEnter;
  3645. let afterHook = onAfterEnter;
  3646. let cancelHook = onEnterCancelled;
  3647. if (!state.isMounted) {
  3648. if (appear) {
  3649. hook = onAppear || onEnter;
  3650. afterHook = onAfterAppear || onAfterEnter;
  3651. cancelHook = onAppearCancelled || onEnterCancelled;
  3652. }
  3653. else {
  3654. return;
  3655. }
  3656. }
  3657. let called = false;
  3658. const done = (el._enterCb = (cancelled) => {
  3659. if (called)
  3660. return;
  3661. called = true;
  3662. if (cancelled) {
  3663. callHook(cancelHook, [el]);
  3664. }
  3665. else {
  3666. callHook(afterHook, [el]);
  3667. }
  3668. if (hooks.delayedLeave) {
  3669. hooks.delayedLeave();
  3670. }
  3671. el._enterCb = undefined;
  3672. });
  3673. if (hook) {
  3674. callAsyncHook(hook, [el, done]);
  3675. }
  3676. else {
  3677. done();
  3678. }
  3679. },
  3680. leave(el, remove) {
  3681. const key = String(vnode.key);
  3682. if (el._enterCb) {
  3683. el._enterCb(true /* cancelled */);
  3684. }
  3685. if (state.isUnmounting) {
  3686. return remove();
  3687. }
  3688. callHook(onBeforeLeave, [el]);
  3689. let called = false;
  3690. const done = (el._leaveCb = (cancelled) => {
  3691. if (called)
  3692. return;
  3693. called = true;
  3694. remove();
  3695. if (cancelled) {
  3696. callHook(onLeaveCancelled, [el]);
  3697. }
  3698. else {
  3699. callHook(onAfterLeave, [el]);
  3700. }
  3701. el._leaveCb = undefined;
  3702. if (leavingVNodesCache[key] === vnode) {
  3703. delete leavingVNodesCache[key];
  3704. }
  3705. });
  3706. leavingVNodesCache[key] = vnode;
  3707. if (onLeave) {
  3708. callAsyncHook(onLeave, [el, done]);
  3709. }
  3710. else {
  3711. done();
  3712. }
  3713. },
  3714. clone(vnode) {
  3715. return resolveTransitionHooks(vnode, props, state, instance);
  3716. }
  3717. };
  3718. return hooks;
  3719. }
  3720. // the placeholder really only handles one special case: KeepAlive
  3721. // in the case of a KeepAlive in a leave phase we need to return a KeepAlive
  3722. // placeholder with empty content to avoid the KeepAlive instance from being
  3723. // unmounted.
  3724. function emptyPlaceholder(vnode) {
  3725. if (isKeepAlive(vnode)) {
  3726. vnode = cloneVNode(vnode);
  3727. vnode.children = null;
  3728. return vnode;
  3729. }
  3730. }
  3731. function getKeepAliveChild(vnode) {
  3732. return isKeepAlive(vnode)
  3733. ? vnode.children
  3734. ? vnode.children[0]
  3735. : undefined
  3736. : vnode;
  3737. }
  3738. function setTransitionHooks(vnode, hooks) {
  3739. if (vnode.shapeFlag & 6 /* ShapeFlags.COMPONENT */ && vnode.component) {
  3740. setTransitionHooks(vnode.component.subTree, hooks);
  3741. }
  3742. else if (vnode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  3743. vnode.ssContent.transition = hooks.clone(vnode.ssContent);
  3744. vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
  3745. }
  3746. else {
  3747. vnode.transition = hooks;
  3748. }
  3749. }
  3750. function getTransitionRawChildren(children, keepComment = false, parentKey) {
  3751. let ret = [];
  3752. let keyedFragmentCount = 0;
  3753. for (let i = 0; i < children.length; i++) {
  3754. let child = children[i];
  3755. // #5360 inherit parent key in case of <template v-for>
  3756. const key = parentKey == null
  3757. ? child.key
  3758. : String(parentKey) + String(child.key != null ? child.key : i);
  3759. // handle fragment children case, e.g. v-for
  3760. if (child.type === Fragment) {
  3761. if (child.patchFlag & 128 /* PatchFlags.KEYED_FRAGMENT */)
  3762. keyedFragmentCount++;
  3763. ret = ret.concat(getTransitionRawChildren(child.children, keepComment, key));
  3764. }
  3765. // comment placeholders should be skipped, e.g. v-if
  3766. else if (keepComment || child.type !== Comment) {
  3767. ret.push(key != null ? cloneVNode(child, { key }) : child);
  3768. }
  3769. }
  3770. // #1126 if a transition children list contains multiple sub fragments, these
  3771. // fragments will be merged into a flat children array. Since each v-for
  3772. // fragment may contain different static bindings inside, we need to de-op
  3773. // these children to force full diffs to ensure correct behavior.
  3774. if (keyedFragmentCount > 1) {
  3775. for (let i = 0; i < ret.length; i++) {
  3776. ret[i].patchFlag = -2 /* PatchFlags.BAIL */;
  3777. }
  3778. }
  3779. return ret;
  3780. }
  3781. // implementation, close to no-op
  3782. function defineComponent(options) {
  3783. return isFunction(options) ? { setup: options, name: options.name } : options;
  3784. }
  3785. const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
  3786. function defineAsyncComponent(source) {
  3787. if (isFunction(source)) {
  3788. source = { loader: source };
  3789. }
  3790. const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
  3791. suspensible = true, onError: userOnError } = source;
  3792. let pendingRequest = null;
  3793. let resolvedComp;
  3794. let retries = 0;
  3795. const retry = () => {
  3796. retries++;
  3797. pendingRequest = null;
  3798. return load();
  3799. };
  3800. const load = () => {
  3801. let thisRequest;
  3802. return (pendingRequest ||
  3803. (thisRequest = pendingRequest =
  3804. loader()
  3805. .catch(err => {
  3806. err = err instanceof Error ? err : new Error(String(err));
  3807. if (userOnError) {
  3808. return new Promise((resolve, reject) => {
  3809. const userRetry = () => resolve(retry());
  3810. const userFail = () => reject(err);
  3811. userOnError(err, userRetry, userFail, retries + 1);
  3812. });
  3813. }
  3814. else {
  3815. throw err;
  3816. }
  3817. })
  3818. .then((comp) => {
  3819. if (thisRequest !== pendingRequest && pendingRequest) {
  3820. return pendingRequest;
  3821. }
  3822. if (!comp) {
  3823. warn$1(`Async component loader resolved to undefined. ` +
  3824. `If you are using retry(), make sure to return its return value.`);
  3825. }
  3826. // interop module default
  3827. if (comp &&
  3828. (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
  3829. comp = comp.default;
  3830. }
  3831. if (comp && !isObject(comp) && !isFunction(comp)) {
  3832. throw new Error(`Invalid async component load result: ${comp}`);
  3833. }
  3834. resolvedComp = comp;
  3835. return comp;
  3836. })));
  3837. };
  3838. return defineComponent({
  3839. name: 'AsyncComponentWrapper',
  3840. __asyncLoader: load,
  3841. get __asyncResolved() {
  3842. return resolvedComp;
  3843. },
  3844. setup() {
  3845. const instance = currentInstance;
  3846. // already resolved
  3847. if (resolvedComp) {
  3848. return () => createInnerComp(resolvedComp, instance);
  3849. }
  3850. const onError = (err) => {
  3851. pendingRequest = null;
  3852. handleError(err, instance, 13 /* ErrorCodes.ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
  3853. };
  3854. // suspense-controlled or SSR.
  3855. if ((suspensible && instance.suspense) ||
  3856. (false )) {
  3857. return load()
  3858. .then(comp => {
  3859. return () => createInnerComp(comp, instance);
  3860. })
  3861. .catch(err => {
  3862. onError(err);
  3863. return () => errorComponent
  3864. ? createVNode(errorComponent, {
  3865. error: err
  3866. })
  3867. : null;
  3868. });
  3869. }
  3870. const loaded = ref(false);
  3871. const error = ref();
  3872. const delayed = ref(!!delay);
  3873. if (delay) {
  3874. setTimeout(() => {
  3875. delayed.value = false;
  3876. }, delay);
  3877. }
  3878. if (timeout != null) {
  3879. setTimeout(() => {
  3880. if (!loaded.value && !error.value) {
  3881. const err = new Error(`Async component timed out after ${timeout}ms.`);
  3882. onError(err);
  3883. error.value = err;
  3884. }
  3885. }, timeout);
  3886. }
  3887. load()
  3888. .then(() => {
  3889. loaded.value = true;
  3890. if (instance.parent && isKeepAlive(instance.parent.vnode)) {
  3891. // parent is keep-alive, force update so the loaded component's
  3892. // name is taken into account
  3893. queueJob(instance.parent.update);
  3894. }
  3895. })
  3896. .catch(err => {
  3897. onError(err);
  3898. error.value = err;
  3899. });
  3900. return () => {
  3901. if (loaded.value && resolvedComp) {
  3902. return createInnerComp(resolvedComp, instance);
  3903. }
  3904. else if (error.value && errorComponent) {
  3905. return createVNode(errorComponent, {
  3906. error: error.value
  3907. });
  3908. }
  3909. else if (loadingComponent && !delayed.value) {
  3910. return createVNode(loadingComponent);
  3911. }
  3912. };
  3913. }
  3914. });
  3915. }
  3916. function createInnerComp(comp, parent) {
  3917. const { ref, props, children, ce } = parent.vnode;
  3918. const vnode = createVNode(comp, props, children);
  3919. // ensure inner component inherits the async wrapper's ref owner
  3920. vnode.ref = ref;
  3921. // pass the custom element callback on to the inner comp
  3922. // and remove it from the async wrapper
  3923. vnode.ce = ce;
  3924. delete parent.vnode.ce;
  3925. return vnode;
  3926. }
  3927. const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
  3928. const KeepAliveImpl = {
  3929. name: `KeepAlive`,
  3930. // Marker for special handling inside the renderer. We are not using a ===
  3931. // check directly on KeepAlive in the renderer, because importing it directly
  3932. // would prevent it from being tree-shaken.
  3933. __isKeepAlive: true,
  3934. props: {
  3935. include: [String, RegExp, Array],
  3936. exclude: [String, RegExp, Array],
  3937. max: [String, Number]
  3938. },
  3939. setup(props, { slots }) {
  3940. const instance = getCurrentInstance();
  3941. // KeepAlive communicates with the instantiated renderer via the
  3942. // ctx where the renderer passes in its internals,
  3943. // and the KeepAlive instance exposes activate/deactivate implementations.
  3944. // The whole point of this is to avoid importing KeepAlive directly in the
  3945. // renderer to facilitate tree-shaking.
  3946. const sharedContext = instance.ctx;
  3947. const cache = new Map();
  3948. const keys = new Set();
  3949. let current = null;
  3950. {
  3951. instance.__v_cache = cache;
  3952. }
  3953. const parentSuspense = instance.suspense;
  3954. const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
  3955. const storageContainer = createElement('div');
  3956. sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
  3957. const instance = vnode.component;
  3958. move(vnode, container, anchor, 0 /* MoveType.ENTER */, parentSuspense);
  3959. // in case props have changed
  3960. patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized);
  3961. queuePostRenderEffect(() => {
  3962. instance.isDeactivated = false;
  3963. if (instance.a) {
  3964. invokeArrayFns(instance.a);
  3965. }
  3966. const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
  3967. if (vnodeHook) {
  3968. invokeVNodeHook(vnodeHook, instance.parent, vnode);
  3969. }
  3970. }, parentSuspense);
  3971. {
  3972. // Update components tree
  3973. devtoolsComponentAdded(instance);
  3974. }
  3975. };
  3976. sharedContext.deactivate = (vnode) => {
  3977. const instance = vnode.component;
  3978. move(vnode, storageContainer, null, 1 /* MoveType.LEAVE */, parentSuspense);
  3979. queuePostRenderEffect(() => {
  3980. if (instance.da) {
  3981. invokeArrayFns(instance.da);
  3982. }
  3983. const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
  3984. if (vnodeHook) {
  3985. invokeVNodeHook(vnodeHook, instance.parent, vnode);
  3986. }
  3987. instance.isDeactivated = true;
  3988. }, parentSuspense);
  3989. {
  3990. // Update components tree
  3991. devtoolsComponentAdded(instance);
  3992. }
  3993. };
  3994. function unmount(vnode) {
  3995. // reset the shapeFlag so it can be properly unmounted
  3996. resetShapeFlag(vnode);
  3997. _unmount(vnode, instance, parentSuspense, true);
  3998. }
  3999. function pruneCache(filter) {
  4000. cache.forEach((vnode, key) => {
  4001. const name = getComponentName(vnode.type);
  4002. if (name && (!filter || !filter(name))) {
  4003. pruneCacheEntry(key);
  4004. }
  4005. });
  4006. }
  4007. function pruneCacheEntry(key) {
  4008. const cached = cache.get(key);
  4009. if (!current || cached.type !== current.type) {
  4010. unmount(cached);
  4011. }
  4012. else if (current) {
  4013. // current active instance should no longer be kept-alive.
  4014. // we can't unmount it now but it might be later, so reset its flag now.
  4015. resetShapeFlag(current);
  4016. }
  4017. cache.delete(key);
  4018. keys.delete(key);
  4019. }
  4020. // prune cache on include/exclude prop change
  4021. watch(() => [props.include, props.exclude], ([include, exclude]) => {
  4022. include && pruneCache(name => matches(include, name));
  4023. exclude && pruneCache(name => !matches(exclude, name));
  4024. },
  4025. // prune post-render after `current` has been updated
  4026. { flush: 'post', deep: true });
  4027. // cache sub tree after render
  4028. let pendingCacheKey = null;
  4029. const cacheSubtree = () => {
  4030. // fix #1621, the pendingCacheKey could be 0
  4031. if (pendingCacheKey != null) {
  4032. cache.set(pendingCacheKey, getInnerChild(instance.subTree));
  4033. }
  4034. };
  4035. onMounted(cacheSubtree);
  4036. onUpdated(cacheSubtree);
  4037. onBeforeUnmount(() => {
  4038. cache.forEach(cached => {
  4039. const { subTree, suspense } = instance;
  4040. const vnode = getInnerChild(subTree);
  4041. if (cached.type === vnode.type) {
  4042. // current instance will be unmounted as part of keep-alive's unmount
  4043. resetShapeFlag(vnode);
  4044. // but invoke its deactivated hook here
  4045. const da = vnode.component.da;
  4046. da && queuePostRenderEffect(da, suspense);
  4047. return;
  4048. }
  4049. unmount(cached);
  4050. });
  4051. });
  4052. return () => {
  4053. pendingCacheKey = null;
  4054. if (!slots.default) {
  4055. return null;
  4056. }
  4057. const children = slots.default();
  4058. const rawVNode = children[0];
  4059. if (children.length > 1) {
  4060. {
  4061. warn$1(`KeepAlive should contain exactly one component child.`);
  4062. }
  4063. current = null;
  4064. return children;
  4065. }
  4066. else if (!isVNode(rawVNode) ||
  4067. (!(rawVNode.shapeFlag & 4 /* ShapeFlags.STATEFUL_COMPONENT */) &&
  4068. !(rawVNode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */))) {
  4069. current = null;
  4070. return rawVNode;
  4071. }
  4072. let vnode = getInnerChild(rawVNode);
  4073. const comp = vnode.type;
  4074. // for async components, name check should be based in its loaded
  4075. // inner component if available
  4076. const name = getComponentName(isAsyncWrapper(vnode)
  4077. ? vnode.type.__asyncResolved || {}
  4078. : comp);
  4079. const { include, exclude, max } = props;
  4080. if ((include && (!name || !matches(include, name))) ||
  4081. (exclude && name && matches(exclude, name))) {
  4082. current = vnode;
  4083. return rawVNode;
  4084. }
  4085. const key = vnode.key == null ? comp : vnode.key;
  4086. const cachedVNode = cache.get(key);
  4087. // clone vnode if it's reused because we are going to mutate it
  4088. if (vnode.el) {
  4089. vnode = cloneVNode(vnode);
  4090. if (rawVNode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  4091. rawVNode.ssContent = vnode;
  4092. }
  4093. }
  4094. // #1513 it's possible for the returned vnode to be cloned due to attr
  4095. // fallthrough or scopeId, so the vnode here may not be the final vnode
  4096. // that is mounted. Instead of caching it directly, we store the pending
  4097. // key and cache `instance.subTree` (the normalized vnode) in
  4098. // beforeMount/beforeUpdate hooks.
  4099. pendingCacheKey = key;
  4100. if (cachedVNode) {
  4101. // copy over mounted state
  4102. vnode.el = cachedVNode.el;
  4103. vnode.component = cachedVNode.component;
  4104. if (vnode.transition) {
  4105. // recursively update transition hooks on subTree
  4106. setTransitionHooks(vnode, vnode.transition);
  4107. }
  4108. // avoid vnode being mounted as fresh
  4109. vnode.shapeFlag |= 512 /* ShapeFlags.COMPONENT_KEPT_ALIVE */;
  4110. // make this key the freshest
  4111. keys.delete(key);
  4112. keys.add(key);
  4113. }
  4114. else {
  4115. keys.add(key);
  4116. // prune oldest entry
  4117. if (max && keys.size > parseInt(max, 10)) {
  4118. pruneCacheEntry(keys.values().next().value);
  4119. }
  4120. }
  4121. // avoid vnode being unmounted
  4122. vnode.shapeFlag |= 256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */;
  4123. current = vnode;
  4124. return isSuspense(rawVNode.type) ? rawVNode : vnode;
  4125. };
  4126. }
  4127. };
  4128. // export the public type for h/tsx inference
  4129. // also to avoid inline import() in generated d.ts files
  4130. const KeepAlive = KeepAliveImpl;
  4131. function matches(pattern, name) {
  4132. if (isArray(pattern)) {
  4133. return pattern.some((p) => matches(p, name));
  4134. }
  4135. else if (isString(pattern)) {
  4136. return pattern.split(',').includes(name);
  4137. }
  4138. else if (pattern.test) {
  4139. return pattern.test(name);
  4140. }
  4141. /* istanbul ignore next */
  4142. return false;
  4143. }
  4144. function onActivated(hook, target) {
  4145. registerKeepAliveHook(hook, "a" /* LifecycleHooks.ACTIVATED */, target);
  4146. }
  4147. function onDeactivated(hook, target) {
  4148. registerKeepAliveHook(hook, "da" /* LifecycleHooks.DEACTIVATED */, target);
  4149. }
  4150. function registerKeepAliveHook(hook, type, target = currentInstance) {
  4151. // cache the deactivate branch check wrapper for injected hooks so the same
  4152. // hook can be properly deduped by the scheduler. "__wdc" stands for "with
  4153. // deactivation check".
  4154. const wrappedHook = hook.__wdc ||
  4155. (hook.__wdc = () => {
  4156. // only fire the hook if the target instance is NOT in a deactivated branch.
  4157. let current = target;
  4158. while (current) {
  4159. if (current.isDeactivated) {
  4160. return;
  4161. }
  4162. current = current.parent;
  4163. }
  4164. return hook();
  4165. });
  4166. injectHook(type, wrappedHook, target);
  4167. // In addition to registering it on the target instance, we walk up the parent
  4168. // chain and register it on all ancestor instances that are keep-alive roots.
  4169. // This avoids the need to walk the entire component tree when invoking these
  4170. // hooks, and more importantly, avoids the need to track child components in
  4171. // arrays.
  4172. if (target) {
  4173. let current = target.parent;
  4174. while (current && current.parent) {
  4175. if (isKeepAlive(current.parent.vnode)) {
  4176. injectToKeepAliveRoot(wrappedHook, type, target, current);
  4177. }
  4178. current = current.parent;
  4179. }
  4180. }
  4181. }
  4182. function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
  4183. // injectHook wraps the original for error handling, so make sure to remove
  4184. // the wrapped version.
  4185. const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
  4186. onUnmounted(() => {
  4187. remove(keepAliveRoot[type], injected);
  4188. }, target);
  4189. }
  4190. function resetShapeFlag(vnode) {
  4191. // bitwise operations to remove keep alive flags
  4192. vnode.shapeFlag &= ~256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */;
  4193. vnode.shapeFlag &= ~512 /* ShapeFlags.COMPONENT_KEPT_ALIVE */;
  4194. }
  4195. function getInnerChild(vnode) {
  4196. return vnode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */ ? vnode.ssContent : vnode;
  4197. }
  4198. function injectHook(type, hook, target = currentInstance, prepend = false) {
  4199. if (target) {
  4200. const hooks = target[type] || (target[type] = []);
  4201. // cache the error handling wrapper for injected hooks so the same hook
  4202. // can be properly deduped by the scheduler. "__weh" stands for "with error
  4203. // handling".
  4204. const wrappedHook = hook.__weh ||
  4205. (hook.__weh = (...args) => {
  4206. if (target.isUnmounted) {
  4207. return;
  4208. }
  4209. // disable tracking inside all lifecycle hooks
  4210. // since they can potentially be called inside effects.
  4211. pauseTracking();
  4212. // Set currentInstance during hook invocation.
  4213. // This assumes the hook does not synchronously trigger other hooks, which
  4214. // can only be false when the user does something really funky.
  4215. setCurrentInstance(target);
  4216. const res = callWithAsyncErrorHandling(hook, target, type, args);
  4217. unsetCurrentInstance();
  4218. resetTracking();
  4219. return res;
  4220. });
  4221. if (prepend) {
  4222. hooks.unshift(wrappedHook);
  4223. }
  4224. else {
  4225. hooks.push(wrappedHook);
  4226. }
  4227. return wrappedHook;
  4228. }
  4229. else {
  4230. const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
  4231. warn$1(`${apiName} is called when there is no active component instance to be ` +
  4232. `associated with. ` +
  4233. `Lifecycle injection APIs can only be used during execution of setup().` +
  4234. (` If you are using async setup(), make sure to register lifecycle ` +
  4235. `hooks before the first await statement.`
  4236. ));
  4237. }
  4238. }
  4239. const createHook = (lifecycle) => (hook, target = currentInstance) =>
  4240. // post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
  4241. (!isInSSRComponentSetup || lifecycle === "sp" /* LifecycleHooks.SERVER_PREFETCH */) &&
  4242. injectHook(lifecycle, (...args) => hook(...args), target);
  4243. const onBeforeMount = createHook("bm" /* LifecycleHooks.BEFORE_MOUNT */);
  4244. const onMounted = createHook("m" /* LifecycleHooks.MOUNTED */);
  4245. const onBeforeUpdate = createHook("bu" /* LifecycleHooks.BEFORE_UPDATE */);
  4246. const onUpdated = createHook("u" /* LifecycleHooks.UPDATED */);
  4247. const onBeforeUnmount = createHook("bum" /* LifecycleHooks.BEFORE_UNMOUNT */);
  4248. const onUnmounted = createHook("um" /* LifecycleHooks.UNMOUNTED */);
  4249. const onServerPrefetch = createHook("sp" /* LifecycleHooks.SERVER_PREFETCH */);
  4250. const onRenderTriggered = createHook("rtg" /* LifecycleHooks.RENDER_TRIGGERED */);
  4251. const onRenderTracked = createHook("rtc" /* LifecycleHooks.RENDER_TRACKED */);
  4252. function onErrorCaptured(hook, target = currentInstance) {
  4253. injectHook("ec" /* LifecycleHooks.ERROR_CAPTURED */, hook, target);
  4254. }
  4255. /**
  4256. Runtime helper for applying directives to a vnode. Example usage:
  4257. const comp = resolveComponent('comp')
  4258. const foo = resolveDirective('foo')
  4259. const bar = resolveDirective('bar')
  4260. return withDirectives(h(comp), [
  4261. [foo, this.x],
  4262. [bar, this.y]
  4263. ])
  4264. */
  4265. function validateDirectiveName(name) {
  4266. if (isBuiltInDirective(name)) {
  4267. warn$1('Do not use built-in directive ids as custom directive id: ' + name);
  4268. }
  4269. }
  4270. /**
  4271. * Adds directives to a VNode.
  4272. */
  4273. function withDirectives(vnode, directives) {
  4274. const internalInstance = currentRenderingInstance;
  4275. if (internalInstance === null) {
  4276. warn$1(`withDirectives can only be used inside render functions.`);
  4277. return vnode;
  4278. }
  4279. const instance = getExposeProxy(internalInstance) ||
  4280. internalInstance.proxy;
  4281. const bindings = vnode.dirs || (vnode.dirs = []);
  4282. for (let i = 0; i < directives.length; i++) {
  4283. let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
  4284. if (dir) {
  4285. if (isFunction(dir)) {
  4286. dir = {
  4287. mounted: dir,
  4288. updated: dir
  4289. };
  4290. }
  4291. if (dir.deep) {
  4292. traverse(value);
  4293. }
  4294. bindings.push({
  4295. dir,
  4296. instance,
  4297. value,
  4298. oldValue: void 0,
  4299. arg,
  4300. modifiers
  4301. });
  4302. }
  4303. }
  4304. return vnode;
  4305. }
  4306. function invokeDirectiveHook(vnode, prevVNode, instance, name) {
  4307. const bindings = vnode.dirs;
  4308. const oldBindings = prevVNode && prevVNode.dirs;
  4309. for (let i = 0; i < bindings.length; i++) {
  4310. const binding = bindings[i];
  4311. if (oldBindings) {
  4312. binding.oldValue = oldBindings[i].value;
  4313. }
  4314. let hook = binding.dir[name];
  4315. if (hook) {
  4316. // disable tracking inside all lifecycle hooks
  4317. // since they can potentially be called inside effects.
  4318. pauseTracking();
  4319. callWithAsyncErrorHandling(hook, instance, 8 /* ErrorCodes.DIRECTIVE_HOOK */, [
  4320. vnode.el,
  4321. binding,
  4322. vnode,
  4323. prevVNode
  4324. ]);
  4325. resetTracking();
  4326. }
  4327. }
  4328. }
  4329. const COMPONENTS = 'components';
  4330. const DIRECTIVES = 'directives';
  4331. /**
  4332. * @private
  4333. */
  4334. function resolveComponent(name, maybeSelfReference) {
  4335. return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
  4336. }
  4337. const NULL_DYNAMIC_COMPONENT = Symbol();
  4338. /**
  4339. * @private
  4340. */
  4341. function resolveDynamicComponent(component) {
  4342. if (isString(component)) {
  4343. return resolveAsset(COMPONENTS, component, false) || component;
  4344. }
  4345. else {
  4346. // invalid types will fallthrough to createVNode and raise warning
  4347. return (component || NULL_DYNAMIC_COMPONENT);
  4348. }
  4349. }
  4350. /**
  4351. * @private
  4352. */
  4353. function resolveDirective(name) {
  4354. return resolveAsset(DIRECTIVES, name);
  4355. }
  4356. // implementation
  4357. function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
  4358. const instance = currentRenderingInstance || currentInstance;
  4359. if (instance) {
  4360. const Component = instance.type;
  4361. // explicit self name has highest priority
  4362. if (type === COMPONENTS) {
  4363. const selfName = getComponentName(Component, false /* do not include inferred name to avoid breaking existing code */);
  4364. if (selfName &&
  4365. (selfName === name ||
  4366. selfName === camelize(name) ||
  4367. selfName === capitalize(camelize(name)))) {
  4368. return Component;
  4369. }
  4370. }
  4371. const res =
  4372. // local registration
  4373. // check instance[type] first which is resolved for options API
  4374. resolve(instance[type] || Component[type], name) ||
  4375. // global registration
  4376. resolve(instance.appContext[type], name);
  4377. if (!res && maybeSelfReference) {
  4378. // fallback to implicit self-reference
  4379. return Component;
  4380. }
  4381. if (warnMissing && !res) {
  4382. const extra = type === COMPONENTS
  4383. ? `\nIf this is a native custom element, make sure to exclude it from ` +
  4384. `component resolution via compilerOptions.isCustomElement.`
  4385. : ``;
  4386. warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`);
  4387. }
  4388. return res;
  4389. }
  4390. else {
  4391. warn$1(`resolve${capitalize(type.slice(0, -1))} ` +
  4392. `can only be used in render() or setup().`);
  4393. }
  4394. }
  4395. function resolve(registry, name) {
  4396. return (registry &&
  4397. (registry[name] ||
  4398. registry[camelize(name)] ||
  4399. registry[capitalize(camelize(name))]));
  4400. }
  4401. /**
  4402. * Actual implementation
  4403. */
  4404. function renderList(source, renderItem, cache, index) {
  4405. let ret;
  4406. const cached = (cache && cache[index]);
  4407. if (isArray(source) || isString(source)) {
  4408. ret = new Array(source.length);
  4409. for (let i = 0, l = source.length; i < l; i++) {
  4410. ret[i] = renderItem(source[i], i, undefined, cached && cached[i]);
  4411. }
  4412. }
  4413. else if (typeof source === 'number') {
  4414. if (!Number.isInteger(source)) {
  4415. warn$1(`The v-for range expect an integer value but got ${source}.`);
  4416. }
  4417. ret = new Array(source);
  4418. for (let i = 0; i < source; i++) {
  4419. ret[i] = renderItem(i + 1, i, undefined, cached && cached[i]);
  4420. }
  4421. }
  4422. else if (isObject(source)) {
  4423. if (source[Symbol.iterator]) {
  4424. ret = Array.from(source, (item, i) => renderItem(item, i, undefined, cached && cached[i]));
  4425. }
  4426. else {
  4427. const keys = Object.keys(source);
  4428. ret = new Array(keys.length);
  4429. for (let i = 0, l = keys.length; i < l; i++) {
  4430. const key = keys[i];
  4431. ret[i] = renderItem(source[key], key, i, cached && cached[i]);
  4432. }
  4433. }
  4434. }
  4435. else {
  4436. ret = [];
  4437. }
  4438. if (cache) {
  4439. cache[index] = ret;
  4440. }
  4441. return ret;
  4442. }
  4443. /**
  4444. * Compiler runtime helper for creating dynamic slots object
  4445. * @private
  4446. */
  4447. function createSlots(slots, dynamicSlots) {
  4448. for (let i = 0; i < dynamicSlots.length; i++) {
  4449. const slot = dynamicSlots[i];
  4450. // array of dynamic slot generated by <template v-for="..." #[...]>
  4451. if (isArray(slot)) {
  4452. for (let j = 0; j < slot.length; j++) {
  4453. slots[slot[j].name] = slot[j].fn;
  4454. }
  4455. }
  4456. else if (slot) {
  4457. // conditional single slot generated by <template v-if="..." #foo>
  4458. slots[slot.name] = slot.key
  4459. ? (...args) => {
  4460. const res = slot.fn(...args);
  4461. // attach branch key so each conditional branch is considered a
  4462. // different fragment
  4463. if (res)
  4464. res.key = slot.key;
  4465. return res;
  4466. }
  4467. : slot.fn;
  4468. }
  4469. }
  4470. return slots;
  4471. }
  4472. /**
  4473. * Compiler runtime helper for rendering `<slot/>`
  4474. * @private
  4475. */
  4476. function renderSlot(slots, name, props = {},
  4477. // this is not a user-facing function, so the fallback is always generated by
  4478. // the compiler and guaranteed to be a function returning an array
  4479. fallback, noSlotted) {
  4480. if (currentRenderingInstance.isCE ||
  4481. (currentRenderingInstance.parent &&
  4482. isAsyncWrapper(currentRenderingInstance.parent) &&
  4483. currentRenderingInstance.parent.isCE)) {
  4484. if (name !== 'default')
  4485. props.name = name;
  4486. return createVNode('slot', props, fallback && fallback());
  4487. }
  4488. let slot = slots[name];
  4489. if (slot && slot.length > 1) {
  4490. warn$1(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
  4491. `function. You need to mark this component with $dynamic-slots in the ` +
  4492. `parent template.`);
  4493. slot = () => [];
  4494. }
  4495. // a compiled slot disables block tracking by default to avoid manual
  4496. // invocation interfering with template-based block tracking, but in
  4497. // `renderSlot` we can be sure that it's template-based so we can force
  4498. // enable it.
  4499. if (slot && slot._c) {
  4500. slot._d = false;
  4501. }
  4502. openBlock();
  4503. const validSlotContent = slot && ensureValidVNode(slot(props));
  4504. const rendered = createBlock(Fragment, {
  4505. key: props.key ||
  4506. // slot content array of a dynamic conditional slot may have a branch
  4507. // key attached in the `createSlots` helper, respect that
  4508. (validSlotContent && validSlotContent.key) ||
  4509. `_${name}`
  4510. }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* SlotFlags.STABLE */
  4511. ? 64 /* PatchFlags.STABLE_FRAGMENT */
  4512. : -2 /* PatchFlags.BAIL */);
  4513. if (!noSlotted && rendered.scopeId) {
  4514. rendered.slotScopeIds = [rendered.scopeId + '-s'];
  4515. }
  4516. if (slot && slot._c) {
  4517. slot._d = true;
  4518. }
  4519. return rendered;
  4520. }
  4521. function ensureValidVNode(vnodes) {
  4522. return vnodes.some(child => {
  4523. if (!isVNode(child))
  4524. return true;
  4525. if (child.type === Comment)
  4526. return false;
  4527. if (child.type === Fragment &&
  4528. !ensureValidVNode(child.children))
  4529. return false;
  4530. return true;
  4531. })
  4532. ? vnodes
  4533. : null;
  4534. }
  4535. /**
  4536. * For prefixing keys in v-on="obj" with "on"
  4537. * @private
  4538. */
  4539. function toHandlers(obj, preserveCaseIfNecessary) {
  4540. const ret = {};
  4541. if (!isObject(obj)) {
  4542. warn$1(`v-on with no argument expects an object value.`);
  4543. return ret;
  4544. }
  4545. for (const key in obj) {
  4546. ret[preserveCaseIfNecessary && /[A-Z]/.test(key)
  4547. ? `on:${key}`
  4548. : toHandlerKey(key)] = obj[key];
  4549. }
  4550. return ret;
  4551. }
  4552. /**
  4553. * #2437 In Vue 3, functional components do not have a public instance proxy but
  4554. * they exist in the internal parent chain. For code that relies on traversing
  4555. * public $parent chains, skip functional ones and go to the parent instead.
  4556. */
  4557. const getPublicInstance = (i) => {
  4558. if (!i)
  4559. return null;
  4560. if (isStatefulComponent(i))
  4561. return getExposeProxy(i) || i.proxy;
  4562. return getPublicInstance(i.parent);
  4563. };
  4564. const publicPropertiesMap =
  4565. // Move PURE marker to new line to workaround compiler discarding it
  4566. // due to type annotation
  4567. /*#__PURE__*/ extend(Object.create(null), {
  4568. $: i => i,
  4569. $el: i => i.vnode.el,
  4570. $data: i => i.data,
  4571. $props: i => (shallowReadonly(i.props) ),
  4572. $attrs: i => (shallowReadonly(i.attrs) ),
  4573. $slots: i => (shallowReadonly(i.slots) ),
  4574. $refs: i => (shallowReadonly(i.refs) ),
  4575. $parent: i => getPublicInstance(i.parent),
  4576. $root: i => getPublicInstance(i.root),
  4577. $emit: i => i.emit,
  4578. $options: i => (resolveMergedOptions(i) ),
  4579. $forceUpdate: i => i.f || (i.f = () => queueJob(i.update)),
  4580. $nextTick: i => i.n || (i.n = nextTick.bind(i.proxy)),
  4581. $watch: i => (instanceWatch.bind(i) )
  4582. });
  4583. const isReservedPrefix = (key) => key === '_' || key === '$';
  4584. const hasSetupBinding = (state, key) => state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn(state, key);
  4585. const PublicInstanceProxyHandlers = {
  4586. get({ _: instance }, key) {
  4587. const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
  4588. // for internal formatters to know that this is a Vue instance
  4589. if (key === '__isVue') {
  4590. return true;
  4591. }
  4592. // data / props / ctx
  4593. // This getter gets called for every property access on the render context
  4594. // during render and is a major hotspot. The most expensive part of this
  4595. // is the multiple hasOwn() calls. It's much faster to do a simple property
  4596. // access on a plain object, so we use an accessCache object (with null
  4597. // prototype) to memoize what access type a key corresponds to.
  4598. let normalizedProps;
  4599. if (key[0] !== '$') {
  4600. const n = accessCache[key];
  4601. if (n !== undefined) {
  4602. switch (n) {
  4603. case 1 /* AccessTypes.SETUP */:
  4604. return setupState[key];
  4605. case 2 /* AccessTypes.DATA */:
  4606. return data[key];
  4607. case 4 /* AccessTypes.CONTEXT */:
  4608. return ctx[key];
  4609. case 3 /* AccessTypes.PROPS */:
  4610. return props[key];
  4611. // default: just fallthrough
  4612. }
  4613. }
  4614. else if (hasSetupBinding(setupState, key)) {
  4615. accessCache[key] = 1 /* AccessTypes.SETUP */;
  4616. return setupState[key];
  4617. }
  4618. else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  4619. accessCache[key] = 2 /* AccessTypes.DATA */;
  4620. return data[key];
  4621. }
  4622. else if (
  4623. // only cache other properties when instance has declared (thus stable)
  4624. // props
  4625. (normalizedProps = instance.propsOptions[0]) &&
  4626. hasOwn(normalizedProps, key)) {
  4627. accessCache[key] = 3 /* AccessTypes.PROPS */;
  4628. return props[key];
  4629. }
  4630. else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  4631. accessCache[key] = 4 /* AccessTypes.CONTEXT */;
  4632. return ctx[key];
  4633. }
  4634. else if (shouldCacheAccess) {
  4635. accessCache[key] = 0 /* AccessTypes.OTHER */;
  4636. }
  4637. }
  4638. const publicGetter = publicPropertiesMap[key];
  4639. let cssModule, globalProperties;
  4640. // public $xxx properties
  4641. if (publicGetter) {
  4642. if (key === '$attrs') {
  4643. track(instance, "get" /* TrackOpTypes.GET */, key);
  4644. markAttrsAccessed();
  4645. }
  4646. return publicGetter(instance);
  4647. }
  4648. else if (
  4649. // css module (injected by vue-loader)
  4650. (cssModule = type.__cssModules) &&
  4651. (cssModule = cssModule[key])) {
  4652. return cssModule;
  4653. }
  4654. else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  4655. // user may set custom properties to `this` that start with `$`
  4656. accessCache[key] = 4 /* AccessTypes.CONTEXT */;
  4657. return ctx[key];
  4658. }
  4659. else if (
  4660. // global properties
  4661. ((globalProperties = appContext.config.globalProperties),
  4662. hasOwn(globalProperties, key))) {
  4663. {
  4664. return globalProperties[key];
  4665. }
  4666. }
  4667. else if (currentRenderingInstance &&
  4668. (!isString(key) ||
  4669. // #1091 avoid internal isRef/isVNode checks on component instance leading
  4670. // to infinite warning loop
  4671. key.indexOf('__v') !== 0)) {
  4672. if (data !== EMPTY_OBJ && isReservedPrefix(key[0]) && hasOwn(data, key)) {
  4673. warn$1(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
  4674. `character ("$" or "_") and is not proxied on the render context.`);
  4675. }
  4676. else if (instance === currentRenderingInstance) {
  4677. warn$1(`Property ${JSON.stringify(key)} was accessed during render ` +
  4678. `but is not defined on instance.`);
  4679. }
  4680. }
  4681. },
  4682. set({ _: instance }, key, value) {
  4683. const { data, setupState, ctx } = instance;
  4684. if (hasSetupBinding(setupState, key)) {
  4685. setupState[key] = value;
  4686. return true;
  4687. }
  4688. else if (setupState.__isScriptSetup &&
  4689. hasOwn(setupState, key)) {
  4690. warn$1(`Cannot mutate <script setup> binding "${key}" from Options API.`);
  4691. return false;
  4692. }
  4693. else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  4694. data[key] = value;
  4695. return true;
  4696. }
  4697. else if (hasOwn(instance.props, key)) {
  4698. warn$1(`Attempting to mutate prop "${key}". Props are readonly.`);
  4699. return false;
  4700. }
  4701. if (key[0] === '$' && key.slice(1) in instance) {
  4702. warn$1(`Attempting to mutate public property "${key}". ` +
  4703. `Properties starting with $ are reserved and readonly.`);
  4704. return false;
  4705. }
  4706. else {
  4707. if (key in instance.appContext.config.globalProperties) {
  4708. Object.defineProperty(ctx, key, {
  4709. enumerable: true,
  4710. configurable: true,
  4711. value
  4712. });
  4713. }
  4714. else {
  4715. ctx[key] = value;
  4716. }
  4717. }
  4718. return true;
  4719. },
  4720. has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
  4721. let normalizedProps;
  4722. return (!!accessCache[key] ||
  4723. (data !== EMPTY_OBJ && hasOwn(data, key)) ||
  4724. hasSetupBinding(setupState, key) ||
  4725. ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
  4726. hasOwn(ctx, key) ||
  4727. hasOwn(publicPropertiesMap, key) ||
  4728. hasOwn(appContext.config.globalProperties, key));
  4729. },
  4730. defineProperty(target, key, descriptor) {
  4731. if (descriptor.get != null) {
  4732. // invalidate key cache of a getter based property #5417
  4733. target._.accessCache[key] = 0;
  4734. }
  4735. else if (hasOwn(descriptor, 'value')) {
  4736. this.set(target, key, descriptor.value, null);
  4737. }
  4738. return Reflect.defineProperty(target, key, descriptor);
  4739. }
  4740. };
  4741. {
  4742. PublicInstanceProxyHandlers.ownKeys = (target) => {
  4743. warn$1(`Avoid app logic that relies on enumerating keys on a component instance. ` +
  4744. `The keys will be empty in production mode to avoid performance overhead.`);
  4745. return Reflect.ownKeys(target);
  4746. };
  4747. }
  4748. const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend({}, PublicInstanceProxyHandlers, {
  4749. get(target, key) {
  4750. // fast path for unscopables when using `with` block
  4751. if (key === Symbol.unscopables) {
  4752. return;
  4753. }
  4754. return PublicInstanceProxyHandlers.get(target, key, target);
  4755. },
  4756. has(_, key) {
  4757. const has = key[0] !== '_' && !isGloballyWhitelisted(key);
  4758. if (!has && PublicInstanceProxyHandlers.has(_, key)) {
  4759. warn$1(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
  4760. }
  4761. return has;
  4762. }
  4763. });
  4764. // dev only
  4765. // In dev mode, the proxy target exposes the same properties as seen on `this`
  4766. // for easier console inspection. In prod mode it will be an empty object so
  4767. // these properties definitions can be skipped.
  4768. function createDevRenderContext(instance) {
  4769. const target = {};
  4770. // expose internal instance for proxy handlers
  4771. Object.defineProperty(target, `_`, {
  4772. configurable: true,
  4773. enumerable: false,
  4774. get: () => instance
  4775. });
  4776. // expose public properties
  4777. Object.keys(publicPropertiesMap).forEach(key => {
  4778. Object.defineProperty(target, key, {
  4779. configurable: true,
  4780. enumerable: false,
  4781. get: () => publicPropertiesMap[key](instance),
  4782. // intercepted by the proxy so no need for implementation,
  4783. // but needed to prevent set errors
  4784. set: NOOP
  4785. });
  4786. });
  4787. return target;
  4788. }
  4789. // dev only
  4790. function exposePropsOnRenderContext(instance) {
  4791. const { ctx, propsOptions: [propsOptions] } = instance;
  4792. if (propsOptions) {
  4793. Object.keys(propsOptions).forEach(key => {
  4794. Object.defineProperty(ctx, key, {
  4795. enumerable: true,
  4796. configurable: true,
  4797. get: () => instance.props[key],
  4798. set: NOOP
  4799. });
  4800. });
  4801. }
  4802. }
  4803. // dev only
  4804. function exposeSetupStateOnRenderContext(instance) {
  4805. const { ctx, setupState } = instance;
  4806. Object.keys(toRaw(setupState)).forEach(key => {
  4807. if (!setupState.__isScriptSetup) {
  4808. if (isReservedPrefix(key[0])) {
  4809. warn$1(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
  4810. `which are reserved prefixes for Vue internals.`);
  4811. return;
  4812. }
  4813. Object.defineProperty(ctx, key, {
  4814. enumerable: true,
  4815. configurable: true,
  4816. get: () => setupState[key],
  4817. set: NOOP
  4818. });
  4819. }
  4820. });
  4821. }
  4822. function createDuplicateChecker() {
  4823. const cache = Object.create(null);
  4824. return (type, key) => {
  4825. if (cache[key]) {
  4826. warn$1(`${type} property "${key}" is already defined in ${cache[key]}.`);
  4827. }
  4828. else {
  4829. cache[key] = type;
  4830. }
  4831. };
  4832. }
  4833. let shouldCacheAccess = true;
  4834. function applyOptions(instance) {
  4835. const options = resolveMergedOptions(instance);
  4836. const publicThis = instance.proxy;
  4837. const ctx = instance.ctx;
  4838. // do not cache property access on public proxy during state initialization
  4839. shouldCacheAccess = false;
  4840. // call beforeCreate first before accessing other options since
  4841. // the hook may mutate resolved options (#2791)
  4842. if (options.beforeCreate) {
  4843. callHook(options.beforeCreate, instance, "bc" /* LifecycleHooks.BEFORE_CREATE */);
  4844. }
  4845. const {
  4846. // state
  4847. data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
  4848. // lifecycle
  4849. created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch,
  4850. // public API
  4851. expose, inheritAttrs,
  4852. // assets
  4853. components, directives, filters } = options;
  4854. const checkDuplicateProperties = createDuplicateChecker() ;
  4855. {
  4856. const [propsOptions] = instance.propsOptions;
  4857. if (propsOptions) {
  4858. for (const key in propsOptions) {
  4859. checkDuplicateProperties("Props" /* OptionTypes.PROPS */, key);
  4860. }
  4861. }
  4862. }
  4863. // options initialization order (to be consistent with Vue 2):
  4864. // - props (already done outside of this function)
  4865. // - inject
  4866. // - methods
  4867. // - data (deferred since it relies on `this` access)
  4868. // - computed
  4869. // - watch (deferred since it relies on `this` access)
  4870. if (injectOptions) {
  4871. resolveInjections(injectOptions, ctx, checkDuplicateProperties, instance.appContext.config.unwrapInjectedRef);
  4872. }
  4873. if (methods) {
  4874. for (const key in methods) {
  4875. const methodHandler = methods[key];
  4876. if (isFunction(methodHandler)) {
  4877. // In dev mode, we use the `createRenderContext` function to define
  4878. // methods to the proxy target, and those are read-only but
  4879. // reconfigurable, so it needs to be redefined here
  4880. {
  4881. Object.defineProperty(ctx, key, {
  4882. value: methodHandler.bind(publicThis),
  4883. configurable: true,
  4884. enumerable: true,
  4885. writable: true
  4886. });
  4887. }
  4888. {
  4889. checkDuplicateProperties("Methods" /* OptionTypes.METHODS */, key);
  4890. }
  4891. }
  4892. else {
  4893. warn$1(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
  4894. `Did you reference the function correctly?`);
  4895. }
  4896. }
  4897. }
  4898. if (dataOptions) {
  4899. if (!isFunction(dataOptions)) {
  4900. warn$1(`The data option must be a function. ` +
  4901. `Plain object usage is no longer supported.`);
  4902. }
  4903. const data = dataOptions.call(publicThis, publicThis);
  4904. if (isPromise(data)) {
  4905. warn$1(`data() returned a Promise - note data() cannot be async; If you ` +
  4906. `intend to perform data fetching before component renders, use ` +
  4907. `async setup() + <Suspense>.`);
  4908. }
  4909. if (!isObject(data)) {
  4910. warn$1(`data() should return an object.`);
  4911. }
  4912. else {
  4913. instance.data = reactive(data);
  4914. {
  4915. for (const key in data) {
  4916. checkDuplicateProperties("Data" /* OptionTypes.DATA */, key);
  4917. // expose data on ctx during dev
  4918. if (!isReservedPrefix(key[0])) {
  4919. Object.defineProperty(ctx, key, {
  4920. configurable: true,
  4921. enumerable: true,
  4922. get: () => data[key],
  4923. set: NOOP
  4924. });
  4925. }
  4926. }
  4927. }
  4928. }
  4929. }
  4930. // state initialization complete at this point - start caching access
  4931. shouldCacheAccess = true;
  4932. if (computedOptions) {
  4933. for (const key in computedOptions) {
  4934. const opt = computedOptions[key];
  4935. const get = isFunction(opt)
  4936. ? opt.bind(publicThis, publicThis)
  4937. : isFunction(opt.get)
  4938. ? opt.get.bind(publicThis, publicThis)
  4939. : NOOP;
  4940. if (get === NOOP) {
  4941. warn$1(`Computed property "${key}" has no getter.`);
  4942. }
  4943. const set = !isFunction(opt) && isFunction(opt.set)
  4944. ? opt.set.bind(publicThis)
  4945. : () => {
  4946. warn$1(`Write operation failed: computed property "${key}" is readonly.`);
  4947. }
  4948. ;
  4949. const c = computed$1({
  4950. get,
  4951. set
  4952. });
  4953. Object.defineProperty(ctx, key, {
  4954. enumerable: true,
  4955. configurable: true,
  4956. get: () => c.value,
  4957. set: v => (c.value = v)
  4958. });
  4959. {
  4960. checkDuplicateProperties("Computed" /* OptionTypes.COMPUTED */, key);
  4961. }
  4962. }
  4963. }
  4964. if (watchOptions) {
  4965. for (const key in watchOptions) {
  4966. createWatcher(watchOptions[key], ctx, publicThis, key);
  4967. }
  4968. }
  4969. if (provideOptions) {
  4970. const provides = isFunction(provideOptions)
  4971. ? provideOptions.call(publicThis)
  4972. : provideOptions;
  4973. Reflect.ownKeys(provides).forEach(key => {
  4974. provide(key, provides[key]);
  4975. });
  4976. }
  4977. if (created) {
  4978. callHook(created, instance, "c" /* LifecycleHooks.CREATED */);
  4979. }
  4980. function registerLifecycleHook(register, hook) {
  4981. if (isArray(hook)) {
  4982. hook.forEach(_hook => register(_hook.bind(publicThis)));
  4983. }
  4984. else if (hook) {
  4985. register(hook.bind(publicThis));
  4986. }
  4987. }
  4988. registerLifecycleHook(onBeforeMount, beforeMount);
  4989. registerLifecycleHook(onMounted, mounted);
  4990. registerLifecycleHook(onBeforeUpdate, beforeUpdate);
  4991. registerLifecycleHook(onUpdated, updated);
  4992. registerLifecycleHook(onActivated, activated);
  4993. registerLifecycleHook(onDeactivated, deactivated);
  4994. registerLifecycleHook(onErrorCaptured, errorCaptured);
  4995. registerLifecycleHook(onRenderTracked, renderTracked);
  4996. registerLifecycleHook(onRenderTriggered, renderTriggered);
  4997. registerLifecycleHook(onBeforeUnmount, beforeUnmount);
  4998. registerLifecycleHook(onUnmounted, unmounted);
  4999. registerLifecycleHook(onServerPrefetch, serverPrefetch);
  5000. if (isArray(expose)) {
  5001. if (expose.length) {
  5002. const exposed = instance.exposed || (instance.exposed = {});
  5003. expose.forEach(key => {
  5004. Object.defineProperty(exposed, key, {
  5005. get: () => publicThis[key],
  5006. set: val => (publicThis[key] = val)
  5007. });
  5008. });
  5009. }
  5010. else if (!instance.exposed) {
  5011. instance.exposed = {};
  5012. }
  5013. }
  5014. // options that are handled when creating the instance but also need to be
  5015. // applied from mixins
  5016. if (render && instance.render === NOOP) {
  5017. instance.render = render;
  5018. }
  5019. if (inheritAttrs != null) {
  5020. instance.inheritAttrs = inheritAttrs;
  5021. }
  5022. // asset options.
  5023. if (components)
  5024. instance.components = components;
  5025. if (directives)
  5026. instance.directives = directives;
  5027. }
  5028. function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP, unwrapRef = false) {
  5029. if (isArray(injectOptions)) {
  5030. injectOptions = normalizeInject(injectOptions);
  5031. }
  5032. for (const key in injectOptions) {
  5033. const opt = injectOptions[key];
  5034. let injected;
  5035. if (isObject(opt)) {
  5036. if ('default' in opt) {
  5037. injected = inject(opt.from || key, opt.default, true /* treat default function as factory */);
  5038. }
  5039. else {
  5040. injected = inject(opt.from || key);
  5041. }
  5042. }
  5043. else {
  5044. injected = inject(opt);
  5045. }
  5046. if (isRef(injected)) {
  5047. // TODO remove the check in 3.3
  5048. if (unwrapRef) {
  5049. Object.defineProperty(ctx, key, {
  5050. enumerable: true,
  5051. configurable: true,
  5052. get: () => injected.value,
  5053. set: v => (injected.value = v)
  5054. });
  5055. }
  5056. else {
  5057. {
  5058. warn$1(`injected property "${key}" is a ref and will be auto-unwrapped ` +
  5059. `and no longer needs \`.value\` in the next minor release. ` +
  5060. `To opt-in to the new behavior now, ` +
  5061. `set \`app.config.unwrapInjectedRef = true\` (this config is ` +
  5062. `temporary and will not be needed in the future.)`);
  5063. }
  5064. ctx[key] = injected;
  5065. }
  5066. }
  5067. else {
  5068. ctx[key] = injected;
  5069. }
  5070. {
  5071. checkDuplicateProperties("Inject" /* OptionTypes.INJECT */, key);
  5072. }
  5073. }
  5074. }
  5075. function callHook(hook, instance, type) {
  5076. callWithAsyncErrorHandling(isArray(hook)
  5077. ? hook.map(h => h.bind(instance.proxy))
  5078. : hook.bind(instance.proxy), instance, type);
  5079. }
  5080. function createWatcher(raw, ctx, publicThis, key) {
  5081. const getter = key.includes('.')
  5082. ? createPathGetter(publicThis, key)
  5083. : () => publicThis[key];
  5084. if (isString(raw)) {
  5085. const handler = ctx[raw];
  5086. if (isFunction(handler)) {
  5087. watch(getter, handler);
  5088. }
  5089. else {
  5090. warn$1(`Invalid watch handler specified by key "${raw}"`, handler);
  5091. }
  5092. }
  5093. else if (isFunction(raw)) {
  5094. watch(getter, raw.bind(publicThis));
  5095. }
  5096. else if (isObject(raw)) {
  5097. if (isArray(raw)) {
  5098. raw.forEach(r => createWatcher(r, ctx, publicThis, key));
  5099. }
  5100. else {
  5101. const handler = isFunction(raw.handler)
  5102. ? raw.handler.bind(publicThis)
  5103. : ctx[raw.handler];
  5104. if (isFunction(handler)) {
  5105. watch(getter, handler, raw);
  5106. }
  5107. else {
  5108. warn$1(`Invalid watch handler specified by key "${raw.handler}"`, handler);
  5109. }
  5110. }
  5111. }
  5112. else {
  5113. warn$1(`Invalid watch option: "${key}"`, raw);
  5114. }
  5115. }
  5116. /**
  5117. * Resolve merged options and cache it on the component.
  5118. * This is done only once per-component since the merging does not involve
  5119. * instances.
  5120. */
  5121. function resolveMergedOptions(instance) {
  5122. const base = instance.type;
  5123. const { mixins, extends: extendsOptions } = base;
  5124. const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext;
  5125. const cached = cache.get(base);
  5126. let resolved;
  5127. if (cached) {
  5128. resolved = cached;
  5129. }
  5130. else if (!globalMixins.length && !mixins && !extendsOptions) {
  5131. {
  5132. resolved = base;
  5133. }
  5134. }
  5135. else {
  5136. resolved = {};
  5137. if (globalMixins.length) {
  5138. globalMixins.forEach(m => mergeOptions(resolved, m, optionMergeStrategies, true));
  5139. }
  5140. mergeOptions(resolved, base, optionMergeStrategies);
  5141. }
  5142. if (isObject(base)) {
  5143. cache.set(base, resolved);
  5144. }
  5145. return resolved;
  5146. }
  5147. function mergeOptions(to, from, strats, asMixin = false) {
  5148. const { mixins, extends: extendsOptions } = from;
  5149. if (extendsOptions) {
  5150. mergeOptions(to, extendsOptions, strats, true);
  5151. }
  5152. if (mixins) {
  5153. mixins.forEach((m) => mergeOptions(to, m, strats, true));
  5154. }
  5155. for (const key in from) {
  5156. if (asMixin && key === 'expose') {
  5157. warn$1(`"expose" option is ignored when declared in mixins or extends. ` +
  5158. `It should only be declared in the base component itself.`);
  5159. }
  5160. else {
  5161. const strat = internalOptionMergeStrats[key] || (strats && strats[key]);
  5162. to[key] = strat ? strat(to[key], from[key]) : from[key];
  5163. }
  5164. }
  5165. return to;
  5166. }
  5167. const internalOptionMergeStrats = {
  5168. data: mergeDataFn,
  5169. props: mergeObjectOptions,
  5170. emits: mergeObjectOptions,
  5171. // objects
  5172. methods: mergeObjectOptions,
  5173. computed: mergeObjectOptions,
  5174. // lifecycle
  5175. beforeCreate: mergeAsArray,
  5176. created: mergeAsArray,
  5177. beforeMount: mergeAsArray,
  5178. mounted: mergeAsArray,
  5179. beforeUpdate: mergeAsArray,
  5180. updated: mergeAsArray,
  5181. beforeDestroy: mergeAsArray,
  5182. beforeUnmount: mergeAsArray,
  5183. destroyed: mergeAsArray,
  5184. unmounted: mergeAsArray,
  5185. activated: mergeAsArray,
  5186. deactivated: mergeAsArray,
  5187. errorCaptured: mergeAsArray,
  5188. serverPrefetch: mergeAsArray,
  5189. // assets
  5190. components: mergeObjectOptions,
  5191. directives: mergeObjectOptions,
  5192. // watch
  5193. watch: mergeWatchOptions,
  5194. // provide / inject
  5195. provide: mergeDataFn,
  5196. inject: mergeInject
  5197. };
  5198. function mergeDataFn(to, from) {
  5199. if (!from) {
  5200. return to;
  5201. }
  5202. if (!to) {
  5203. return from;
  5204. }
  5205. return function mergedDataFn() {
  5206. return (extend)(isFunction(to) ? to.call(this, this) : to, isFunction(from) ? from.call(this, this) : from);
  5207. };
  5208. }
  5209. function mergeInject(to, from) {
  5210. return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
  5211. }
  5212. function normalizeInject(raw) {
  5213. if (isArray(raw)) {
  5214. const res = {};
  5215. for (let i = 0; i < raw.length; i++) {
  5216. res[raw[i]] = raw[i];
  5217. }
  5218. return res;
  5219. }
  5220. return raw;
  5221. }
  5222. function mergeAsArray(to, from) {
  5223. return to ? [...new Set([].concat(to, from))] : from;
  5224. }
  5225. function mergeObjectOptions(to, from) {
  5226. return to ? extend(extend(Object.create(null), to), from) : from;
  5227. }
  5228. function mergeWatchOptions(to, from) {
  5229. if (!to)
  5230. return from;
  5231. if (!from)
  5232. return to;
  5233. const merged = extend(Object.create(null), to);
  5234. for (const key in from) {
  5235. merged[key] = mergeAsArray(to[key], from[key]);
  5236. }
  5237. return merged;
  5238. }
  5239. function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
  5240. isSSR = false) {
  5241. const props = {};
  5242. const attrs = {};
  5243. def(attrs, InternalObjectKey, 1);
  5244. instance.propsDefaults = Object.create(null);
  5245. setFullProps(instance, rawProps, props, attrs);
  5246. // ensure all declared prop keys are present
  5247. for (const key in instance.propsOptions[0]) {
  5248. if (!(key in props)) {
  5249. props[key] = undefined;
  5250. }
  5251. }
  5252. // validation
  5253. {
  5254. validateProps(rawProps || {}, props, instance);
  5255. }
  5256. if (isStateful) {
  5257. // stateful
  5258. instance.props = isSSR ? props : shallowReactive(props);
  5259. }
  5260. else {
  5261. if (!instance.type.props) {
  5262. // functional w/ optional props, props === attrs
  5263. instance.props = attrs;
  5264. }
  5265. else {
  5266. // functional w/ declared props
  5267. instance.props = props;
  5268. }
  5269. }
  5270. instance.attrs = attrs;
  5271. }
  5272. function isInHmrContext(instance) {
  5273. while (instance) {
  5274. if (instance.type.__hmrId)
  5275. return true;
  5276. instance = instance.parent;
  5277. }
  5278. }
  5279. function updateProps(instance, rawProps, rawPrevProps, optimized) {
  5280. const { props, attrs, vnode: { patchFlag } } = instance;
  5281. const rawCurrentProps = toRaw(props);
  5282. const [options] = instance.propsOptions;
  5283. let hasAttrsChanged = false;
  5284. if (
  5285. // always force full diff in dev
  5286. // - #1942 if hmr is enabled with sfc component
  5287. // - vite#872 non-sfc component used by sfc component
  5288. !(isInHmrContext(instance)) &&
  5289. (optimized || patchFlag > 0) &&
  5290. !(patchFlag & 16 /* PatchFlags.FULL_PROPS */)) {
  5291. if (patchFlag & 8 /* PatchFlags.PROPS */) {
  5292. // Compiler-generated props & no keys change, just set the updated
  5293. // the props.
  5294. const propsToUpdate = instance.vnode.dynamicProps;
  5295. for (let i = 0; i < propsToUpdate.length; i++) {
  5296. let key = propsToUpdate[i];
  5297. // skip if the prop key is a declared emit event listener
  5298. if (isEmitListener(instance.emitsOptions, key)) {
  5299. continue;
  5300. }
  5301. // PROPS flag guarantees rawProps to be non-null
  5302. const value = rawProps[key];
  5303. if (options) {
  5304. // attr / props separation was done on init and will be consistent
  5305. // in this code path, so just check if attrs have it.
  5306. if (hasOwn(attrs, key)) {
  5307. if (value !== attrs[key]) {
  5308. attrs[key] = value;
  5309. hasAttrsChanged = true;
  5310. }
  5311. }
  5312. else {
  5313. const camelizedKey = camelize(key);
  5314. props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false /* isAbsent */);
  5315. }
  5316. }
  5317. else {
  5318. if (value !== attrs[key]) {
  5319. attrs[key] = value;
  5320. hasAttrsChanged = true;
  5321. }
  5322. }
  5323. }
  5324. }
  5325. }
  5326. else {
  5327. // full props update.
  5328. if (setFullProps(instance, rawProps, props, attrs)) {
  5329. hasAttrsChanged = true;
  5330. }
  5331. // in case of dynamic props, check if we need to delete keys from
  5332. // the props object
  5333. let kebabKey;
  5334. for (const key in rawCurrentProps) {
  5335. if (!rawProps ||
  5336. // for camelCase
  5337. (!hasOwn(rawProps, key) &&
  5338. // it's possible the original props was passed in as kebab-case
  5339. // and converted to camelCase (#955)
  5340. ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
  5341. if (options) {
  5342. if (rawPrevProps &&
  5343. // for camelCase
  5344. (rawPrevProps[key] !== undefined ||
  5345. // for kebab-case
  5346. rawPrevProps[kebabKey] !== undefined)) {
  5347. props[key] = resolvePropValue(options, rawCurrentProps, key, undefined, instance, true /* isAbsent */);
  5348. }
  5349. }
  5350. else {
  5351. delete props[key];
  5352. }
  5353. }
  5354. }
  5355. // in the case of functional component w/o props declaration, props and
  5356. // attrs point to the same object so it should already have been updated.
  5357. if (attrs !== rawCurrentProps) {
  5358. for (const key in attrs) {
  5359. if (!rawProps ||
  5360. (!hasOwn(rawProps, key) &&
  5361. (!false ))) {
  5362. delete attrs[key];
  5363. hasAttrsChanged = true;
  5364. }
  5365. }
  5366. }
  5367. }
  5368. // trigger updates for $attrs in case it's used in component slots
  5369. if (hasAttrsChanged) {
  5370. trigger(instance, "set" /* TriggerOpTypes.SET */, '$attrs');
  5371. }
  5372. {
  5373. validateProps(rawProps || {}, props, instance);
  5374. }
  5375. }
  5376. function setFullProps(instance, rawProps, props, attrs) {
  5377. const [options, needCastKeys] = instance.propsOptions;
  5378. let hasAttrsChanged = false;
  5379. let rawCastValues;
  5380. if (rawProps) {
  5381. for (let key in rawProps) {
  5382. // key, ref are reserved and never passed down
  5383. if (isReservedProp(key)) {
  5384. continue;
  5385. }
  5386. const value = rawProps[key];
  5387. // prop option names are camelized during normalization, so to support
  5388. // kebab -> camel conversion here we need to camelize the key.
  5389. let camelKey;
  5390. if (options && hasOwn(options, (camelKey = camelize(key)))) {
  5391. if (!needCastKeys || !needCastKeys.includes(camelKey)) {
  5392. props[camelKey] = value;
  5393. }
  5394. else {
  5395. (rawCastValues || (rawCastValues = {}))[camelKey] = value;
  5396. }
  5397. }
  5398. else if (!isEmitListener(instance.emitsOptions, key)) {
  5399. if (!(key in attrs) || value !== attrs[key]) {
  5400. attrs[key] = value;
  5401. hasAttrsChanged = true;
  5402. }
  5403. }
  5404. }
  5405. }
  5406. if (needCastKeys) {
  5407. const rawCurrentProps = toRaw(props);
  5408. const castValues = rawCastValues || EMPTY_OBJ;
  5409. for (let i = 0; i < needCastKeys.length; i++) {
  5410. const key = needCastKeys[i];
  5411. props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key));
  5412. }
  5413. }
  5414. return hasAttrsChanged;
  5415. }
  5416. function resolvePropValue(options, props, key, value, instance, isAbsent) {
  5417. const opt = options[key];
  5418. if (opt != null) {
  5419. const hasDefault = hasOwn(opt, 'default');
  5420. // default values
  5421. if (hasDefault && value === undefined) {
  5422. const defaultValue = opt.default;
  5423. if (opt.type !== Function && isFunction(defaultValue)) {
  5424. const { propsDefaults } = instance;
  5425. if (key in propsDefaults) {
  5426. value = propsDefaults[key];
  5427. }
  5428. else {
  5429. setCurrentInstance(instance);
  5430. value = propsDefaults[key] = defaultValue.call(null, props);
  5431. unsetCurrentInstance();
  5432. }
  5433. }
  5434. else {
  5435. value = defaultValue;
  5436. }
  5437. }
  5438. // boolean casting
  5439. if (opt[0 /* BooleanFlags.shouldCast */]) {
  5440. if (isAbsent && !hasDefault) {
  5441. value = false;
  5442. }
  5443. else if (opt[1 /* BooleanFlags.shouldCastTrue */] &&
  5444. (value === '' || value === hyphenate(key))) {
  5445. value = true;
  5446. }
  5447. }
  5448. }
  5449. return value;
  5450. }
  5451. function normalizePropsOptions(comp, appContext, asMixin = false) {
  5452. const cache = appContext.propsCache;
  5453. const cached = cache.get(comp);
  5454. if (cached) {
  5455. return cached;
  5456. }
  5457. const raw = comp.props;
  5458. const normalized = {};
  5459. const needCastKeys = [];
  5460. // apply mixin/extends props
  5461. let hasExtends = false;
  5462. if (!isFunction(comp)) {
  5463. const extendProps = (raw) => {
  5464. hasExtends = true;
  5465. const [props, keys] = normalizePropsOptions(raw, appContext, true);
  5466. extend(normalized, props);
  5467. if (keys)
  5468. needCastKeys.push(...keys);
  5469. };
  5470. if (!asMixin && appContext.mixins.length) {
  5471. appContext.mixins.forEach(extendProps);
  5472. }
  5473. if (comp.extends) {
  5474. extendProps(comp.extends);
  5475. }
  5476. if (comp.mixins) {
  5477. comp.mixins.forEach(extendProps);
  5478. }
  5479. }
  5480. if (!raw && !hasExtends) {
  5481. if (isObject(comp)) {
  5482. cache.set(comp, EMPTY_ARR);
  5483. }
  5484. return EMPTY_ARR;
  5485. }
  5486. if (isArray(raw)) {
  5487. for (let i = 0; i < raw.length; i++) {
  5488. if (!isString(raw[i])) {
  5489. warn$1(`props must be strings when using array syntax.`, raw[i]);
  5490. }
  5491. const normalizedKey = camelize(raw[i]);
  5492. if (validatePropName(normalizedKey)) {
  5493. normalized[normalizedKey] = EMPTY_OBJ;
  5494. }
  5495. }
  5496. }
  5497. else if (raw) {
  5498. if (!isObject(raw)) {
  5499. warn$1(`invalid props options`, raw);
  5500. }
  5501. for (const key in raw) {
  5502. const normalizedKey = camelize(key);
  5503. if (validatePropName(normalizedKey)) {
  5504. const opt = raw[key];
  5505. const prop = (normalized[normalizedKey] =
  5506. isArray(opt) || isFunction(opt) ? { type: opt } : Object.assign({}, opt));
  5507. if (prop) {
  5508. const booleanIndex = getTypeIndex(Boolean, prop.type);
  5509. const stringIndex = getTypeIndex(String, prop.type);
  5510. prop[0 /* BooleanFlags.shouldCast */] = booleanIndex > -1;
  5511. prop[1 /* BooleanFlags.shouldCastTrue */] =
  5512. stringIndex < 0 || booleanIndex < stringIndex;
  5513. // if the prop needs boolean casting or default value
  5514. if (booleanIndex > -1 || hasOwn(prop, 'default')) {
  5515. needCastKeys.push(normalizedKey);
  5516. }
  5517. }
  5518. }
  5519. }
  5520. }
  5521. const res = [normalized, needCastKeys];
  5522. if (isObject(comp)) {
  5523. cache.set(comp, res);
  5524. }
  5525. return res;
  5526. }
  5527. function validatePropName(key) {
  5528. if (key[0] !== '$') {
  5529. return true;
  5530. }
  5531. else {
  5532. warn$1(`Invalid prop name: "${key}" is a reserved property.`);
  5533. }
  5534. return false;
  5535. }
  5536. // use function string name to check type constructors
  5537. // so that it works across vms / iframes.
  5538. function getType(ctor) {
  5539. const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
  5540. return match ? match[1] : ctor === null ? 'null' : '';
  5541. }
  5542. function isSameType(a, b) {
  5543. return getType(a) === getType(b);
  5544. }
  5545. function getTypeIndex(type, expectedTypes) {
  5546. if (isArray(expectedTypes)) {
  5547. return expectedTypes.findIndex(t => isSameType(t, type));
  5548. }
  5549. else if (isFunction(expectedTypes)) {
  5550. return isSameType(expectedTypes, type) ? 0 : -1;
  5551. }
  5552. return -1;
  5553. }
  5554. /**
  5555. * dev only
  5556. */
  5557. function validateProps(rawProps, props, instance) {
  5558. const resolvedValues = toRaw(props);
  5559. const options = instance.propsOptions[0];
  5560. for (const key in options) {
  5561. let opt = options[key];
  5562. if (opt == null)
  5563. continue;
  5564. validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key)));
  5565. }
  5566. }
  5567. /**
  5568. * dev only
  5569. */
  5570. function validateProp(name, value, prop, isAbsent) {
  5571. const { type, required, validator } = prop;
  5572. // required!
  5573. if (required && isAbsent) {
  5574. warn$1('Missing required prop: "' + name + '"');
  5575. return;
  5576. }
  5577. // missing but optional
  5578. if (value == null && !prop.required) {
  5579. return;
  5580. }
  5581. // type check
  5582. if (type != null && type !== true) {
  5583. let isValid = false;
  5584. const types = isArray(type) ? type : [type];
  5585. const expectedTypes = [];
  5586. // value is valid as long as one of the specified types match
  5587. for (let i = 0; i < types.length && !isValid; i++) {
  5588. const { valid, expectedType } = assertType(value, types[i]);
  5589. expectedTypes.push(expectedType || '');
  5590. isValid = valid;
  5591. }
  5592. if (!isValid) {
  5593. warn$1(getInvalidTypeMessage(name, value, expectedTypes));
  5594. return;
  5595. }
  5596. }
  5597. // custom validator
  5598. if (validator && !validator(value)) {
  5599. warn$1('Invalid prop: custom validator check failed for prop "' + name + '".');
  5600. }
  5601. }
  5602. const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
  5603. /**
  5604. * dev only
  5605. */
  5606. function assertType(value, type) {
  5607. let valid;
  5608. const expectedType = getType(type);
  5609. if (isSimpleType(expectedType)) {
  5610. const t = typeof value;
  5611. valid = t === expectedType.toLowerCase();
  5612. // for primitive wrapper objects
  5613. if (!valid && t === 'object') {
  5614. valid = value instanceof type;
  5615. }
  5616. }
  5617. else if (expectedType === 'Object') {
  5618. valid = isObject(value);
  5619. }
  5620. else if (expectedType === 'Array') {
  5621. valid = isArray(value);
  5622. }
  5623. else if (expectedType === 'null') {
  5624. valid = value === null;
  5625. }
  5626. else {
  5627. valid = value instanceof type;
  5628. }
  5629. return {
  5630. valid,
  5631. expectedType
  5632. };
  5633. }
  5634. /**
  5635. * dev only
  5636. */
  5637. function getInvalidTypeMessage(name, value, expectedTypes) {
  5638. let message = `Invalid prop: type check failed for prop "${name}".` +
  5639. ` Expected ${expectedTypes.map(capitalize).join(' | ')}`;
  5640. const expectedType = expectedTypes[0];
  5641. const receivedType = toRawType(value);
  5642. const expectedValue = styleValue(value, expectedType);
  5643. const receivedValue = styleValue(value, receivedType);
  5644. // check if we need to specify expected value
  5645. if (expectedTypes.length === 1 &&
  5646. isExplicable(expectedType) &&
  5647. !isBoolean(expectedType, receivedType)) {
  5648. message += ` with value ${expectedValue}`;
  5649. }
  5650. message += `, got ${receivedType} `;
  5651. // check if we need to specify received value
  5652. if (isExplicable(receivedType)) {
  5653. message += `with value ${receivedValue}.`;
  5654. }
  5655. return message;
  5656. }
  5657. /**
  5658. * dev only
  5659. */
  5660. function styleValue(value, type) {
  5661. if (type === 'String') {
  5662. return `"${value}"`;
  5663. }
  5664. else if (type === 'Number') {
  5665. return `${Number(value)}`;
  5666. }
  5667. else {
  5668. return `${value}`;
  5669. }
  5670. }
  5671. /**
  5672. * dev only
  5673. */
  5674. function isExplicable(type) {
  5675. const explicitTypes = ['string', 'number', 'boolean'];
  5676. return explicitTypes.some(elem => type.toLowerCase() === elem);
  5677. }
  5678. /**
  5679. * dev only
  5680. */
  5681. function isBoolean(...args) {
  5682. return args.some(elem => elem.toLowerCase() === 'boolean');
  5683. }
  5684. const isInternalKey = (key) => key[0] === '_' || key === '$stable';
  5685. const normalizeSlotValue = (value) => isArray(value)
  5686. ? value.map(normalizeVNode)
  5687. : [normalizeVNode(value)];
  5688. const normalizeSlot = (key, rawSlot, ctx) => {
  5689. if (rawSlot._n) {
  5690. // already normalized - #5353
  5691. return rawSlot;
  5692. }
  5693. const normalized = withCtx((...args) => {
  5694. if (true && currentInstance) {
  5695. warn$1(`Slot "${key}" invoked outside of the render function: ` +
  5696. `this will not track dependencies used in the slot. ` +
  5697. `Invoke the slot function inside the render function instead.`);
  5698. }
  5699. return normalizeSlotValue(rawSlot(...args));
  5700. }, ctx);
  5701. normalized._c = false;
  5702. return normalized;
  5703. };
  5704. const normalizeObjectSlots = (rawSlots, slots, instance) => {
  5705. const ctx = rawSlots._ctx;
  5706. for (const key in rawSlots) {
  5707. if (isInternalKey(key))
  5708. continue;
  5709. const value = rawSlots[key];
  5710. if (isFunction(value)) {
  5711. slots[key] = normalizeSlot(key, value, ctx);
  5712. }
  5713. else if (value != null) {
  5714. {
  5715. warn$1(`Non-function value encountered for slot "${key}". ` +
  5716. `Prefer function slots for better performance.`);
  5717. }
  5718. const normalized = normalizeSlotValue(value);
  5719. slots[key] = () => normalized;
  5720. }
  5721. }
  5722. };
  5723. const normalizeVNodeSlots = (instance, children) => {
  5724. if (!isKeepAlive(instance.vnode) &&
  5725. !(false )) {
  5726. warn$1(`Non-function value encountered for default slot. ` +
  5727. `Prefer function slots for better performance.`);
  5728. }
  5729. const normalized = normalizeSlotValue(children);
  5730. instance.slots.default = () => normalized;
  5731. };
  5732. const initSlots = (instance, children) => {
  5733. if (instance.vnode.shapeFlag & 32 /* ShapeFlags.SLOTS_CHILDREN */) {
  5734. const type = children._;
  5735. if (type) {
  5736. // users can get the shallow readonly version of the slots object through `this.$slots`,
  5737. // we should avoid the proxy object polluting the slots of the internal instance
  5738. instance.slots = toRaw(children);
  5739. // make compiler marker non-enumerable
  5740. def(children, '_', type);
  5741. }
  5742. else {
  5743. normalizeObjectSlots(children, (instance.slots = {}));
  5744. }
  5745. }
  5746. else {
  5747. instance.slots = {};
  5748. if (children) {
  5749. normalizeVNodeSlots(instance, children);
  5750. }
  5751. }
  5752. def(instance.slots, InternalObjectKey, 1);
  5753. };
  5754. const updateSlots = (instance, children, optimized) => {
  5755. const { vnode, slots } = instance;
  5756. let needDeletionCheck = true;
  5757. let deletionComparisonTarget = EMPTY_OBJ;
  5758. if (vnode.shapeFlag & 32 /* ShapeFlags.SLOTS_CHILDREN */) {
  5759. const type = children._;
  5760. if (type) {
  5761. // compiled slots.
  5762. if (isHmrUpdating) {
  5763. // Parent was HMR updated so slot content may have changed.
  5764. // force update slots and mark instance for hmr as well
  5765. extend(slots, children);
  5766. }
  5767. else if (optimized && type === 1 /* SlotFlags.STABLE */) {
  5768. // compiled AND stable.
  5769. // no need to update, and skip stale slots removal.
  5770. needDeletionCheck = false;
  5771. }
  5772. else {
  5773. // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
  5774. // normalization.
  5775. extend(slots, children);
  5776. // #2893
  5777. // when rendering the optimized slots by manually written render function,
  5778. // we need to delete the `slots._` flag if necessary to make subsequent updates reliable,
  5779. // i.e. let the `renderSlot` create the bailed Fragment
  5780. if (!optimized && type === 1 /* SlotFlags.STABLE */) {
  5781. delete slots._;
  5782. }
  5783. }
  5784. }
  5785. else {
  5786. needDeletionCheck = !children.$stable;
  5787. normalizeObjectSlots(children, slots);
  5788. }
  5789. deletionComparisonTarget = children;
  5790. }
  5791. else if (children) {
  5792. // non slot object children (direct value) passed to a component
  5793. normalizeVNodeSlots(instance, children);
  5794. deletionComparisonTarget = { default: 1 };
  5795. }
  5796. // delete stale slots
  5797. if (needDeletionCheck) {
  5798. for (const key in slots) {
  5799. if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
  5800. delete slots[key];
  5801. }
  5802. }
  5803. }
  5804. };
  5805. function createAppContext() {
  5806. return {
  5807. app: null,
  5808. config: {
  5809. isNativeTag: NO,
  5810. performance: false,
  5811. globalProperties: {},
  5812. optionMergeStrategies: {},
  5813. errorHandler: undefined,
  5814. warnHandler: undefined,
  5815. compilerOptions: {}
  5816. },
  5817. mixins: [],
  5818. components: {},
  5819. directives: {},
  5820. provides: Object.create(null),
  5821. optionsCache: new WeakMap(),
  5822. propsCache: new WeakMap(),
  5823. emitsCache: new WeakMap()
  5824. };
  5825. }
  5826. let uid = 0;
  5827. function createAppAPI(render, hydrate) {
  5828. return function createApp(rootComponent, rootProps = null) {
  5829. if (!isFunction(rootComponent)) {
  5830. rootComponent = Object.assign({}, rootComponent);
  5831. }
  5832. if (rootProps != null && !isObject(rootProps)) {
  5833. warn$1(`root props passed to app.mount() must be an object.`);
  5834. rootProps = null;
  5835. }
  5836. const context = createAppContext();
  5837. const installedPlugins = new Set();
  5838. let isMounted = false;
  5839. const app = (context.app = {
  5840. _uid: uid++,
  5841. _component: rootComponent,
  5842. _props: rootProps,
  5843. _container: null,
  5844. _context: context,
  5845. _instance: null,
  5846. version,
  5847. get config() {
  5848. return context.config;
  5849. },
  5850. set config(v) {
  5851. {
  5852. warn$1(`app.config cannot be replaced. Modify individual options instead.`);
  5853. }
  5854. },
  5855. use(plugin, ...options) {
  5856. if (installedPlugins.has(plugin)) {
  5857. warn$1(`Plugin has already been applied to target app.`);
  5858. }
  5859. else if (plugin && isFunction(plugin.install)) {
  5860. installedPlugins.add(plugin);
  5861. plugin.install(app, ...options);
  5862. }
  5863. else if (isFunction(plugin)) {
  5864. installedPlugins.add(plugin);
  5865. plugin(app, ...options);
  5866. }
  5867. else {
  5868. warn$1(`A plugin must either be a function or an object with an "install" ` +
  5869. `function.`);
  5870. }
  5871. return app;
  5872. },
  5873. mixin(mixin) {
  5874. {
  5875. if (!context.mixins.includes(mixin)) {
  5876. context.mixins.push(mixin);
  5877. }
  5878. else {
  5879. warn$1('Mixin has already been applied to target app' +
  5880. (mixin.name ? `: ${mixin.name}` : ''));
  5881. }
  5882. }
  5883. return app;
  5884. },
  5885. component(name, component) {
  5886. {
  5887. validateComponentName(name, context.config);
  5888. }
  5889. if (!component) {
  5890. return context.components[name];
  5891. }
  5892. if (context.components[name]) {
  5893. warn$1(`Component "${name}" has already been registered in target app.`);
  5894. }
  5895. context.components[name] = component;
  5896. return app;
  5897. },
  5898. directive(name, directive) {
  5899. {
  5900. validateDirectiveName(name);
  5901. }
  5902. if (!directive) {
  5903. return context.directives[name];
  5904. }
  5905. if (context.directives[name]) {
  5906. warn$1(`Directive "${name}" has already been registered in target app.`);
  5907. }
  5908. context.directives[name] = directive;
  5909. return app;
  5910. },
  5911. mount(rootContainer, isHydrate, isSVG) {
  5912. if (!isMounted) {
  5913. // #5571
  5914. if (rootContainer.__vue_app__) {
  5915. warn$1(`There is already an app instance mounted on the host container.\n` +
  5916. ` If you want to mount another app on the same host container,` +
  5917. ` you need to unmount the previous app by calling \`app.unmount()\` first.`);
  5918. }
  5919. const vnode = createVNode(rootComponent, rootProps);
  5920. // store app context on the root VNode.
  5921. // this will be set on the root instance on initial mount.
  5922. vnode.appContext = context;
  5923. // HMR root reload
  5924. {
  5925. context.reload = () => {
  5926. render(cloneVNode(vnode), rootContainer, isSVG);
  5927. };
  5928. }
  5929. if (isHydrate && hydrate) {
  5930. hydrate(vnode, rootContainer);
  5931. }
  5932. else {
  5933. render(vnode, rootContainer, isSVG);
  5934. }
  5935. isMounted = true;
  5936. app._container = rootContainer;
  5937. rootContainer.__vue_app__ = app;
  5938. {
  5939. app._instance = vnode.component;
  5940. devtoolsInitApp(app, version);
  5941. }
  5942. return getExposeProxy(vnode.component) || vnode.component.proxy;
  5943. }
  5944. else {
  5945. warn$1(`App has already been mounted.\n` +
  5946. `If you want to remount the same app, move your app creation logic ` +
  5947. `into a factory function and create fresh app instances for each ` +
  5948. `mount - e.g. \`const createMyApp = () => createApp(App)\``);
  5949. }
  5950. },
  5951. unmount() {
  5952. if (isMounted) {
  5953. render(null, app._container);
  5954. {
  5955. app._instance = null;
  5956. devtoolsUnmountApp(app);
  5957. }
  5958. delete app._container.__vue_app__;
  5959. }
  5960. else {
  5961. warn$1(`Cannot unmount an app that is not mounted.`);
  5962. }
  5963. },
  5964. provide(key, value) {
  5965. if (key in context.provides) {
  5966. warn$1(`App already provides property with key "${String(key)}". ` +
  5967. `It will be overwritten with the new value.`);
  5968. }
  5969. context.provides[key] = value;
  5970. return app;
  5971. }
  5972. });
  5973. return app;
  5974. };
  5975. }
  5976. /**
  5977. * Function for handling a template ref
  5978. */
  5979. function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
  5980. if (isArray(rawRef)) {
  5981. rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount));
  5982. return;
  5983. }
  5984. if (isAsyncWrapper(vnode) && !isUnmount) {
  5985. // when mounting async components, nothing needs to be done,
  5986. // because the template ref is forwarded to inner component
  5987. return;
  5988. }
  5989. const refValue = vnode.shapeFlag & 4 /* ShapeFlags.STATEFUL_COMPONENT */
  5990. ? getExposeProxy(vnode.component) || vnode.component.proxy
  5991. : vnode.el;
  5992. const value = isUnmount ? null : refValue;
  5993. const { i: owner, r: ref } = rawRef;
  5994. if (!owner) {
  5995. warn$1(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
  5996. `A vnode with ref must be created inside the render function.`);
  5997. return;
  5998. }
  5999. const oldRef = oldRawRef && oldRawRef.r;
  6000. const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
  6001. const setupState = owner.setupState;
  6002. // dynamic ref changed. unset old ref
  6003. if (oldRef != null && oldRef !== ref) {
  6004. if (isString(oldRef)) {
  6005. refs[oldRef] = null;
  6006. if (hasOwn(setupState, oldRef)) {
  6007. setupState[oldRef] = null;
  6008. }
  6009. }
  6010. else if (isRef(oldRef)) {
  6011. oldRef.value = null;
  6012. }
  6013. }
  6014. if (isFunction(ref)) {
  6015. callWithErrorHandling(ref, owner, 12 /* ErrorCodes.FUNCTION_REF */, [value, refs]);
  6016. }
  6017. else {
  6018. const _isString = isString(ref);
  6019. const _isRef = isRef(ref);
  6020. if (_isString || _isRef) {
  6021. const doSet = () => {
  6022. if (rawRef.f) {
  6023. const existing = _isString
  6024. ? hasOwn(setupState, ref)
  6025. ? setupState[ref]
  6026. : refs[ref]
  6027. : ref.value;
  6028. if (isUnmount) {
  6029. isArray(existing) && remove(existing, refValue);
  6030. }
  6031. else {
  6032. if (!isArray(existing)) {
  6033. if (_isString) {
  6034. refs[ref] = [refValue];
  6035. if (hasOwn(setupState, ref)) {
  6036. setupState[ref] = refs[ref];
  6037. }
  6038. }
  6039. else {
  6040. ref.value = [refValue];
  6041. if (rawRef.k)
  6042. refs[rawRef.k] = ref.value;
  6043. }
  6044. }
  6045. else if (!existing.includes(refValue)) {
  6046. existing.push(refValue);
  6047. }
  6048. }
  6049. }
  6050. else if (_isString) {
  6051. refs[ref] = value;
  6052. if (hasOwn(setupState, ref)) {
  6053. setupState[ref] = value;
  6054. }
  6055. }
  6056. else if (_isRef) {
  6057. ref.value = value;
  6058. if (rawRef.k)
  6059. refs[rawRef.k] = value;
  6060. }
  6061. else {
  6062. warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
  6063. }
  6064. };
  6065. if (value) {
  6066. doSet.id = -1;
  6067. queuePostRenderEffect(doSet, parentSuspense);
  6068. }
  6069. else {
  6070. doSet();
  6071. }
  6072. }
  6073. else {
  6074. warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
  6075. }
  6076. }
  6077. }
  6078. let hasMismatch = false;
  6079. const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
  6080. const isComment = (node) => node.nodeType === 8 /* DOMNodeTypes.COMMENT */;
  6081. // Note: hydration is DOM-specific
  6082. // But we have to place it in core due to tight coupling with core - splitting
  6083. // it out creates a ton of unnecessary complexity.
  6084. // Hydration also depends on some renderer internal logic which needs to be
  6085. // passed in via arguments.
  6086. function createHydrationFunctions(rendererInternals) {
  6087. const { mt: mountComponent, p: patch, o: { patchProp, createText, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
  6088. const hydrate = (vnode, container) => {
  6089. if (!container.hasChildNodes()) {
  6090. warn$1(`Attempting to hydrate existing markup but container is empty. ` +
  6091. `Performing full mount instead.`);
  6092. patch(null, vnode, container);
  6093. flushPostFlushCbs();
  6094. container._vnode = vnode;
  6095. return;
  6096. }
  6097. hasMismatch = false;
  6098. hydrateNode(container.firstChild, vnode, null, null, null);
  6099. flushPostFlushCbs();
  6100. container._vnode = vnode;
  6101. if (hasMismatch && !false) {
  6102. // this error should show up in production
  6103. console.error(`Hydration completed but contains mismatches.`);
  6104. }
  6105. };
  6106. const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {
  6107. const isFragmentStart = isComment(node) && node.data === '[';
  6108. const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart);
  6109. const { type, ref, shapeFlag, patchFlag } = vnode;
  6110. let domType = node.nodeType;
  6111. vnode.el = node;
  6112. if (patchFlag === -2 /* PatchFlags.BAIL */) {
  6113. optimized = false;
  6114. vnode.dynamicChildren = null;
  6115. }
  6116. let nextNode = null;
  6117. switch (type) {
  6118. case Text:
  6119. if (domType !== 3 /* DOMNodeTypes.TEXT */) {
  6120. // #5728 empty text node inside a slot can cause hydration failure
  6121. // because the server rendered HTML won't contain a text node
  6122. if (vnode.children === '') {
  6123. insert((vnode.el = createText('')), parentNode(node), node);
  6124. nextNode = node;
  6125. }
  6126. else {
  6127. nextNode = onMismatch();
  6128. }
  6129. }
  6130. else {
  6131. if (node.data !== vnode.children) {
  6132. hasMismatch = true;
  6133. warn$1(`Hydration text mismatch:` +
  6134. `\n- Client: ${JSON.stringify(node.data)}` +
  6135. `\n- Server: ${JSON.stringify(vnode.children)}`);
  6136. node.data = vnode.children;
  6137. }
  6138. nextNode = nextSibling(node);
  6139. }
  6140. break;
  6141. case Comment:
  6142. if (domType !== 8 /* DOMNodeTypes.COMMENT */ || isFragmentStart) {
  6143. nextNode = onMismatch();
  6144. }
  6145. else {
  6146. nextNode = nextSibling(node);
  6147. }
  6148. break;
  6149. case Static:
  6150. if (isFragmentStart) {
  6151. // entire template is static but SSRed as a fragment
  6152. node = nextSibling(node);
  6153. domType = node.nodeType;
  6154. }
  6155. if (domType === 1 /* DOMNodeTypes.ELEMENT */ || domType === 3 /* DOMNodeTypes.TEXT */) {
  6156. // determine anchor, adopt content
  6157. nextNode = node;
  6158. // if the static vnode has its content stripped during build,
  6159. // adopt it from the server-rendered HTML.
  6160. const needToAdoptContent = !vnode.children.length;
  6161. for (let i = 0; i < vnode.staticCount; i++) {
  6162. if (needToAdoptContent)
  6163. vnode.children +=
  6164. nextNode.nodeType === 1 /* DOMNodeTypes.ELEMENT */
  6165. ? nextNode.outerHTML
  6166. : nextNode.data;
  6167. if (i === vnode.staticCount - 1) {
  6168. vnode.anchor = nextNode;
  6169. }
  6170. nextNode = nextSibling(nextNode);
  6171. }
  6172. return isFragmentStart ? nextSibling(nextNode) : nextNode;
  6173. }
  6174. else {
  6175. onMismatch();
  6176. }
  6177. break;
  6178. case Fragment:
  6179. if (!isFragmentStart) {
  6180. nextNode = onMismatch();
  6181. }
  6182. else {
  6183. nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
  6184. }
  6185. break;
  6186. default:
  6187. if (shapeFlag & 1 /* ShapeFlags.ELEMENT */) {
  6188. if (domType !== 1 /* DOMNodeTypes.ELEMENT */ ||
  6189. vnode.type.toLowerCase() !==
  6190. node.tagName.toLowerCase()) {
  6191. nextNode = onMismatch();
  6192. }
  6193. else {
  6194. nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
  6195. }
  6196. }
  6197. else if (shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
  6198. // when setting up the render effect, if the initial vnode already
  6199. // has .el set, the component will perform hydration instead of mount
  6200. // on its sub-tree.
  6201. vnode.slotScopeIds = slotScopeIds;
  6202. const container = parentNode(node);
  6203. mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
  6204. // component may be async, so in the case of fragments we cannot rely
  6205. // on component's rendered output to determine the end of the fragment
  6206. // instead, we do a lookahead to find the end anchor node.
  6207. nextNode = isFragmentStart
  6208. ? locateClosingAsyncAnchor(node)
  6209. : nextSibling(node);
  6210. // #4293 teleport as component root
  6211. if (nextNode &&
  6212. isComment(nextNode) &&
  6213. nextNode.data === 'teleport end') {
  6214. nextNode = nextSibling(nextNode);
  6215. }
  6216. // #3787
  6217. // if component is async, it may get moved / unmounted before its
  6218. // inner component is loaded, so we need to give it a placeholder
  6219. // vnode that matches its adopted DOM.
  6220. if (isAsyncWrapper(vnode)) {
  6221. let subTree;
  6222. if (isFragmentStart) {
  6223. subTree = createVNode(Fragment);
  6224. subTree.anchor = nextNode
  6225. ? nextNode.previousSibling
  6226. : container.lastChild;
  6227. }
  6228. else {
  6229. subTree =
  6230. node.nodeType === 3 ? createTextVNode('') : createVNode('div');
  6231. }
  6232. subTree.el = node;
  6233. vnode.component.subTree = subTree;
  6234. }
  6235. }
  6236. else if (shapeFlag & 64 /* ShapeFlags.TELEPORT */) {
  6237. if (domType !== 8 /* DOMNodeTypes.COMMENT */) {
  6238. nextNode = onMismatch();
  6239. }
  6240. else {
  6241. nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, rendererInternals, hydrateChildren);
  6242. }
  6243. }
  6244. else if (shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  6245. nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode);
  6246. }
  6247. else {
  6248. warn$1('Invalid HostVNode type:', type, `(${typeof type})`);
  6249. }
  6250. }
  6251. if (ref != null) {
  6252. setRef(ref, null, parentSuspense, vnode);
  6253. }
  6254. return nextNode;
  6255. };
  6256. const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
  6257. optimized = optimized || !!vnode.dynamicChildren;
  6258. const { type, props, patchFlag, shapeFlag, dirs } = vnode;
  6259. // #4006 for form elements with non-string v-model value bindings
  6260. // e.g. <option :value="obj">, <input type="checkbox" :true-value="1">
  6261. const forcePatchValue = (type === 'input' && dirs) || type === 'option';
  6262. // skip props & children if this is hoisted static nodes
  6263. // #5405 in dev, always hydrate children for HMR
  6264. {
  6265. if (dirs) {
  6266. invokeDirectiveHook(vnode, null, parentComponent, 'created');
  6267. }
  6268. // props
  6269. if (props) {
  6270. if (forcePatchValue ||
  6271. !optimized ||
  6272. patchFlag & (16 /* PatchFlags.FULL_PROPS */ | 32 /* PatchFlags.HYDRATE_EVENTS */)) {
  6273. for (const key in props) {
  6274. if ((forcePatchValue && key.endsWith('value')) ||
  6275. (isOn(key) && !isReservedProp(key))) {
  6276. patchProp(el, key, null, props[key], false, undefined, parentComponent);
  6277. }
  6278. }
  6279. }
  6280. else if (props.onClick) {
  6281. // Fast path for click listeners (which is most often) to avoid
  6282. // iterating through props.
  6283. patchProp(el, 'onClick', null, props.onClick, false, undefined, parentComponent);
  6284. }
  6285. }
  6286. // vnode / directive hooks
  6287. let vnodeHooks;
  6288. if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
  6289. invokeVNodeHook(vnodeHooks, parentComponent, vnode);
  6290. }
  6291. if (dirs) {
  6292. invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
  6293. }
  6294. if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
  6295. queueEffectWithSuspense(() => {
  6296. vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
  6297. dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
  6298. }, parentSuspense);
  6299. }
  6300. // children
  6301. if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */ &&
  6302. // skip if element has innerHTML / textContent
  6303. !(props && (props.innerHTML || props.textContent))) {
  6304. let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, slotScopeIds, optimized);
  6305. let hasWarned = false;
  6306. while (next) {
  6307. hasMismatch = true;
  6308. if (!hasWarned) {
  6309. warn$1(`Hydration children mismatch in <${vnode.type}>: ` +
  6310. `server rendered element contains more child nodes than client vdom.`);
  6311. hasWarned = true;
  6312. }
  6313. // The SSRed DOM contains more nodes than it should. Remove them.
  6314. const cur = next;
  6315. next = next.nextSibling;
  6316. remove(cur);
  6317. }
  6318. }
  6319. else if (shapeFlag & 8 /* ShapeFlags.TEXT_CHILDREN */) {
  6320. if (el.textContent !== vnode.children) {
  6321. hasMismatch = true;
  6322. warn$1(`Hydration text content mismatch in <${vnode.type}>:\n` +
  6323. `- Client: ${el.textContent}\n` +
  6324. `- Server: ${vnode.children}`);
  6325. el.textContent = vnode.children;
  6326. }
  6327. }
  6328. }
  6329. return el.nextSibling;
  6330. };
  6331. const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {
  6332. optimized = optimized || !!parentVNode.dynamicChildren;
  6333. const children = parentVNode.children;
  6334. const l = children.length;
  6335. let hasWarned = false;
  6336. for (let i = 0; i < l; i++) {
  6337. const vnode = optimized
  6338. ? children[i]
  6339. : (children[i] = normalizeVNode(children[i]));
  6340. if (node) {
  6341. node = hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
  6342. }
  6343. else if (vnode.type === Text && !vnode.children) {
  6344. continue;
  6345. }
  6346. else {
  6347. hasMismatch = true;
  6348. if (!hasWarned) {
  6349. warn$1(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
  6350. `server rendered element contains fewer child nodes than client vdom.`);
  6351. hasWarned = true;
  6352. }
  6353. // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
  6354. patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
  6355. }
  6356. }
  6357. return node;
  6358. };
  6359. const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
  6360. const { slotScopeIds: fragmentSlotScopeIds } = vnode;
  6361. if (fragmentSlotScopeIds) {
  6362. slotScopeIds = slotScopeIds
  6363. ? slotScopeIds.concat(fragmentSlotScopeIds)
  6364. : fragmentSlotScopeIds;
  6365. }
  6366. const container = parentNode(node);
  6367. const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, slotScopeIds, optimized);
  6368. if (next && isComment(next) && next.data === ']') {
  6369. return nextSibling((vnode.anchor = next));
  6370. }
  6371. else {
  6372. // fragment didn't hydrate successfully, since we didn't get a end anchor
  6373. // back. This should have led to node/children mismatch warnings.
  6374. hasMismatch = true;
  6375. // since the anchor is missing, we need to create one and insert it
  6376. insert((vnode.anchor = createComment(`]`)), container, next);
  6377. return next;
  6378. }
  6379. };
  6380. const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {
  6381. hasMismatch = true;
  6382. warn$1(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* DOMNodeTypes.TEXT */
  6383. ? `(text)`
  6384. : isComment(node) && node.data === '['
  6385. ? `(start of fragment)`
  6386. : ``);
  6387. vnode.el = null;
  6388. if (isFragment) {
  6389. // remove excessive fragment nodes
  6390. const end = locateClosingAsyncAnchor(node);
  6391. while (true) {
  6392. const next = nextSibling(node);
  6393. if (next && next !== end) {
  6394. remove(next);
  6395. }
  6396. else {
  6397. break;
  6398. }
  6399. }
  6400. }
  6401. const next = nextSibling(node);
  6402. const container = parentNode(node);
  6403. remove(node);
  6404. patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
  6405. return next;
  6406. };
  6407. const locateClosingAsyncAnchor = (node) => {
  6408. let match = 0;
  6409. while (node) {
  6410. node = nextSibling(node);
  6411. if (node && isComment(node)) {
  6412. if (node.data === '[')
  6413. match++;
  6414. if (node.data === ']') {
  6415. if (match === 0) {
  6416. return nextSibling(node);
  6417. }
  6418. else {
  6419. match--;
  6420. }
  6421. }
  6422. }
  6423. }
  6424. return node;
  6425. };
  6426. return [hydrate, hydrateNode];
  6427. }
  6428. /* eslint-disable no-restricted-globals */
  6429. let supported;
  6430. let perf;
  6431. function startMeasure(instance, type) {
  6432. if (instance.appContext.config.performance && isSupported()) {
  6433. perf.mark(`vue-${type}-${instance.uid}`);
  6434. }
  6435. {
  6436. devtoolsPerfStart(instance, type, isSupported() ? perf.now() : Date.now());
  6437. }
  6438. }
  6439. function endMeasure(instance, type) {
  6440. if (instance.appContext.config.performance && isSupported()) {
  6441. const startTag = `vue-${type}-${instance.uid}`;
  6442. const endTag = startTag + `:end`;
  6443. perf.mark(endTag);
  6444. perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
  6445. perf.clearMarks(startTag);
  6446. perf.clearMarks(endTag);
  6447. }
  6448. {
  6449. devtoolsPerfEnd(instance, type, isSupported() ? perf.now() : Date.now());
  6450. }
  6451. }
  6452. function isSupported() {
  6453. if (supported !== undefined) {
  6454. return supported;
  6455. }
  6456. if (typeof window !== 'undefined' && window.performance) {
  6457. supported = true;
  6458. perf = window.performance;
  6459. }
  6460. else {
  6461. supported = false;
  6462. }
  6463. return supported;
  6464. }
  6465. const queuePostRenderEffect = queueEffectWithSuspense
  6466. ;
  6467. /**
  6468. * The createRenderer function accepts two generic arguments:
  6469. * HostNode and HostElement, corresponding to Node and Element types in the
  6470. * host environment. For example, for runtime-dom, HostNode would be the DOM
  6471. * `Node` interface and HostElement would be the DOM `Element` interface.
  6472. *
  6473. * Custom renderers can pass in the platform specific types like this:
  6474. *
  6475. * ``` js
  6476. * const { render, createApp } = createRenderer<Node, Element>({
  6477. * patchProp,
  6478. * ...nodeOps
  6479. * })
  6480. * ```
  6481. */
  6482. function createRenderer(options) {
  6483. return baseCreateRenderer(options);
  6484. }
  6485. // Separate API for creating hydration-enabled renderer.
  6486. // Hydration logic is only used when calling this function, making it
  6487. // tree-shakable.
  6488. function createHydrationRenderer(options) {
  6489. return baseCreateRenderer(options, createHydrationFunctions);
  6490. }
  6491. // implementation
  6492. function baseCreateRenderer(options, createHydrationFns) {
  6493. const target = getGlobalThis();
  6494. target.__VUE__ = true;
  6495. {
  6496. setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__, target);
  6497. }
  6498. const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, insertStaticContent: hostInsertStaticContent } = options;
  6499. // Note: functions inside this closure should use `const xxx = () => {}`
  6500. // style in order to prevent being inlined by minifiers.
  6501. const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = isHmrUpdating ? false : !!n2.dynamicChildren) => {
  6502. if (n1 === n2) {
  6503. return;
  6504. }
  6505. // patching & not same type, unmount old tree
  6506. if (n1 && !isSameVNodeType(n1, n2)) {
  6507. anchor = getNextHostNode(n1);
  6508. unmount(n1, parentComponent, parentSuspense, true);
  6509. n1 = null;
  6510. }
  6511. if (n2.patchFlag === -2 /* PatchFlags.BAIL */) {
  6512. optimized = false;
  6513. n2.dynamicChildren = null;
  6514. }
  6515. const { type, ref, shapeFlag } = n2;
  6516. switch (type) {
  6517. case Text:
  6518. processText(n1, n2, container, anchor);
  6519. break;
  6520. case Comment:
  6521. processCommentNode(n1, n2, container, anchor);
  6522. break;
  6523. case Static:
  6524. if (n1 == null) {
  6525. mountStaticNode(n2, container, anchor, isSVG);
  6526. }
  6527. else {
  6528. patchStaticNode(n1, n2, container, isSVG);
  6529. }
  6530. break;
  6531. case Fragment:
  6532. processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6533. break;
  6534. default:
  6535. if (shapeFlag & 1 /* ShapeFlags.ELEMENT */) {
  6536. processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6537. }
  6538. else if (shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
  6539. processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6540. }
  6541. else if (shapeFlag & 64 /* ShapeFlags.TELEPORT */) {
  6542. type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
  6543. }
  6544. else if (shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  6545. type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
  6546. }
  6547. else {
  6548. warn$1('Invalid VNode type:', type, `(${typeof type})`);
  6549. }
  6550. }
  6551. // set ref
  6552. if (ref != null && parentComponent) {
  6553. setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
  6554. }
  6555. };
  6556. const processText = (n1, n2, container, anchor) => {
  6557. if (n1 == null) {
  6558. hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
  6559. }
  6560. else {
  6561. const el = (n2.el = n1.el);
  6562. if (n2.children !== n1.children) {
  6563. hostSetText(el, n2.children);
  6564. }
  6565. }
  6566. };
  6567. const processCommentNode = (n1, n2, container, anchor) => {
  6568. if (n1 == null) {
  6569. hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
  6570. }
  6571. else {
  6572. // there's no support for dynamic comments
  6573. n2.el = n1.el;
  6574. }
  6575. };
  6576. const mountStaticNode = (n2, container, anchor, isSVG) => {
  6577. [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG, n2.el, n2.anchor);
  6578. };
  6579. /**
  6580. * Dev / HMR only
  6581. */
  6582. const patchStaticNode = (n1, n2, container, isSVG) => {
  6583. // static nodes are only patched during dev for HMR
  6584. if (n2.children !== n1.children) {
  6585. const anchor = hostNextSibling(n1.anchor);
  6586. // remove existing
  6587. removeStaticNode(n1);
  6588. [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
  6589. }
  6590. else {
  6591. n2.el = n1.el;
  6592. n2.anchor = n1.anchor;
  6593. }
  6594. };
  6595. const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
  6596. let next;
  6597. while (el && el !== anchor) {
  6598. next = hostNextSibling(el);
  6599. hostInsert(el, container, nextSibling);
  6600. el = next;
  6601. }
  6602. hostInsert(anchor, container, nextSibling);
  6603. };
  6604. const removeStaticNode = ({ el, anchor }) => {
  6605. let next;
  6606. while (el && el !== anchor) {
  6607. next = hostNextSibling(el);
  6608. hostRemove(el);
  6609. el = next;
  6610. }
  6611. hostRemove(anchor);
  6612. };
  6613. const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6614. isSVG = isSVG || n2.type === 'svg';
  6615. if (n1 == null) {
  6616. mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6617. }
  6618. else {
  6619. patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6620. }
  6621. };
  6622. const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6623. let el;
  6624. let vnodeHook;
  6625. const { type, props, shapeFlag, transition, dirs } = vnode;
  6626. el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
  6627. // mount children first, since some props may rely on child content
  6628. // being already rendered, e.g. `<select value>`
  6629. if (shapeFlag & 8 /* ShapeFlags.TEXT_CHILDREN */) {
  6630. hostSetElementText(el, vnode.children);
  6631. }
  6632. else if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  6633. mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', slotScopeIds, optimized);
  6634. }
  6635. if (dirs) {
  6636. invokeDirectiveHook(vnode, null, parentComponent, 'created');
  6637. }
  6638. // props
  6639. if (props) {
  6640. for (const key in props) {
  6641. if (key !== 'value' && !isReservedProp(key)) {
  6642. hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  6643. }
  6644. }
  6645. /**
  6646. * Special case for setting value on DOM elements:
  6647. * - it can be order-sensitive (e.g. should be set *after* min/max, #2325, #4024)
  6648. * - it needs to be forced (#1471)
  6649. * #2353 proposes adding another renderer option to configure this, but
  6650. * the properties affects are so finite it is worth special casing it
  6651. * here to reduce the complexity. (Special casing it also should not
  6652. * affect non-DOM renderers)
  6653. */
  6654. if ('value' in props) {
  6655. hostPatchProp(el, 'value', null, props.value);
  6656. }
  6657. if ((vnodeHook = props.onVnodeBeforeMount)) {
  6658. invokeVNodeHook(vnodeHook, parentComponent, vnode);
  6659. }
  6660. }
  6661. // scopeId
  6662. setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
  6663. {
  6664. Object.defineProperty(el, '__vnode', {
  6665. value: vnode,
  6666. enumerable: false
  6667. });
  6668. Object.defineProperty(el, '__vueParentComponent', {
  6669. value: parentComponent,
  6670. enumerable: false
  6671. });
  6672. }
  6673. if (dirs) {
  6674. invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
  6675. }
  6676. // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
  6677. // #1689 For inside suspense + suspense resolved case, just call it
  6678. const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
  6679. transition &&
  6680. !transition.persisted;
  6681. if (needCallTransitionHooks) {
  6682. transition.beforeEnter(el);
  6683. }
  6684. hostInsert(el, container, anchor);
  6685. if ((vnodeHook = props && props.onVnodeMounted) ||
  6686. needCallTransitionHooks ||
  6687. dirs) {
  6688. queuePostRenderEffect(() => {
  6689. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
  6690. needCallTransitionHooks && transition.enter(el);
  6691. dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
  6692. }, parentSuspense);
  6693. }
  6694. };
  6695. const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
  6696. if (scopeId) {
  6697. hostSetScopeId(el, scopeId);
  6698. }
  6699. if (slotScopeIds) {
  6700. for (let i = 0; i < slotScopeIds.length; i++) {
  6701. hostSetScopeId(el, slotScopeIds[i]);
  6702. }
  6703. }
  6704. if (parentComponent) {
  6705. let subTree = parentComponent.subTree;
  6706. if (subTree.patchFlag > 0 &&
  6707. subTree.patchFlag & 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */) {
  6708. subTree =
  6709. filterSingleRoot(subTree.children) || subTree;
  6710. }
  6711. if (vnode === subTree) {
  6712. const parentVNode = parentComponent.vnode;
  6713. setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
  6714. }
  6715. }
  6716. };
  6717. const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, start = 0) => {
  6718. for (let i = start; i < children.length; i++) {
  6719. const child = (children[i] = optimized
  6720. ? cloneIfMounted(children[i])
  6721. : normalizeVNode(children[i]));
  6722. patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6723. }
  6724. };
  6725. const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6726. const el = (n2.el = n1.el);
  6727. let { patchFlag, dynamicChildren, dirs } = n2;
  6728. // #1426 take the old vnode's patch flag into account since user may clone a
  6729. // compiler-generated vnode, which de-opts to FULL_PROPS
  6730. patchFlag |= n1.patchFlag & 16 /* PatchFlags.FULL_PROPS */;
  6731. const oldProps = n1.props || EMPTY_OBJ;
  6732. const newProps = n2.props || EMPTY_OBJ;
  6733. let vnodeHook;
  6734. // disable recurse in beforeUpdate hooks
  6735. parentComponent && toggleRecurse(parentComponent, false);
  6736. if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
  6737. invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
  6738. }
  6739. if (dirs) {
  6740. invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
  6741. }
  6742. parentComponent && toggleRecurse(parentComponent, true);
  6743. if (isHmrUpdating) {
  6744. // HMR updated, force full diff
  6745. patchFlag = 0;
  6746. optimized = false;
  6747. dynamicChildren = null;
  6748. }
  6749. const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
  6750. if (dynamicChildren) {
  6751. patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
  6752. if (parentComponent && parentComponent.type.__hmrId) {
  6753. traverseStaticChildren(n1, n2);
  6754. }
  6755. }
  6756. else if (!optimized) {
  6757. // full diff
  6758. patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
  6759. }
  6760. if (patchFlag > 0) {
  6761. // the presence of a patchFlag means this element's render code was
  6762. // generated by the compiler and can take the fast path.
  6763. // in this path old node and new node are guaranteed to have the same shape
  6764. // (i.e. at the exact same position in the source template)
  6765. if (patchFlag & 16 /* PatchFlags.FULL_PROPS */) {
  6766. // element props contain dynamic keys, full diff needed
  6767. patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
  6768. }
  6769. else {
  6770. // class
  6771. // this flag is matched when the element has dynamic class bindings.
  6772. if (patchFlag & 2 /* PatchFlags.CLASS */) {
  6773. if (oldProps.class !== newProps.class) {
  6774. hostPatchProp(el, 'class', null, newProps.class, isSVG);
  6775. }
  6776. }
  6777. // style
  6778. // this flag is matched when the element has dynamic style bindings
  6779. if (patchFlag & 4 /* PatchFlags.STYLE */) {
  6780. hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
  6781. }
  6782. // props
  6783. // This flag is matched when the element has dynamic prop/attr bindings
  6784. // other than class and style. The keys of dynamic prop/attrs are saved for
  6785. // faster iteration.
  6786. // Note dynamic keys like :[foo]="bar" will cause this optimization to
  6787. // bail out and go through a full diff because we need to unset the old key
  6788. if (patchFlag & 8 /* PatchFlags.PROPS */) {
  6789. // if the flag is present then dynamicProps must be non-null
  6790. const propsToUpdate = n2.dynamicProps;
  6791. for (let i = 0; i < propsToUpdate.length; i++) {
  6792. const key = propsToUpdate[i];
  6793. const prev = oldProps[key];
  6794. const next = newProps[key];
  6795. // #1471 force patch value
  6796. if (next !== prev || key === 'value') {
  6797. hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
  6798. }
  6799. }
  6800. }
  6801. }
  6802. // text
  6803. // This flag is matched when the element has only dynamic text children.
  6804. if (patchFlag & 1 /* PatchFlags.TEXT */) {
  6805. if (n1.children !== n2.children) {
  6806. hostSetElementText(el, n2.children);
  6807. }
  6808. }
  6809. }
  6810. else if (!optimized && dynamicChildren == null) {
  6811. // unoptimized, full diff
  6812. patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
  6813. }
  6814. if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
  6815. queuePostRenderEffect(() => {
  6816. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
  6817. dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
  6818. }, parentSuspense);
  6819. }
  6820. };
  6821. // The fast path for blocks.
  6822. const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
  6823. for (let i = 0; i < newChildren.length; i++) {
  6824. const oldVNode = oldChildren[i];
  6825. const newVNode = newChildren[i];
  6826. // Determine the container (parent element) for the patch.
  6827. const container =
  6828. // oldVNode may be an errored async setup() component inside Suspense
  6829. // which will not have a mounted element
  6830. oldVNode.el &&
  6831. // - In the case of a Fragment, we need to provide the actual parent
  6832. // of the Fragment itself so it can move its children.
  6833. (oldVNode.type === Fragment ||
  6834. // - In the case of different nodes, there is going to be a replacement
  6835. // which also requires the correct parent container
  6836. !isSameVNodeType(oldVNode, newVNode) ||
  6837. // - In the case of a component, it could contain anything.
  6838. oldVNode.shapeFlag & (6 /* ShapeFlags.COMPONENT */ | 64 /* ShapeFlags.TELEPORT */))
  6839. ? hostParentNode(oldVNode.el)
  6840. : // In other cases, the parent container is not actually used so we
  6841. // just pass the block element here to avoid a DOM parentNode call.
  6842. fallbackContainer;
  6843. patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
  6844. }
  6845. };
  6846. const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
  6847. if (oldProps !== newProps) {
  6848. if (oldProps !== EMPTY_OBJ) {
  6849. for (const key in oldProps) {
  6850. if (!isReservedProp(key) && !(key in newProps)) {
  6851. hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  6852. }
  6853. }
  6854. }
  6855. for (const key in newProps) {
  6856. // empty string is not valid prop
  6857. if (isReservedProp(key))
  6858. continue;
  6859. const next = newProps[key];
  6860. const prev = oldProps[key];
  6861. // defer patching value
  6862. if (next !== prev && key !== 'value') {
  6863. hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  6864. }
  6865. }
  6866. if ('value' in newProps) {
  6867. hostPatchProp(el, 'value', oldProps.value, newProps.value);
  6868. }
  6869. }
  6870. };
  6871. const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6872. const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
  6873. const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
  6874. let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
  6875. if (// #5523 dev root fragment may inherit directives
  6876. (isHmrUpdating || patchFlag & 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */)) {
  6877. // HMR updated / Dev root fragment (w/ comments), force full diff
  6878. patchFlag = 0;
  6879. optimized = false;
  6880. dynamicChildren = null;
  6881. }
  6882. // check if this is a slot fragment with :slotted scope ids
  6883. if (fragmentSlotScopeIds) {
  6884. slotScopeIds = slotScopeIds
  6885. ? slotScopeIds.concat(fragmentSlotScopeIds)
  6886. : fragmentSlotScopeIds;
  6887. }
  6888. if (n1 == null) {
  6889. hostInsert(fragmentStartAnchor, container, anchor);
  6890. hostInsert(fragmentEndAnchor, container, anchor);
  6891. // a fragment can only have array children
  6892. // since they are either generated by the compiler, or implicitly created
  6893. // from arrays.
  6894. mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6895. }
  6896. else {
  6897. if (patchFlag > 0 &&
  6898. patchFlag & 64 /* PatchFlags.STABLE_FRAGMENT */ &&
  6899. dynamicChildren &&
  6900. // #2715 the previous fragment could've been a BAILed one as a result
  6901. // of renderSlot() with no valid children
  6902. n1.dynamicChildren) {
  6903. // a stable fragment (template root or <template v-for>) doesn't need to
  6904. // patch children order, but it may contain dynamicChildren.
  6905. patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
  6906. if (parentComponent && parentComponent.type.__hmrId) {
  6907. traverseStaticChildren(n1, n2);
  6908. }
  6909. else if (
  6910. // #2080 if the stable fragment has a key, it's a <template v-for> that may
  6911. // get moved around. Make sure all root level vnodes inherit el.
  6912. // #2134 or if it's a component root, it may also get moved around
  6913. // as the component is being moved.
  6914. n2.key != null ||
  6915. (parentComponent && n2 === parentComponent.subTree)) {
  6916. traverseStaticChildren(n1, n2, true /* shallow */);
  6917. }
  6918. }
  6919. else {
  6920. // keyed / unkeyed, or manual fragments.
  6921. // for keyed & unkeyed, since they are compiler generated from v-for,
  6922. // each child is guaranteed to be a block so the fragment will never
  6923. // have dynamicChildren.
  6924. patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6925. }
  6926. }
  6927. };
  6928. const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6929. n2.slotScopeIds = slotScopeIds;
  6930. if (n1 == null) {
  6931. if (n2.shapeFlag & 512 /* ShapeFlags.COMPONENT_KEPT_ALIVE */) {
  6932. parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
  6933. }
  6934. else {
  6935. mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  6936. }
  6937. }
  6938. else {
  6939. updateComponent(n1, n2, optimized);
  6940. }
  6941. };
  6942. const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  6943. const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
  6944. if (instance.type.__hmrId) {
  6945. registerHMR(instance);
  6946. }
  6947. {
  6948. pushWarningContext(initialVNode);
  6949. startMeasure(instance, `mount`);
  6950. }
  6951. // inject renderer internals for keepAlive
  6952. if (isKeepAlive(initialVNode)) {
  6953. instance.ctx.renderer = internals;
  6954. }
  6955. // resolve props and slots for setup context
  6956. {
  6957. {
  6958. startMeasure(instance, `init`);
  6959. }
  6960. setupComponent(instance);
  6961. {
  6962. endMeasure(instance, `init`);
  6963. }
  6964. }
  6965. // setup() is async. This component relies on async logic to be resolved
  6966. // before proceeding
  6967. if (instance.asyncDep) {
  6968. parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
  6969. // Give it a placeholder if this is not hydration
  6970. // TODO handle self-defined fallback
  6971. if (!initialVNode.el) {
  6972. const placeholder = (instance.subTree = createVNode(Comment));
  6973. processCommentNode(null, placeholder, container, anchor);
  6974. }
  6975. return;
  6976. }
  6977. setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
  6978. {
  6979. popWarningContext();
  6980. endMeasure(instance, `mount`);
  6981. }
  6982. };
  6983. const updateComponent = (n1, n2, optimized) => {
  6984. const instance = (n2.component = n1.component);
  6985. if (shouldUpdateComponent(n1, n2, optimized)) {
  6986. if (instance.asyncDep &&
  6987. !instance.asyncResolved) {
  6988. // async & still pending - just update props and slots
  6989. // since the component's reactive effect for render isn't set-up yet
  6990. {
  6991. pushWarningContext(n2);
  6992. }
  6993. updateComponentPreRender(instance, n2, optimized);
  6994. {
  6995. popWarningContext();
  6996. }
  6997. return;
  6998. }
  6999. else {
  7000. // normal update
  7001. instance.next = n2;
  7002. // in case the child component is also queued, remove it to avoid
  7003. // double updating the same child component in the same flush.
  7004. invalidateJob(instance.update);
  7005. // instance.update is the reactive effect.
  7006. instance.update();
  7007. }
  7008. }
  7009. else {
  7010. // no update needed. just copy over properties
  7011. n2.el = n1.el;
  7012. instance.vnode = n2;
  7013. }
  7014. };
  7015. const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
  7016. const componentUpdateFn = () => {
  7017. if (!instance.isMounted) {
  7018. let vnodeHook;
  7019. const { el, props } = initialVNode;
  7020. const { bm, m, parent } = instance;
  7021. const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);
  7022. toggleRecurse(instance, false);
  7023. // beforeMount hook
  7024. if (bm) {
  7025. invokeArrayFns(bm);
  7026. }
  7027. // onVnodeBeforeMount
  7028. if (!isAsyncWrapperVNode &&
  7029. (vnodeHook = props && props.onVnodeBeforeMount)) {
  7030. invokeVNodeHook(vnodeHook, parent, initialVNode);
  7031. }
  7032. toggleRecurse(instance, true);
  7033. if (el && hydrateNode) {
  7034. // vnode has adopted host node - perform hydration instead of mount.
  7035. const hydrateSubTree = () => {
  7036. {
  7037. startMeasure(instance, `render`);
  7038. }
  7039. instance.subTree = renderComponentRoot(instance);
  7040. {
  7041. endMeasure(instance, `render`);
  7042. }
  7043. {
  7044. startMeasure(instance, `hydrate`);
  7045. }
  7046. hydrateNode(el, instance.subTree, instance, parentSuspense, null);
  7047. {
  7048. endMeasure(instance, `hydrate`);
  7049. }
  7050. };
  7051. if (isAsyncWrapperVNode) {
  7052. initialVNode.type.__asyncLoader().then(
  7053. // note: we are moving the render call into an async callback,
  7054. // which means it won't track dependencies - but it's ok because
  7055. // a server-rendered async wrapper is already in resolved state
  7056. // and it will never need to change.
  7057. () => !instance.isUnmounted && hydrateSubTree());
  7058. }
  7059. else {
  7060. hydrateSubTree();
  7061. }
  7062. }
  7063. else {
  7064. {
  7065. startMeasure(instance, `render`);
  7066. }
  7067. const subTree = (instance.subTree = renderComponentRoot(instance));
  7068. {
  7069. endMeasure(instance, `render`);
  7070. }
  7071. {
  7072. startMeasure(instance, `patch`);
  7073. }
  7074. patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
  7075. {
  7076. endMeasure(instance, `patch`);
  7077. }
  7078. initialVNode.el = subTree.el;
  7079. }
  7080. // mounted hook
  7081. if (m) {
  7082. queuePostRenderEffect(m, parentSuspense);
  7083. }
  7084. // onVnodeMounted
  7085. if (!isAsyncWrapperVNode &&
  7086. (vnodeHook = props && props.onVnodeMounted)) {
  7087. const scopedInitialVNode = initialVNode;
  7088. queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense);
  7089. }
  7090. // activated hook for keep-alive roots.
  7091. // #1742 activated hook must be accessed after first render
  7092. // since the hook may be injected by a child keep-alive
  7093. if (initialVNode.shapeFlag & 256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */ ||
  7094. (parent &&
  7095. isAsyncWrapper(parent.vnode) &&
  7096. parent.vnode.shapeFlag & 256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */)) {
  7097. instance.a && queuePostRenderEffect(instance.a, parentSuspense);
  7098. }
  7099. instance.isMounted = true;
  7100. {
  7101. devtoolsComponentAdded(instance);
  7102. }
  7103. // #2458: deference mount-only object parameters to prevent memleaks
  7104. initialVNode = container = anchor = null;
  7105. }
  7106. else {
  7107. // updateComponent
  7108. // This is triggered by mutation of component's own state (next: null)
  7109. // OR parent calling processComponent (next: VNode)
  7110. let { next, bu, u, parent, vnode } = instance;
  7111. let originNext = next;
  7112. let vnodeHook;
  7113. {
  7114. pushWarningContext(next || instance.vnode);
  7115. }
  7116. // Disallow component effect recursion during pre-lifecycle hooks.
  7117. toggleRecurse(instance, false);
  7118. if (next) {
  7119. next.el = vnode.el;
  7120. updateComponentPreRender(instance, next, optimized);
  7121. }
  7122. else {
  7123. next = vnode;
  7124. }
  7125. // beforeUpdate hook
  7126. if (bu) {
  7127. invokeArrayFns(bu);
  7128. }
  7129. // onVnodeBeforeUpdate
  7130. if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
  7131. invokeVNodeHook(vnodeHook, parent, next, vnode);
  7132. }
  7133. toggleRecurse(instance, true);
  7134. // render
  7135. {
  7136. startMeasure(instance, `render`);
  7137. }
  7138. const nextTree = renderComponentRoot(instance);
  7139. {
  7140. endMeasure(instance, `render`);
  7141. }
  7142. const prevTree = instance.subTree;
  7143. instance.subTree = nextTree;
  7144. {
  7145. startMeasure(instance, `patch`);
  7146. }
  7147. patch(prevTree, nextTree,
  7148. // parent may have changed if it's in a teleport
  7149. hostParentNode(prevTree.el),
  7150. // anchor may have changed if it's in a fragment
  7151. getNextHostNode(prevTree), instance, parentSuspense, isSVG);
  7152. {
  7153. endMeasure(instance, `patch`);
  7154. }
  7155. next.el = nextTree.el;
  7156. if (originNext === null) {
  7157. // self-triggered update. In case of HOC, update parent component
  7158. // vnode el. HOC is indicated by parent instance's subTree pointing
  7159. // to child component's vnode
  7160. updateHOCHostEl(instance, nextTree.el);
  7161. }
  7162. // updated hook
  7163. if (u) {
  7164. queuePostRenderEffect(u, parentSuspense);
  7165. }
  7166. // onVnodeUpdated
  7167. if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
  7168. queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense);
  7169. }
  7170. {
  7171. devtoolsComponentUpdated(instance);
  7172. }
  7173. {
  7174. popWarningContext();
  7175. }
  7176. }
  7177. };
  7178. // create reactive effect for rendering
  7179. const effect = (instance.effect = new ReactiveEffect(componentUpdateFn, () => queueJob(update), instance.scope // track it in component's effect scope
  7180. ));
  7181. const update = (instance.update = () => effect.run());
  7182. update.id = instance.uid;
  7183. // allowRecurse
  7184. // #1801, #2043 component render effects should allow recursive updates
  7185. toggleRecurse(instance, true);
  7186. {
  7187. effect.onTrack = instance.rtc
  7188. ? e => invokeArrayFns(instance.rtc, e)
  7189. : void 0;
  7190. effect.onTrigger = instance.rtg
  7191. ? e => invokeArrayFns(instance.rtg, e)
  7192. : void 0;
  7193. update.ownerInstance = instance;
  7194. }
  7195. update();
  7196. };
  7197. const updateComponentPreRender = (instance, nextVNode, optimized) => {
  7198. nextVNode.component = instance;
  7199. const prevProps = instance.vnode.props;
  7200. instance.vnode = nextVNode;
  7201. instance.next = null;
  7202. updateProps(instance, nextVNode.props, prevProps, optimized);
  7203. updateSlots(instance, nextVNode.children, optimized);
  7204. pauseTracking();
  7205. // props update may have triggered pre-flush watchers.
  7206. // flush them before the render update.
  7207. flushPreFlushCbs();
  7208. resetTracking();
  7209. };
  7210. const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
  7211. const c1 = n1 && n1.children;
  7212. const prevShapeFlag = n1 ? n1.shapeFlag : 0;
  7213. const c2 = n2.children;
  7214. const { patchFlag, shapeFlag } = n2;
  7215. // fast path
  7216. if (patchFlag > 0) {
  7217. if (patchFlag & 128 /* PatchFlags.KEYED_FRAGMENT */) {
  7218. // this could be either fully-keyed or mixed (some keyed some not)
  7219. // presence of patchFlag means children are guaranteed to be arrays
  7220. patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7221. return;
  7222. }
  7223. else if (patchFlag & 256 /* PatchFlags.UNKEYED_FRAGMENT */) {
  7224. // unkeyed
  7225. patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7226. return;
  7227. }
  7228. }
  7229. // children has 3 possibilities: text, array or no children.
  7230. if (shapeFlag & 8 /* ShapeFlags.TEXT_CHILDREN */) {
  7231. // text children fast path
  7232. if (prevShapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  7233. unmountChildren(c1, parentComponent, parentSuspense);
  7234. }
  7235. if (c2 !== c1) {
  7236. hostSetElementText(container, c2);
  7237. }
  7238. }
  7239. else {
  7240. if (prevShapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  7241. // prev children was array
  7242. if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  7243. // two arrays, cannot assume anything, do full diff
  7244. patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7245. }
  7246. else {
  7247. // no new children, just unmount old
  7248. unmountChildren(c1, parentComponent, parentSuspense, true);
  7249. }
  7250. }
  7251. else {
  7252. // prev children was text OR null
  7253. // new children is array OR null
  7254. if (prevShapeFlag & 8 /* ShapeFlags.TEXT_CHILDREN */) {
  7255. hostSetElementText(container, '');
  7256. }
  7257. // mount new if array
  7258. if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  7259. mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7260. }
  7261. }
  7262. }
  7263. };
  7264. const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  7265. c1 = c1 || EMPTY_ARR;
  7266. c2 = c2 || EMPTY_ARR;
  7267. const oldLength = c1.length;
  7268. const newLength = c2.length;
  7269. const commonLength = Math.min(oldLength, newLength);
  7270. let i;
  7271. for (i = 0; i < commonLength; i++) {
  7272. const nextChild = (c2[i] = optimized
  7273. ? cloneIfMounted(c2[i])
  7274. : normalizeVNode(c2[i]));
  7275. patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7276. }
  7277. if (oldLength > newLength) {
  7278. // remove old
  7279. unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
  7280. }
  7281. else {
  7282. // mount new
  7283. mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
  7284. }
  7285. };
  7286. // can be all-keyed or mixed
  7287. const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  7288. let i = 0;
  7289. const l2 = c2.length;
  7290. let e1 = c1.length - 1; // prev ending index
  7291. let e2 = l2 - 1; // next ending index
  7292. // 1. sync from start
  7293. // (a b) c
  7294. // (a b) d e
  7295. while (i <= e1 && i <= e2) {
  7296. const n1 = c1[i];
  7297. const n2 = (c2[i] = optimized
  7298. ? cloneIfMounted(c2[i])
  7299. : normalizeVNode(c2[i]));
  7300. if (isSameVNodeType(n1, n2)) {
  7301. patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7302. }
  7303. else {
  7304. break;
  7305. }
  7306. i++;
  7307. }
  7308. // 2. sync from end
  7309. // a (b c)
  7310. // d e (b c)
  7311. while (i <= e1 && i <= e2) {
  7312. const n1 = c1[e1];
  7313. const n2 = (c2[e2] = optimized
  7314. ? cloneIfMounted(c2[e2])
  7315. : normalizeVNode(c2[e2]));
  7316. if (isSameVNodeType(n1, n2)) {
  7317. patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7318. }
  7319. else {
  7320. break;
  7321. }
  7322. e1--;
  7323. e2--;
  7324. }
  7325. // 3. common sequence + mount
  7326. // (a b)
  7327. // (a b) c
  7328. // i = 2, e1 = 1, e2 = 2
  7329. // (a b)
  7330. // c (a b)
  7331. // i = 0, e1 = -1, e2 = 0
  7332. if (i > e1) {
  7333. if (i <= e2) {
  7334. const nextPos = e2 + 1;
  7335. const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
  7336. while (i <= e2) {
  7337. patch(null, (c2[i] = optimized
  7338. ? cloneIfMounted(c2[i])
  7339. : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7340. i++;
  7341. }
  7342. }
  7343. }
  7344. // 4. common sequence + unmount
  7345. // (a b) c
  7346. // (a b)
  7347. // i = 2, e1 = 2, e2 = 1
  7348. // a (b c)
  7349. // (b c)
  7350. // i = 0, e1 = 0, e2 = -1
  7351. else if (i > e2) {
  7352. while (i <= e1) {
  7353. unmount(c1[i], parentComponent, parentSuspense, true);
  7354. i++;
  7355. }
  7356. }
  7357. // 5. unknown sequence
  7358. // [i ... e1 + 1]: a b [c d e] f g
  7359. // [i ... e2 + 1]: a b [e d c h] f g
  7360. // i = 2, e1 = 4, e2 = 5
  7361. else {
  7362. const s1 = i; // prev starting index
  7363. const s2 = i; // next starting index
  7364. // 5.1 build key:index map for newChildren
  7365. const keyToNewIndexMap = new Map();
  7366. for (i = s2; i <= e2; i++) {
  7367. const nextChild = (c2[i] = optimized
  7368. ? cloneIfMounted(c2[i])
  7369. : normalizeVNode(c2[i]));
  7370. if (nextChild.key != null) {
  7371. if (keyToNewIndexMap.has(nextChild.key)) {
  7372. warn$1(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
  7373. }
  7374. keyToNewIndexMap.set(nextChild.key, i);
  7375. }
  7376. }
  7377. // 5.2 loop through old children left to be patched and try to patch
  7378. // matching nodes & remove nodes that are no longer present
  7379. let j;
  7380. let patched = 0;
  7381. const toBePatched = e2 - s2 + 1;
  7382. let moved = false;
  7383. // used to track whether any node has moved
  7384. let maxNewIndexSoFar = 0;
  7385. // works as Map<newIndex, oldIndex>
  7386. // Note that oldIndex is offset by +1
  7387. // and oldIndex = 0 is a special value indicating the new node has
  7388. // no corresponding old node.
  7389. // used for determining longest stable subsequence
  7390. const newIndexToOldIndexMap = new Array(toBePatched);
  7391. for (i = 0; i < toBePatched; i++)
  7392. newIndexToOldIndexMap[i] = 0;
  7393. for (i = s1; i <= e1; i++) {
  7394. const prevChild = c1[i];
  7395. if (patched >= toBePatched) {
  7396. // all new children have been patched so this can only be a removal
  7397. unmount(prevChild, parentComponent, parentSuspense, true);
  7398. continue;
  7399. }
  7400. let newIndex;
  7401. if (prevChild.key != null) {
  7402. newIndex = keyToNewIndexMap.get(prevChild.key);
  7403. }
  7404. else {
  7405. // key-less node, try to locate a key-less node of the same type
  7406. for (j = s2; j <= e2; j++) {
  7407. if (newIndexToOldIndexMap[j - s2] === 0 &&
  7408. isSameVNodeType(prevChild, c2[j])) {
  7409. newIndex = j;
  7410. break;
  7411. }
  7412. }
  7413. }
  7414. if (newIndex === undefined) {
  7415. unmount(prevChild, parentComponent, parentSuspense, true);
  7416. }
  7417. else {
  7418. newIndexToOldIndexMap[newIndex - s2] = i + 1;
  7419. if (newIndex >= maxNewIndexSoFar) {
  7420. maxNewIndexSoFar = newIndex;
  7421. }
  7422. else {
  7423. moved = true;
  7424. }
  7425. patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7426. patched++;
  7427. }
  7428. }
  7429. // 5.3 move and mount
  7430. // generate longest stable subsequence only when nodes have moved
  7431. const increasingNewIndexSequence = moved
  7432. ? getSequence(newIndexToOldIndexMap)
  7433. : EMPTY_ARR;
  7434. j = increasingNewIndexSequence.length - 1;
  7435. // looping backwards so that we can use last patched node as anchor
  7436. for (i = toBePatched - 1; i >= 0; i--) {
  7437. const nextIndex = s2 + i;
  7438. const nextChild = c2[nextIndex];
  7439. const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
  7440. if (newIndexToOldIndexMap[i] === 0) {
  7441. // mount new
  7442. patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7443. }
  7444. else if (moved) {
  7445. // move if:
  7446. // There is no stable subsequence (e.g. a reverse)
  7447. // OR current node is not among the stable sequence
  7448. if (j < 0 || i !== increasingNewIndexSequence[j]) {
  7449. move(nextChild, container, anchor, 2 /* MoveType.REORDER */);
  7450. }
  7451. else {
  7452. j--;
  7453. }
  7454. }
  7455. }
  7456. }
  7457. };
  7458. const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
  7459. const { el, type, transition, children, shapeFlag } = vnode;
  7460. if (shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
  7461. move(vnode.component.subTree, container, anchor, moveType);
  7462. return;
  7463. }
  7464. if (shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  7465. vnode.suspense.move(container, anchor, moveType);
  7466. return;
  7467. }
  7468. if (shapeFlag & 64 /* ShapeFlags.TELEPORT */) {
  7469. type.move(vnode, container, anchor, internals);
  7470. return;
  7471. }
  7472. if (type === Fragment) {
  7473. hostInsert(el, container, anchor);
  7474. for (let i = 0; i < children.length; i++) {
  7475. move(children[i], container, anchor, moveType);
  7476. }
  7477. hostInsert(vnode.anchor, container, anchor);
  7478. return;
  7479. }
  7480. if (type === Static) {
  7481. moveStaticNode(vnode, container, anchor);
  7482. return;
  7483. }
  7484. // single nodes
  7485. const needTransition = moveType !== 2 /* MoveType.REORDER */ &&
  7486. shapeFlag & 1 /* ShapeFlags.ELEMENT */ &&
  7487. transition;
  7488. if (needTransition) {
  7489. if (moveType === 0 /* MoveType.ENTER */) {
  7490. transition.beforeEnter(el);
  7491. hostInsert(el, container, anchor);
  7492. queuePostRenderEffect(() => transition.enter(el), parentSuspense);
  7493. }
  7494. else {
  7495. const { leave, delayLeave, afterLeave } = transition;
  7496. const remove = () => hostInsert(el, container, anchor);
  7497. const performLeave = () => {
  7498. leave(el, () => {
  7499. remove();
  7500. afterLeave && afterLeave();
  7501. });
  7502. };
  7503. if (delayLeave) {
  7504. delayLeave(el, remove, performLeave);
  7505. }
  7506. else {
  7507. performLeave();
  7508. }
  7509. }
  7510. }
  7511. else {
  7512. hostInsert(el, container, anchor);
  7513. }
  7514. };
  7515. const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
  7516. const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
  7517. // unset ref
  7518. if (ref != null) {
  7519. setRef(ref, null, parentSuspense, vnode, true);
  7520. }
  7521. if (shapeFlag & 256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */) {
  7522. parentComponent.ctx.deactivate(vnode);
  7523. return;
  7524. }
  7525. const shouldInvokeDirs = shapeFlag & 1 /* ShapeFlags.ELEMENT */ && dirs;
  7526. const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);
  7527. let vnodeHook;
  7528. if (shouldInvokeVnodeHook &&
  7529. (vnodeHook = props && props.onVnodeBeforeUnmount)) {
  7530. invokeVNodeHook(vnodeHook, parentComponent, vnode);
  7531. }
  7532. if (shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
  7533. unmountComponent(vnode.component, parentSuspense, doRemove);
  7534. }
  7535. else {
  7536. if (shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  7537. vnode.suspense.unmount(parentSuspense, doRemove);
  7538. return;
  7539. }
  7540. if (shouldInvokeDirs) {
  7541. invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
  7542. }
  7543. if (shapeFlag & 64 /* ShapeFlags.TELEPORT */) {
  7544. vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
  7545. }
  7546. else if (dynamicChildren &&
  7547. // #1153: fast path should not be taken for non-stable (v-for) fragments
  7548. (type !== Fragment ||
  7549. (patchFlag > 0 && patchFlag & 64 /* PatchFlags.STABLE_FRAGMENT */))) {
  7550. // fast path for block nodes: only need to unmount dynamic children.
  7551. unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
  7552. }
  7553. else if ((type === Fragment &&
  7554. patchFlag &
  7555. (128 /* PatchFlags.KEYED_FRAGMENT */ | 256 /* PatchFlags.UNKEYED_FRAGMENT */)) ||
  7556. (!optimized && shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */)) {
  7557. unmountChildren(children, parentComponent, parentSuspense);
  7558. }
  7559. if (doRemove) {
  7560. remove(vnode);
  7561. }
  7562. }
  7563. if ((shouldInvokeVnodeHook &&
  7564. (vnodeHook = props && props.onVnodeUnmounted)) ||
  7565. shouldInvokeDirs) {
  7566. queuePostRenderEffect(() => {
  7567. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
  7568. shouldInvokeDirs &&
  7569. invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
  7570. }, parentSuspense);
  7571. }
  7572. };
  7573. const remove = vnode => {
  7574. const { type, el, anchor, transition } = vnode;
  7575. if (type === Fragment) {
  7576. if (vnode.patchFlag > 0 &&
  7577. vnode.patchFlag & 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */ &&
  7578. transition &&
  7579. !transition.persisted) {
  7580. vnode.children.forEach(child => {
  7581. if (child.type === Comment) {
  7582. hostRemove(child.el);
  7583. }
  7584. else {
  7585. remove(child);
  7586. }
  7587. });
  7588. }
  7589. else {
  7590. removeFragment(el, anchor);
  7591. }
  7592. return;
  7593. }
  7594. if (type === Static) {
  7595. removeStaticNode(vnode);
  7596. return;
  7597. }
  7598. const performRemove = () => {
  7599. hostRemove(el);
  7600. if (transition && !transition.persisted && transition.afterLeave) {
  7601. transition.afterLeave();
  7602. }
  7603. };
  7604. if (vnode.shapeFlag & 1 /* ShapeFlags.ELEMENT */ &&
  7605. transition &&
  7606. !transition.persisted) {
  7607. const { leave, delayLeave } = transition;
  7608. const performLeave = () => leave(el, performRemove);
  7609. if (delayLeave) {
  7610. delayLeave(vnode.el, performRemove, performLeave);
  7611. }
  7612. else {
  7613. performLeave();
  7614. }
  7615. }
  7616. else {
  7617. performRemove();
  7618. }
  7619. };
  7620. const removeFragment = (cur, end) => {
  7621. // For fragments, directly remove all contained DOM nodes.
  7622. // (fragment child nodes cannot have transition)
  7623. let next;
  7624. while (cur !== end) {
  7625. next = hostNextSibling(cur);
  7626. hostRemove(cur);
  7627. cur = next;
  7628. }
  7629. hostRemove(end);
  7630. };
  7631. const unmountComponent = (instance, parentSuspense, doRemove) => {
  7632. if (instance.type.__hmrId) {
  7633. unregisterHMR(instance);
  7634. }
  7635. const { bum, scope, update, subTree, um } = instance;
  7636. // beforeUnmount hook
  7637. if (bum) {
  7638. invokeArrayFns(bum);
  7639. }
  7640. // stop effects in component scope
  7641. scope.stop();
  7642. // update may be null if a component is unmounted before its async
  7643. // setup has resolved.
  7644. if (update) {
  7645. // so that scheduler will no longer invoke it
  7646. update.active = false;
  7647. unmount(subTree, instance, parentSuspense, doRemove);
  7648. }
  7649. // unmounted hook
  7650. if (um) {
  7651. queuePostRenderEffect(um, parentSuspense);
  7652. }
  7653. queuePostRenderEffect(() => {
  7654. instance.isUnmounted = true;
  7655. }, parentSuspense);
  7656. // A component with async dep inside a pending suspense is unmounted before
  7657. // its async dep resolves. This should remove the dep from the suspense, and
  7658. // cause the suspense to resolve immediately if that was the last dep.
  7659. if (parentSuspense &&
  7660. parentSuspense.pendingBranch &&
  7661. !parentSuspense.isUnmounted &&
  7662. instance.asyncDep &&
  7663. !instance.asyncResolved &&
  7664. instance.suspenseId === parentSuspense.pendingId) {
  7665. parentSuspense.deps--;
  7666. if (parentSuspense.deps === 0) {
  7667. parentSuspense.resolve();
  7668. }
  7669. }
  7670. {
  7671. devtoolsComponentRemoved(instance);
  7672. }
  7673. };
  7674. const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
  7675. for (let i = start; i < children.length; i++) {
  7676. unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
  7677. }
  7678. };
  7679. const getNextHostNode = vnode => {
  7680. if (vnode.shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
  7681. return getNextHostNode(vnode.component.subTree);
  7682. }
  7683. if (vnode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  7684. return vnode.suspense.next();
  7685. }
  7686. return hostNextSibling((vnode.anchor || vnode.el));
  7687. };
  7688. const render = (vnode, container, isSVG) => {
  7689. if (vnode == null) {
  7690. if (container._vnode) {
  7691. unmount(container._vnode, null, null, true);
  7692. }
  7693. }
  7694. else {
  7695. patch(container._vnode || null, vnode, container, null, null, null, isSVG);
  7696. }
  7697. flushPreFlushCbs();
  7698. flushPostFlushCbs();
  7699. container._vnode = vnode;
  7700. };
  7701. const internals = {
  7702. p: patch,
  7703. um: unmount,
  7704. m: move,
  7705. r: remove,
  7706. mt: mountComponent,
  7707. mc: mountChildren,
  7708. pc: patchChildren,
  7709. pbc: patchBlockChildren,
  7710. n: getNextHostNode,
  7711. o: options
  7712. };
  7713. let hydrate;
  7714. let hydrateNode;
  7715. if (createHydrationFns) {
  7716. [hydrate, hydrateNode] = createHydrationFns(internals);
  7717. }
  7718. return {
  7719. render,
  7720. hydrate,
  7721. createApp: createAppAPI(render, hydrate)
  7722. };
  7723. }
  7724. function toggleRecurse({ effect, update }, allowed) {
  7725. effect.allowRecurse = update.allowRecurse = allowed;
  7726. }
  7727. /**
  7728. * #1156
  7729. * When a component is HMR-enabled, we need to make sure that all static nodes
  7730. * inside a block also inherit the DOM element from the previous tree so that
  7731. * HMR updates (which are full updates) can retrieve the element for patching.
  7732. *
  7733. * #2080
  7734. * Inside keyed `template` fragment static children, if a fragment is moved,
  7735. * the children will always be moved. Therefore, in order to ensure correct move
  7736. * position, el should be inherited from previous nodes.
  7737. */
  7738. function traverseStaticChildren(n1, n2, shallow = false) {
  7739. const ch1 = n1.children;
  7740. const ch2 = n2.children;
  7741. if (isArray(ch1) && isArray(ch2)) {
  7742. for (let i = 0; i < ch1.length; i++) {
  7743. // this is only called in the optimized path so array children are
  7744. // guaranteed to be vnodes
  7745. const c1 = ch1[i];
  7746. let c2 = ch2[i];
  7747. if (c2.shapeFlag & 1 /* ShapeFlags.ELEMENT */ && !c2.dynamicChildren) {
  7748. if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* PatchFlags.HYDRATE_EVENTS */) {
  7749. c2 = ch2[i] = cloneIfMounted(ch2[i]);
  7750. c2.el = c1.el;
  7751. }
  7752. if (!shallow)
  7753. traverseStaticChildren(c1, c2);
  7754. }
  7755. // #6852 also inherit for text nodes
  7756. if (c2.type === Text) {
  7757. c2.el = c1.el;
  7758. }
  7759. // also inherit for comment nodes, but not placeholders (e.g. v-if which
  7760. // would have received .el during block patch)
  7761. if (c2.type === Comment && !c2.el) {
  7762. c2.el = c1.el;
  7763. }
  7764. }
  7765. }
  7766. }
  7767. // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
  7768. function getSequence(arr) {
  7769. const p = arr.slice();
  7770. const result = [0];
  7771. let i, j, u, v, c;
  7772. const len = arr.length;
  7773. for (i = 0; i < len; i++) {
  7774. const arrI = arr[i];
  7775. if (arrI !== 0) {
  7776. j = result[result.length - 1];
  7777. if (arr[j] < arrI) {
  7778. p[i] = j;
  7779. result.push(i);
  7780. continue;
  7781. }
  7782. u = 0;
  7783. v = result.length - 1;
  7784. while (u < v) {
  7785. c = (u + v) >> 1;
  7786. if (arr[result[c]] < arrI) {
  7787. u = c + 1;
  7788. }
  7789. else {
  7790. v = c;
  7791. }
  7792. }
  7793. if (arrI < arr[result[u]]) {
  7794. if (u > 0) {
  7795. p[i] = result[u - 1];
  7796. }
  7797. result[u] = i;
  7798. }
  7799. }
  7800. }
  7801. u = result.length;
  7802. v = result[u - 1];
  7803. while (u-- > 0) {
  7804. result[u] = v;
  7805. v = p[v];
  7806. }
  7807. return result;
  7808. }
  7809. const isTeleport = (type) => type.__isTeleport;
  7810. const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
  7811. const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
  7812. const resolveTarget = (props, select) => {
  7813. const targetSelector = props && props.to;
  7814. if (isString(targetSelector)) {
  7815. if (!select) {
  7816. warn$1(`Current renderer does not support string target for Teleports. ` +
  7817. `(missing querySelector renderer option)`);
  7818. return null;
  7819. }
  7820. else {
  7821. const target = select(targetSelector);
  7822. if (!target) {
  7823. warn$1(`Failed to locate Teleport target with selector "${targetSelector}". ` +
  7824. `Note the target element must exist before the component is mounted - ` +
  7825. `i.e. the target cannot be rendered by the component itself, and ` +
  7826. `ideally should be outside of the entire Vue component tree.`);
  7827. }
  7828. return target;
  7829. }
  7830. }
  7831. else {
  7832. if (!targetSelector && !isTeleportDisabled(props)) {
  7833. warn$1(`Invalid Teleport target: ${targetSelector}`);
  7834. }
  7835. return targetSelector;
  7836. }
  7837. };
  7838. const TeleportImpl = {
  7839. __isTeleport: true,
  7840. process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals) {
  7841. const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
  7842. const disabled = isTeleportDisabled(n2.props);
  7843. let { shapeFlag, children, dynamicChildren } = n2;
  7844. // #3302
  7845. // HMR updated, force full diff
  7846. if (isHmrUpdating) {
  7847. optimized = false;
  7848. dynamicChildren = null;
  7849. }
  7850. if (n1 == null) {
  7851. // insert anchors in the main view
  7852. const placeholder = (n2.el = createComment('teleport start')
  7853. );
  7854. const mainAnchor = (n2.anchor = createComment('teleport end')
  7855. );
  7856. insert(placeholder, container, anchor);
  7857. insert(mainAnchor, container, anchor);
  7858. const target = (n2.target = resolveTarget(n2.props, querySelector));
  7859. const targetAnchor = (n2.targetAnchor = createText(''));
  7860. if (target) {
  7861. insert(targetAnchor, target);
  7862. // #2652 we could be teleporting from a non-SVG tree into an SVG tree
  7863. isSVG = isSVG || isTargetSVG(target);
  7864. }
  7865. else if (!disabled) {
  7866. warn$1('Invalid Teleport target on mount:', target, `(${typeof target})`);
  7867. }
  7868. const mount = (container, anchor) => {
  7869. // Teleport *always* has Array children. This is enforced in both the
  7870. // compiler and vnode children normalization.
  7871. if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  7872. mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7873. }
  7874. };
  7875. if (disabled) {
  7876. mount(container, mainAnchor);
  7877. }
  7878. else if (target) {
  7879. mount(target, targetAnchor);
  7880. }
  7881. }
  7882. else {
  7883. // update content
  7884. n2.el = n1.el;
  7885. const mainAnchor = (n2.anchor = n1.anchor);
  7886. const target = (n2.target = n1.target);
  7887. const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
  7888. const wasDisabled = isTeleportDisabled(n1.props);
  7889. const currentContainer = wasDisabled ? container : target;
  7890. const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
  7891. isSVG = isSVG || isTargetSVG(target);
  7892. if (dynamicChildren) {
  7893. // fast path when the teleport happens to be a block root
  7894. patchBlockChildren(n1.dynamicChildren, dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG, slotScopeIds);
  7895. // even in block tree mode we need to make sure all root-level nodes
  7896. // in the teleport inherit previous DOM references so that they can
  7897. // be moved in future patches.
  7898. traverseStaticChildren(n1, n2, true);
  7899. }
  7900. else if (!optimized) {
  7901. patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, false);
  7902. }
  7903. if (disabled) {
  7904. if (!wasDisabled) {
  7905. // enabled -> disabled
  7906. // move into main container
  7907. moveTeleport(n2, container, mainAnchor, internals, 1 /* TeleportMoveTypes.TOGGLE */);
  7908. }
  7909. }
  7910. else {
  7911. // target changed
  7912. if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
  7913. const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
  7914. if (nextTarget) {
  7915. moveTeleport(n2, nextTarget, null, internals, 0 /* TeleportMoveTypes.TARGET_CHANGE */);
  7916. }
  7917. else {
  7918. warn$1('Invalid Teleport target on update:', target, `(${typeof target})`);
  7919. }
  7920. }
  7921. else if (wasDisabled) {
  7922. // disabled -> enabled
  7923. // move into teleport target
  7924. moveTeleport(n2, target, targetAnchor, internals, 1 /* TeleportMoveTypes.TOGGLE */);
  7925. }
  7926. }
  7927. }
  7928. updateCssVars(n2);
  7929. },
  7930. remove(vnode, parentComponent, parentSuspense, optimized, { um: unmount, o: { remove: hostRemove } }, doRemove) {
  7931. const { shapeFlag, children, anchor, targetAnchor, target, props } = vnode;
  7932. if (target) {
  7933. hostRemove(targetAnchor);
  7934. }
  7935. // an unmounted teleport should always remove its children if not disabled
  7936. if (doRemove || !isTeleportDisabled(props)) {
  7937. hostRemove(anchor);
  7938. if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  7939. for (let i = 0; i < children.length; i++) {
  7940. const child = children[i];
  7941. unmount(child, parentComponent, parentSuspense, true, !!child.dynamicChildren);
  7942. }
  7943. }
  7944. }
  7945. },
  7946. move: moveTeleport,
  7947. hydrate: hydrateTeleport
  7948. };
  7949. function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* TeleportMoveTypes.REORDER */) {
  7950. // move target anchor if this is a target change.
  7951. if (moveType === 0 /* TeleportMoveTypes.TARGET_CHANGE */) {
  7952. insert(vnode.targetAnchor, container, parentAnchor);
  7953. }
  7954. const { el, anchor, shapeFlag, children, props } = vnode;
  7955. const isReorder = moveType === 2 /* TeleportMoveTypes.REORDER */;
  7956. // move main view anchor if this is a re-order.
  7957. if (isReorder) {
  7958. insert(el, container, parentAnchor);
  7959. }
  7960. // if this is a re-order and teleport is enabled (content is in target)
  7961. // do not move children. So the opposite is: only move children if this
  7962. // is not a reorder, or the teleport is disabled
  7963. if (!isReorder || isTeleportDisabled(props)) {
  7964. // Teleport has either Array children or no children.
  7965. if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  7966. for (let i = 0; i < children.length; i++) {
  7967. move(children[i], container, parentAnchor, 2 /* MoveType.REORDER */);
  7968. }
  7969. }
  7970. }
  7971. // move main view anchor if this is a re-order.
  7972. if (isReorder) {
  7973. insert(anchor, container, parentAnchor);
  7974. }
  7975. }
  7976. function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
  7977. const target = (vnode.target = resolveTarget(vnode.props, querySelector));
  7978. if (target) {
  7979. // if multiple teleports rendered to the same target element, we need to
  7980. // pick up from where the last teleport finished instead of the first node
  7981. const targetNode = target._lpa || target.firstChild;
  7982. if (vnode.shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  7983. if (isTeleportDisabled(vnode.props)) {
  7984. vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, slotScopeIds, optimized);
  7985. vnode.targetAnchor = targetNode;
  7986. }
  7987. else {
  7988. vnode.anchor = nextSibling(node);
  7989. // lookahead until we find the target anchor
  7990. // we cannot rely on return value of hydrateChildren() because there
  7991. // could be nested teleports
  7992. let targetAnchor = targetNode;
  7993. while (targetAnchor) {
  7994. targetAnchor = nextSibling(targetAnchor);
  7995. if (targetAnchor &&
  7996. targetAnchor.nodeType === 8 &&
  7997. targetAnchor.data === 'teleport anchor') {
  7998. vnode.targetAnchor = targetAnchor;
  7999. target._lpa =
  8000. vnode.targetAnchor && nextSibling(vnode.targetAnchor);
  8001. break;
  8002. }
  8003. }
  8004. hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
  8005. }
  8006. }
  8007. updateCssVars(vnode);
  8008. }
  8009. return vnode.anchor && nextSibling(vnode.anchor);
  8010. }
  8011. // Force-casted public typing for h and TSX props inference
  8012. const Teleport = TeleportImpl;
  8013. function updateCssVars(vnode) {
  8014. // presence of .ut method indicates owner component uses css vars.
  8015. // code path here can assume browser environment.
  8016. const ctx = vnode.ctx;
  8017. if (ctx && ctx.ut) {
  8018. let node = vnode.children[0].el;
  8019. while (node !== vnode.targetAnchor) {
  8020. if (node.nodeType === 1)
  8021. node.setAttribute('data-v-owner', ctx.uid);
  8022. node = node.nextSibling;
  8023. }
  8024. ctx.ut();
  8025. }
  8026. }
  8027. const Fragment = Symbol('Fragment' );
  8028. const Text = Symbol('Text' );
  8029. const Comment = Symbol('Comment' );
  8030. const Static = Symbol('Static' );
  8031. // Since v-if and v-for are the two possible ways node structure can dynamically
  8032. // change, once we consider v-if branches and each v-for fragment a block, we
  8033. // can divide a template into nested blocks, and within each block the node
  8034. // structure would be stable. This allows us to skip most children diffing
  8035. // and only worry about the dynamic nodes (indicated by patch flags).
  8036. const blockStack = [];
  8037. let currentBlock = null;
  8038. /**
  8039. * Open a block.
  8040. * This must be called before `createBlock`. It cannot be part of `createBlock`
  8041. * because the children of the block are evaluated before `createBlock` itself
  8042. * is called. The generated code typically looks like this:
  8043. *
  8044. * ```js
  8045. * function render() {
  8046. * return (openBlock(),createBlock('div', null, [...]))
  8047. * }
  8048. * ```
  8049. * disableTracking is true when creating a v-for fragment block, since a v-for
  8050. * fragment always diffs its children.
  8051. *
  8052. * @private
  8053. */
  8054. function openBlock(disableTracking = false) {
  8055. blockStack.push((currentBlock = disableTracking ? null : []));
  8056. }
  8057. function closeBlock() {
  8058. blockStack.pop();
  8059. currentBlock = blockStack[blockStack.length - 1] || null;
  8060. }
  8061. // Whether we should be tracking dynamic child nodes inside a block.
  8062. // Only tracks when this value is > 0
  8063. // We are not using a simple boolean because this value may need to be
  8064. // incremented/decremented by nested usage of v-once (see below)
  8065. let isBlockTreeEnabled = 1;
  8066. /**
  8067. * Block tracking sometimes needs to be disabled, for example during the
  8068. * creation of a tree that needs to be cached by v-once. The compiler generates
  8069. * code like this:
  8070. *
  8071. * ``` js
  8072. * _cache[1] || (
  8073. * setBlockTracking(-1),
  8074. * _cache[1] = createVNode(...),
  8075. * setBlockTracking(1),
  8076. * _cache[1]
  8077. * )
  8078. * ```
  8079. *
  8080. * @private
  8081. */
  8082. function setBlockTracking(value) {
  8083. isBlockTreeEnabled += value;
  8084. }
  8085. function setupBlock(vnode) {
  8086. // save current block children on the block vnode
  8087. vnode.dynamicChildren =
  8088. isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
  8089. // close block
  8090. closeBlock();
  8091. // a block is always going to be patched, so track it as a child of its
  8092. // parent block
  8093. if (isBlockTreeEnabled > 0 && currentBlock) {
  8094. currentBlock.push(vnode);
  8095. }
  8096. return vnode;
  8097. }
  8098. /**
  8099. * @private
  8100. */
  8101. function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {
  8102. return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true /* isBlock */));
  8103. }
  8104. /**
  8105. * Create a block root vnode. Takes the same exact arguments as `createVNode`.
  8106. * A block root keeps track of dynamic nodes within the block in the
  8107. * `dynamicChildren` array.
  8108. *
  8109. * @private
  8110. */
  8111. function createBlock(type, props, children, patchFlag, dynamicProps) {
  8112. return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */));
  8113. }
  8114. function isVNode(value) {
  8115. return value ? value.__v_isVNode === true : false;
  8116. }
  8117. function isSameVNodeType(n1, n2) {
  8118. if (n2.shapeFlag & 6 /* ShapeFlags.COMPONENT */ &&
  8119. hmrDirtyComponents.has(n2.type)) {
  8120. // #7042, ensure the vnode being unmounted during HMR
  8121. // bitwise operations to remove keep alive flags
  8122. n1.shapeFlag &= ~256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */;
  8123. n2.shapeFlag &= ~512 /* ShapeFlags.COMPONENT_KEPT_ALIVE */;
  8124. // HMR only: if the component has been hot-updated, force a reload.
  8125. return false;
  8126. }
  8127. return n1.type === n2.type && n1.key === n2.key;
  8128. }
  8129. let vnodeArgsTransformer;
  8130. /**
  8131. * Internal API for registering an arguments transform for createVNode
  8132. * used for creating stubs in the test-utils
  8133. * It is *internal* but needs to be exposed for test-utils to pick up proper
  8134. * typings
  8135. */
  8136. function transformVNodeArgs(transformer) {
  8137. vnodeArgsTransformer = transformer;
  8138. }
  8139. const createVNodeWithArgsTransform = (...args) => {
  8140. return _createVNode(...(vnodeArgsTransformer
  8141. ? vnodeArgsTransformer(args, currentRenderingInstance)
  8142. : args));
  8143. };
  8144. const InternalObjectKey = `__vInternal`;
  8145. const normalizeKey = ({ key }) => key != null ? key : null;
  8146. const normalizeRef = ({ ref, ref_key, ref_for }) => {
  8147. return (ref != null
  8148. ? isString(ref) || isRef(ref) || isFunction(ref)
  8149. ? { i: currentRenderingInstance, r: ref, k: ref_key, f: !!ref_for }
  8150. : ref
  8151. : null);
  8152. };
  8153. function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1 /* ShapeFlags.ELEMENT */, isBlockNode = false, needFullChildrenNormalization = false) {
  8154. const vnode = {
  8155. __v_isVNode: true,
  8156. __v_skip: true,
  8157. type,
  8158. props,
  8159. key: props && normalizeKey(props),
  8160. ref: props && normalizeRef(props),
  8161. scopeId: currentScopeId,
  8162. slotScopeIds: null,
  8163. children,
  8164. component: null,
  8165. suspense: null,
  8166. ssContent: null,
  8167. ssFallback: null,
  8168. dirs: null,
  8169. transition: null,
  8170. el: null,
  8171. anchor: null,
  8172. target: null,
  8173. targetAnchor: null,
  8174. staticCount: 0,
  8175. shapeFlag,
  8176. patchFlag,
  8177. dynamicProps,
  8178. dynamicChildren: null,
  8179. appContext: null,
  8180. ctx: currentRenderingInstance
  8181. };
  8182. if (needFullChildrenNormalization) {
  8183. normalizeChildren(vnode, children);
  8184. // normalize suspense children
  8185. if (shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  8186. type.normalize(vnode);
  8187. }
  8188. }
  8189. else if (children) {
  8190. // compiled element vnode - if children is passed, only possible types are
  8191. // string or Array.
  8192. vnode.shapeFlag |= isString(children)
  8193. ? 8 /* ShapeFlags.TEXT_CHILDREN */
  8194. : 16 /* ShapeFlags.ARRAY_CHILDREN */;
  8195. }
  8196. // validate key
  8197. if (vnode.key !== vnode.key) {
  8198. warn$1(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
  8199. }
  8200. // track vnode for block tree
  8201. if (isBlockTreeEnabled > 0 &&
  8202. // avoid a block node from tracking itself
  8203. !isBlockNode &&
  8204. // has current parent block
  8205. currentBlock &&
  8206. // presence of a patch flag indicates this node needs patching on updates.
  8207. // component nodes also should always be patched, because even if the
  8208. // component doesn't need to update, it needs to persist the instance on to
  8209. // the next vnode so that it can be properly unmounted later.
  8210. (vnode.patchFlag > 0 || shapeFlag & 6 /* ShapeFlags.COMPONENT */) &&
  8211. // the EVENTS flag is only for hydration and if it is the only flag, the
  8212. // vnode should not be considered dynamic due to handler caching.
  8213. vnode.patchFlag !== 32 /* PatchFlags.HYDRATE_EVENTS */) {
  8214. currentBlock.push(vnode);
  8215. }
  8216. return vnode;
  8217. }
  8218. const createVNode = (createVNodeWithArgsTransform );
  8219. function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
  8220. if (!type || type === NULL_DYNAMIC_COMPONENT) {
  8221. if (!type) {
  8222. warn$1(`Invalid vnode type when creating vnode: ${type}.`);
  8223. }
  8224. type = Comment;
  8225. }
  8226. if (isVNode(type)) {
  8227. // createVNode receiving an existing vnode. This happens in cases like
  8228. // <component :is="vnode"/>
  8229. // #2078 make sure to merge refs during the clone instead of overwriting it
  8230. const cloned = cloneVNode(type, props, true /* mergeRef: true */);
  8231. if (children) {
  8232. normalizeChildren(cloned, children);
  8233. }
  8234. if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock) {
  8235. if (cloned.shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
  8236. currentBlock[currentBlock.indexOf(type)] = cloned;
  8237. }
  8238. else {
  8239. currentBlock.push(cloned);
  8240. }
  8241. }
  8242. cloned.patchFlag |= -2 /* PatchFlags.BAIL */;
  8243. return cloned;
  8244. }
  8245. // class component normalization.
  8246. if (isClassComponent(type)) {
  8247. type = type.__vccOpts;
  8248. }
  8249. // class & style normalization.
  8250. if (props) {
  8251. // for reactive or proxy objects, we need to clone it to enable mutation.
  8252. props = guardReactiveProps(props);
  8253. let { class: klass, style } = props;
  8254. if (klass && !isString(klass)) {
  8255. props.class = normalizeClass(klass);
  8256. }
  8257. if (isObject(style)) {
  8258. // reactive state objects need to be cloned since they are likely to be
  8259. // mutated
  8260. if (isProxy(style) && !isArray(style)) {
  8261. style = extend({}, style);
  8262. }
  8263. props.style = normalizeStyle(style);
  8264. }
  8265. }
  8266. // encode the vnode type information into a bitmap
  8267. const shapeFlag = isString(type)
  8268. ? 1 /* ShapeFlags.ELEMENT */
  8269. : isSuspense(type)
  8270. ? 128 /* ShapeFlags.SUSPENSE */
  8271. : isTeleport(type)
  8272. ? 64 /* ShapeFlags.TELEPORT */
  8273. : isObject(type)
  8274. ? 4 /* ShapeFlags.STATEFUL_COMPONENT */
  8275. : isFunction(type)
  8276. ? 2 /* ShapeFlags.FUNCTIONAL_COMPONENT */
  8277. : 0;
  8278. if (shapeFlag & 4 /* ShapeFlags.STATEFUL_COMPONENT */ && isProxy(type)) {
  8279. type = toRaw(type);
  8280. warn$1(`Vue received a Component which was made a reactive object. This can ` +
  8281. `lead to unnecessary performance overhead, and should be avoided by ` +
  8282. `marking the component with \`markRaw\` or using \`shallowRef\` ` +
  8283. `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
  8284. }
  8285. return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true);
  8286. }
  8287. function guardReactiveProps(props) {
  8288. if (!props)
  8289. return null;
  8290. return isProxy(props) || InternalObjectKey in props
  8291. ? extend({}, props)
  8292. : props;
  8293. }
  8294. function cloneVNode(vnode, extraProps, mergeRef = false) {
  8295. // This is intentionally NOT using spread or extend to avoid the runtime
  8296. // key enumeration cost.
  8297. const { props, ref, patchFlag, children } = vnode;
  8298. const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
  8299. const cloned = {
  8300. __v_isVNode: true,
  8301. __v_skip: true,
  8302. type: vnode.type,
  8303. props: mergedProps,
  8304. key: mergedProps && normalizeKey(mergedProps),
  8305. ref: extraProps && extraProps.ref
  8306. ? // #2078 in the case of <component :is="vnode" ref="extra"/>
  8307. // if the vnode itself already has a ref, cloneVNode will need to merge
  8308. // the refs so the single vnode can be set on multiple refs
  8309. mergeRef && ref
  8310. ? isArray(ref)
  8311. ? ref.concat(normalizeRef(extraProps))
  8312. : [ref, normalizeRef(extraProps)]
  8313. : normalizeRef(extraProps)
  8314. : ref,
  8315. scopeId: vnode.scopeId,
  8316. slotScopeIds: vnode.slotScopeIds,
  8317. children: patchFlag === -1 /* PatchFlags.HOISTED */ && isArray(children)
  8318. ? children.map(deepCloneVNode)
  8319. : children,
  8320. target: vnode.target,
  8321. targetAnchor: vnode.targetAnchor,
  8322. staticCount: vnode.staticCount,
  8323. shapeFlag: vnode.shapeFlag,
  8324. // if the vnode is cloned with extra props, we can no longer assume its
  8325. // existing patch flag to be reliable and need to add the FULL_PROPS flag.
  8326. // note: preserve flag for fragments since they use the flag for children
  8327. // fast paths only.
  8328. patchFlag: extraProps && vnode.type !== Fragment
  8329. ? patchFlag === -1 // hoisted node
  8330. ? 16 /* PatchFlags.FULL_PROPS */
  8331. : patchFlag | 16 /* PatchFlags.FULL_PROPS */
  8332. : patchFlag,
  8333. dynamicProps: vnode.dynamicProps,
  8334. dynamicChildren: vnode.dynamicChildren,
  8335. appContext: vnode.appContext,
  8336. dirs: vnode.dirs,
  8337. transition: vnode.transition,
  8338. // These should technically only be non-null on mounted VNodes. However,
  8339. // they *should* be copied for kept-alive vnodes. So we just always copy
  8340. // them since them being non-null during a mount doesn't affect the logic as
  8341. // they will simply be overwritten.
  8342. component: vnode.component,
  8343. suspense: vnode.suspense,
  8344. ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
  8345. ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
  8346. el: vnode.el,
  8347. anchor: vnode.anchor,
  8348. ctx: vnode.ctx
  8349. };
  8350. return cloned;
  8351. }
  8352. /**
  8353. * Dev only, for HMR of hoisted vnodes reused in v-for
  8354. * https://github.com/vitejs/vite/issues/2022
  8355. */
  8356. function deepCloneVNode(vnode) {
  8357. const cloned = cloneVNode(vnode);
  8358. if (isArray(vnode.children)) {
  8359. cloned.children = vnode.children.map(deepCloneVNode);
  8360. }
  8361. return cloned;
  8362. }
  8363. /**
  8364. * @private
  8365. */
  8366. function createTextVNode(text = ' ', flag = 0) {
  8367. return createVNode(Text, null, text, flag);
  8368. }
  8369. /**
  8370. * @private
  8371. */
  8372. function createStaticVNode(content, numberOfNodes) {
  8373. // A static vnode can contain multiple stringified elements, and the number
  8374. // of elements is necessary for hydration.
  8375. const vnode = createVNode(Static, null, content);
  8376. vnode.staticCount = numberOfNodes;
  8377. return vnode;
  8378. }
  8379. /**
  8380. * @private
  8381. */
  8382. function createCommentVNode(text = '',
  8383. // when used as the v-else branch, the comment node must be created as a
  8384. // block to ensure correct updates.
  8385. asBlock = false) {
  8386. return asBlock
  8387. ? (openBlock(), createBlock(Comment, null, text))
  8388. : createVNode(Comment, null, text);
  8389. }
  8390. function normalizeVNode(child) {
  8391. if (child == null || typeof child === 'boolean') {
  8392. // empty placeholder
  8393. return createVNode(Comment);
  8394. }
  8395. else if (isArray(child)) {
  8396. // fragment
  8397. return createVNode(Fragment, null,
  8398. // #3666, avoid reference pollution when reusing vnode
  8399. child.slice());
  8400. }
  8401. else if (typeof child === 'object') {
  8402. // already vnode, this should be the most common since compiled templates
  8403. // always produce all-vnode children arrays
  8404. return cloneIfMounted(child);
  8405. }
  8406. else {
  8407. // strings and numbers
  8408. return createVNode(Text, null, String(child));
  8409. }
  8410. }
  8411. // optimized normalization for template-compiled render fns
  8412. function cloneIfMounted(child) {
  8413. return (child.el === null && child.patchFlag !== -1 /* PatchFlags.HOISTED */) ||
  8414. child.memo
  8415. ? child
  8416. : cloneVNode(child);
  8417. }
  8418. function normalizeChildren(vnode, children) {
  8419. let type = 0;
  8420. const { shapeFlag } = vnode;
  8421. if (children == null) {
  8422. children = null;
  8423. }
  8424. else if (isArray(children)) {
  8425. type = 16 /* ShapeFlags.ARRAY_CHILDREN */;
  8426. }
  8427. else if (typeof children === 'object') {
  8428. if (shapeFlag & (1 /* ShapeFlags.ELEMENT */ | 64 /* ShapeFlags.TELEPORT */)) {
  8429. // Normalize slot to plain children for plain element and Teleport
  8430. const slot = children.default;
  8431. if (slot) {
  8432. // _c marker is added by withCtx() indicating this is a compiled slot
  8433. slot._c && (slot._d = false);
  8434. normalizeChildren(vnode, slot());
  8435. slot._c && (slot._d = true);
  8436. }
  8437. return;
  8438. }
  8439. else {
  8440. type = 32 /* ShapeFlags.SLOTS_CHILDREN */;
  8441. const slotFlag = children._;
  8442. if (!slotFlag && !(InternalObjectKey in children)) {
  8443. children._ctx = currentRenderingInstance;
  8444. }
  8445. else if (slotFlag === 3 /* SlotFlags.FORWARDED */ && currentRenderingInstance) {
  8446. // a child component receives forwarded slots from the parent.
  8447. // its slot type is determined by its parent's slot type.
  8448. if (currentRenderingInstance.slots._ === 1 /* SlotFlags.STABLE */) {
  8449. children._ = 1 /* SlotFlags.STABLE */;
  8450. }
  8451. else {
  8452. children._ = 2 /* SlotFlags.DYNAMIC */;
  8453. vnode.patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  8454. }
  8455. }
  8456. }
  8457. }
  8458. else if (isFunction(children)) {
  8459. children = { default: children, _ctx: currentRenderingInstance };
  8460. type = 32 /* ShapeFlags.SLOTS_CHILDREN */;
  8461. }
  8462. else {
  8463. children = String(children);
  8464. // force teleport children to array so it can be moved around
  8465. if (shapeFlag & 64 /* ShapeFlags.TELEPORT */) {
  8466. type = 16 /* ShapeFlags.ARRAY_CHILDREN */;
  8467. children = [createTextVNode(children)];
  8468. }
  8469. else {
  8470. type = 8 /* ShapeFlags.TEXT_CHILDREN */;
  8471. }
  8472. }
  8473. vnode.children = children;
  8474. vnode.shapeFlag |= type;
  8475. }
  8476. function mergeProps(...args) {
  8477. const ret = {};
  8478. for (let i = 0; i < args.length; i++) {
  8479. const toMerge = args[i];
  8480. for (const key in toMerge) {
  8481. if (key === 'class') {
  8482. if (ret.class !== toMerge.class) {
  8483. ret.class = normalizeClass([ret.class, toMerge.class]);
  8484. }
  8485. }
  8486. else if (key === 'style') {
  8487. ret.style = normalizeStyle([ret.style, toMerge.style]);
  8488. }
  8489. else if (isOn(key)) {
  8490. const existing = ret[key];
  8491. const incoming = toMerge[key];
  8492. if (incoming &&
  8493. existing !== incoming &&
  8494. !(isArray(existing) && existing.includes(incoming))) {
  8495. ret[key] = existing
  8496. ? [].concat(existing, incoming)
  8497. : incoming;
  8498. }
  8499. }
  8500. else if (key !== '') {
  8501. ret[key] = toMerge[key];
  8502. }
  8503. }
  8504. }
  8505. return ret;
  8506. }
  8507. function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
  8508. callWithAsyncErrorHandling(hook, instance, 7 /* ErrorCodes.VNODE_HOOK */, [
  8509. vnode,
  8510. prevVNode
  8511. ]);
  8512. }
  8513. const emptyAppContext = createAppContext();
  8514. let uid$1 = 0;
  8515. function createComponentInstance(vnode, parent, suspense) {
  8516. const type = vnode.type;
  8517. // inherit parent app context - or - if root, adopt from root vnode
  8518. const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
  8519. const instance = {
  8520. uid: uid$1++,
  8521. vnode,
  8522. type,
  8523. parent,
  8524. appContext,
  8525. root: null,
  8526. next: null,
  8527. subTree: null,
  8528. effect: null,
  8529. update: null,
  8530. scope: new EffectScope(true /* detached */),
  8531. render: null,
  8532. proxy: null,
  8533. exposed: null,
  8534. exposeProxy: null,
  8535. withProxy: null,
  8536. provides: parent ? parent.provides : Object.create(appContext.provides),
  8537. accessCache: null,
  8538. renderCache: [],
  8539. // local resolved assets
  8540. components: null,
  8541. directives: null,
  8542. // resolved props and emits options
  8543. propsOptions: normalizePropsOptions(type, appContext),
  8544. emitsOptions: normalizeEmitsOptions(type, appContext),
  8545. // emit
  8546. emit: null,
  8547. emitted: null,
  8548. // props default value
  8549. propsDefaults: EMPTY_OBJ,
  8550. // inheritAttrs
  8551. inheritAttrs: type.inheritAttrs,
  8552. // state
  8553. ctx: EMPTY_OBJ,
  8554. data: EMPTY_OBJ,
  8555. props: EMPTY_OBJ,
  8556. attrs: EMPTY_OBJ,
  8557. slots: EMPTY_OBJ,
  8558. refs: EMPTY_OBJ,
  8559. setupState: EMPTY_OBJ,
  8560. setupContext: null,
  8561. // suspense related
  8562. suspense,
  8563. suspenseId: suspense ? suspense.pendingId : 0,
  8564. asyncDep: null,
  8565. asyncResolved: false,
  8566. // lifecycle hooks
  8567. // not using enums here because it results in computed properties
  8568. isMounted: false,
  8569. isUnmounted: false,
  8570. isDeactivated: false,
  8571. bc: null,
  8572. c: null,
  8573. bm: null,
  8574. m: null,
  8575. bu: null,
  8576. u: null,
  8577. um: null,
  8578. bum: null,
  8579. da: null,
  8580. a: null,
  8581. rtg: null,
  8582. rtc: null,
  8583. ec: null,
  8584. sp: null
  8585. };
  8586. {
  8587. instance.ctx = createDevRenderContext(instance);
  8588. }
  8589. instance.root = parent ? parent.root : instance;
  8590. instance.emit = emit$1.bind(null, instance);
  8591. // apply custom element special handling
  8592. if (vnode.ce) {
  8593. vnode.ce(instance);
  8594. }
  8595. return instance;
  8596. }
  8597. let currentInstance = null;
  8598. const getCurrentInstance = () => currentInstance || currentRenderingInstance;
  8599. const setCurrentInstance = (instance) => {
  8600. currentInstance = instance;
  8601. instance.scope.on();
  8602. };
  8603. const unsetCurrentInstance = () => {
  8604. currentInstance && currentInstance.scope.off();
  8605. currentInstance = null;
  8606. };
  8607. const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
  8608. function validateComponentName(name, config) {
  8609. const appIsNativeTag = config.isNativeTag || NO;
  8610. if (isBuiltInTag(name) || appIsNativeTag(name)) {
  8611. warn$1('Do not use built-in or reserved HTML elements as component id: ' + name);
  8612. }
  8613. }
  8614. function isStatefulComponent(instance) {
  8615. return instance.vnode.shapeFlag & 4 /* ShapeFlags.STATEFUL_COMPONENT */;
  8616. }
  8617. let isInSSRComponentSetup = false;
  8618. function setupComponent(instance, isSSR = false) {
  8619. isInSSRComponentSetup = isSSR;
  8620. const { props, children } = instance.vnode;
  8621. const isStateful = isStatefulComponent(instance);
  8622. initProps(instance, props, isStateful, isSSR);
  8623. initSlots(instance, children);
  8624. const setupResult = isStateful
  8625. ? setupStatefulComponent(instance, isSSR)
  8626. : undefined;
  8627. isInSSRComponentSetup = false;
  8628. return setupResult;
  8629. }
  8630. function setupStatefulComponent(instance, isSSR) {
  8631. var _a;
  8632. const Component = instance.type;
  8633. {
  8634. if (Component.name) {
  8635. validateComponentName(Component.name, instance.appContext.config);
  8636. }
  8637. if (Component.components) {
  8638. const names = Object.keys(Component.components);
  8639. for (let i = 0; i < names.length; i++) {
  8640. validateComponentName(names[i], instance.appContext.config);
  8641. }
  8642. }
  8643. if (Component.directives) {
  8644. const names = Object.keys(Component.directives);
  8645. for (let i = 0; i < names.length; i++) {
  8646. validateDirectiveName(names[i]);
  8647. }
  8648. }
  8649. if (Component.compilerOptions && isRuntimeOnly()) {
  8650. warn$1(`"compilerOptions" is only supported when using a build of Vue that ` +
  8651. `includes the runtime compiler. Since you are using a runtime-only ` +
  8652. `build, the options should be passed via your build tool config instead.`);
  8653. }
  8654. }
  8655. // 0. create render proxy property access cache
  8656. instance.accessCache = Object.create(null);
  8657. // 1. create public instance / render proxy
  8658. // also mark it raw so it's never observed
  8659. instance.proxy = markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));
  8660. {
  8661. exposePropsOnRenderContext(instance);
  8662. }
  8663. // 2. call setup()
  8664. const { setup } = Component;
  8665. if (setup) {
  8666. const setupContext = (instance.setupContext =
  8667. setup.length > 1 ? createSetupContext(instance) : null);
  8668. setCurrentInstance(instance);
  8669. pauseTracking();
  8670. const setupResult = callWithErrorHandling(setup, instance, 0 /* ErrorCodes.SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
  8671. resetTracking();
  8672. unsetCurrentInstance();
  8673. if (isPromise(setupResult)) {
  8674. setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
  8675. if (isSSR) {
  8676. // return the promise so server-renderer can wait on it
  8677. return setupResult
  8678. .then((resolvedResult) => {
  8679. handleSetupResult(instance, resolvedResult, isSSR);
  8680. })
  8681. .catch(e => {
  8682. handleError(e, instance, 0 /* ErrorCodes.SETUP_FUNCTION */);
  8683. });
  8684. }
  8685. else {
  8686. // async setup returned Promise.
  8687. // bail here and wait for re-entry.
  8688. instance.asyncDep = setupResult;
  8689. if (!instance.suspense) {
  8690. const name = (_a = Component.name) !== null && _a !== void 0 ? _a : 'Anonymous';
  8691. warn$1(`Component <${name}>: setup function returned a promise, but no ` +
  8692. `<Suspense> boundary was found in the parent component tree. ` +
  8693. `A component with async setup() must be nested in a <Suspense> ` +
  8694. `in order to be rendered.`);
  8695. }
  8696. }
  8697. }
  8698. else {
  8699. handleSetupResult(instance, setupResult, isSSR);
  8700. }
  8701. }
  8702. else {
  8703. finishComponentSetup(instance, isSSR);
  8704. }
  8705. }
  8706. function handleSetupResult(instance, setupResult, isSSR) {
  8707. if (isFunction(setupResult)) {
  8708. // setup returned an inline render function
  8709. {
  8710. instance.render = setupResult;
  8711. }
  8712. }
  8713. else if (isObject(setupResult)) {
  8714. if (isVNode(setupResult)) {
  8715. warn$1(`setup() should not return VNodes directly - ` +
  8716. `return a render function instead.`);
  8717. }
  8718. // setup returned bindings.
  8719. // assuming a render function compiled from template is present.
  8720. {
  8721. instance.devtoolsRawSetupState = setupResult;
  8722. }
  8723. instance.setupState = proxyRefs(setupResult);
  8724. {
  8725. exposeSetupStateOnRenderContext(instance);
  8726. }
  8727. }
  8728. else if (setupResult !== undefined) {
  8729. warn$1(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
  8730. }
  8731. finishComponentSetup(instance, isSSR);
  8732. }
  8733. let compile;
  8734. let installWithProxy;
  8735. /**
  8736. * For runtime-dom to register the compiler.
  8737. * Note the exported method uses any to avoid d.ts relying on the compiler types.
  8738. */
  8739. function registerRuntimeCompiler(_compile) {
  8740. compile = _compile;
  8741. installWithProxy = i => {
  8742. if (i.render._rc) {
  8743. i.withProxy = new Proxy(i.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
  8744. }
  8745. };
  8746. }
  8747. // dev only
  8748. const isRuntimeOnly = () => !compile;
  8749. function finishComponentSetup(instance, isSSR, skipOptions) {
  8750. const Component = instance.type;
  8751. // template / render function normalization
  8752. // could be already set when returned from setup()
  8753. if (!instance.render) {
  8754. // only do on-the-fly compile if not in SSR - SSR on-the-fly compilation
  8755. // is done by server-renderer
  8756. if (!isSSR && compile && !Component.render) {
  8757. const template = Component.template ||
  8758. resolveMergedOptions(instance).template;
  8759. if (template) {
  8760. {
  8761. startMeasure(instance, `compile`);
  8762. }
  8763. const { isCustomElement, compilerOptions } = instance.appContext.config;
  8764. const { delimiters, compilerOptions: componentCompilerOptions } = Component;
  8765. const finalCompilerOptions = extend(extend({
  8766. isCustomElement,
  8767. delimiters
  8768. }, compilerOptions), componentCompilerOptions);
  8769. Component.render = compile(template, finalCompilerOptions);
  8770. {
  8771. endMeasure(instance, `compile`);
  8772. }
  8773. }
  8774. }
  8775. instance.render = (Component.render || NOOP);
  8776. // for runtime-compiled render functions using `with` blocks, the render
  8777. // proxy used needs a different `has` handler which is more performant and
  8778. // also only allows a whitelist of globals to fallthrough.
  8779. if (installWithProxy) {
  8780. installWithProxy(instance);
  8781. }
  8782. }
  8783. // support for 2.x options
  8784. {
  8785. setCurrentInstance(instance);
  8786. pauseTracking();
  8787. applyOptions(instance);
  8788. resetTracking();
  8789. unsetCurrentInstance();
  8790. }
  8791. // warn missing template/render
  8792. // the runtime compilation of template in SSR is done by server-render
  8793. if (!Component.render && instance.render === NOOP && !isSSR) {
  8794. /* istanbul ignore if */
  8795. if (!compile && Component.template) {
  8796. warn$1(`Component provided template option but ` +
  8797. `runtime compilation is not supported in this build of Vue.` +
  8798. (` Use "vue.esm-browser.js" instead.`
  8799. ) /* should not happen */);
  8800. }
  8801. else {
  8802. warn$1(`Component is missing template or render function.`);
  8803. }
  8804. }
  8805. }
  8806. function createAttrsProxy(instance) {
  8807. return new Proxy(instance.attrs, {
  8808. get(target, key) {
  8809. markAttrsAccessed();
  8810. track(instance, "get" /* TrackOpTypes.GET */, '$attrs');
  8811. return target[key];
  8812. },
  8813. set() {
  8814. warn$1(`setupContext.attrs is readonly.`);
  8815. return false;
  8816. },
  8817. deleteProperty() {
  8818. warn$1(`setupContext.attrs is readonly.`);
  8819. return false;
  8820. }
  8821. }
  8822. );
  8823. }
  8824. function createSetupContext(instance) {
  8825. const expose = exposed => {
  8826. if (instance.exposed) {
  8827. warn$1(`expose() should be called only once per setup().`);
  8828. }
  8829. instance.exposed = exposed || {};
  8830. };
  8831. let attrs;
  8832. {
  8833. // We use getters in dev in case libs like test-utils overwrite instance
  8834. // properties (overwrites should not be done in prod)
  8835. return Object.freeze({
  8836. get attrs() {
  8837. return attrs || (attrs = createAttrsProxy(instance));
  8838. },
  8839. get slots() {
  8840. return shallowReadonly(instance.slots);
  8841. },
  8842. get emit() {
  8843. return (event, ...args) => instance.emit(event, ...args);
  8844. },
  8845. expose
  8846. });
  8847. }
  8848. }
  8849. function getExposeProxy(instance) {
  8850. if (instance.exposed) {
  8851. return (instance.exposeProxy ||
  8852. (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
  8853. get(target, key) {
  8854. if (key in target) {
  8855. return target[key];
  8856. }
  8857. else if (key in publicPropertiesMap) {
  8858. return publicPropertiesMap[key](instance);
  8859. }
  8860. },
  8861. has(target, key) {
  8862. return key in target || key in publicPropertiesMap;
  8863. }
  8864. })));
  8865. }
  8866. }
  8867. const classifyRE = /(?:^|[-_])(\w)/g;
  8868. const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
  8869. function getComponentName(Component, includeInferred = true) {
  8870. return isFunction(Component)
  8871. ? Component.displayName || Component.name
  8872. : Component.name || (includeInferred && Component.__name);
  8873. }
  8874. /* istanbul ignore next */
  8875. function formatComponentName(instance, Component, isRoot = false) {
  8876. let name = getComponentName(Component);
  8877. if (!name && Component.__file) {
  8878. const match = Component.__file.match(/([^/\\]+)\.\w+$/);
  8879. if (match) {
  8880. name = match[1];
  8881. }
  8882. }
  8883. if (!name && instance && instance.parent) {
  8884. // try to infer the name based on reverse resolution
  8885. const inferFromRegistry = (registry) => {
  8886. for (const key in registry) {
  8887. if (registry[key] === Component) {
  8888. return key;
  8889. }
  8890. }
  8891. };
  8892. name =
  8893. inferFromRegistry(instance.components ||
  8894. instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
  8895. }
  8896. return name ? classify(name) : isRoot ? `App` : `Anonymous`;
  8897. }
  8898. function isClassComponent(value) {
  8899. return isFunction(value) && '__vccOpts' in value;
  8900. }
  8901. const computed$1 = ((getterOrOptions, debugOptions) => {
  8902. // @ts-ignore
  8903. return computed(getterOrOptions, debugOptions, isInSSRComponentSetup);
  8904. });
  8905. // dev only
  8906. const warnRuntimeUsage = (method) => warn$1(`${method}() is a compiler-hint helper that is only usable inside ` +
  8907. `<script setup> of a single file component. Its arguments should be ` +
  8908. `compiled away and passing it at runtime has no effect.`);
  8909. // implementation
  8910. function defineProps() {
  8911. {
  8912. warnRuntimeUsage(`defineProps`);
  8913. }
  8914. return null;
  8915. }
  8916. // implementation
  8917. function defineEmits() {
  8918. {
  8919. warnRuntimeUsage(`defineEmits`);
  8920. }
  8921. return null;
  8922. }
  8923. /**
  8924. * Vue `<script setup>` compiler macro for declaring a component's exposed
  8925. * instance properties when it is accessed by a parent component via template
  8926. * refs.
  8927. *
  8928. * `<script setup>` components are closed by default - i.e. variables inside
  8929. * the `<script setup>` scope is not exposed to parent unless explicitly exposed
  8930. * via `defineExpose`.
  8931. *
  8932. * This is only usable inside `<script setup>`, is compiled away in the
  8933. * output and should **not** be actually called at runtime.
  8934. */
  8935. function defineExpose(exposed) {
  8936. {
  8937. warnRuntimeUsage(`defineExpose`);
  8938. }
  8939. }
  8940. /**
  8941. * Vue `<script setup>` compiler macro for providing props default values when
  8942. * using type-based `defineProps` declaration.
  8943. *
  8944. * Example usage:
  8945. * ```ts
  8946. * withDefaults(defineProps<{
  8947. * size?: number
  8948. * labels?: string[]
  8949. * }>(), {
  8950. * size: 3,
  8951. * labels: () => ['default label']
  8952. * })
  8953. * ```
  8954. *
  8955. * This is only usable inside `<script setup>`, is compiled away in the output
  8956. * and should **not** be actually called at runtime.
  8957. */
  8958. function withDefaults(props, defaults) {
  8959. {
  8960. warnRuntimeUsage(`withDefaults`);
  8961. }
  8962. return null;
  8963. }
  8964. function useSlots() {
  8965. return getContext().slots;
  8966. }
  8967. function useAttrs() {
  8968. return getContext().attrs;
  8969. }
  8970. function getContext() {
  8971. const i = getCurrentInstance();
  8972. if (!i) {
  8973. warn$1(`useContext() called without active instance.`);
  8974. }
  8975. return i.setupContext || (i.setupContext = createSetupContext(i));
  8976. }
  8977. /**
  8978. * Runtime helper for merging default declarations. Imported by compiled code
  8979. * only.
  8980. * @internal
  8981. */
  8982. function mergeDefaults(raw, defaults) {
  8983. const props = isArray(raw)
  8984. ? raw.reduce((normalized, p) => ((normalized[p] = {}), normalized), {})
  8985. : raw;
  8986. for (const key in defaults) {
  8987. const opt = props[key];
  8988. if (opt) {
  8989. if (isArray(opt) || isFunction(opt)) {
  8990. props[key] = { type: opt, default: defaults[key] };
  8991. }
  8992. else {
  8993. opt.default = defaults[key];
  8994. }
  8995. }
  8996. else if (opt === null) {
  8997. props[key] = { default: defaults[key] };
  8998. }
  8999. else {
  9000. warn$1(`props default key "${key}" has no corresponding declaration.`);
  9001. }
  9002. }
  9003. return props;
  9004. }
  9005. /**
  9006. * Used to create a proxy for the rest element when destructuring props with
  9007. * defineProps().
  9008. * @internal
  9009. */
  9010. function createPropsRestProxy(props, excludedKeys) {
  9011. const ret = {};
  9012. for (const key in props) {
  9013. if (!excludedKeys.includes(key)) {
  9014. Object.defineProperty(ret, key, {
  9015. enumerable: true,
  9016. get: () => props[key]
  9017. });
  9018. }
  9019. }
  9020. return ret;
  9021. }
  9022. /**
  9023. * `<script setup>` helper for persisting the current instance context over
  9024. * async/await flows.
  9025. *
  9026. * `@vue/compiler-sfc` converts the following:
  9027. *
  9028. * ```ts
  9029. * const x = await foo()
  9030. * ```
  9031. *
  9032. * into:
  9033. *
  9034. * ```ts
  9035. * let __temp, __restore
  9036. * const x = (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
  9037. * ```
  9038. * @internal
  9039. */
  9040. function withAsyncContext(getAwaitable) {
  9041. const ctx = getCurrentInstance();
  9042. if (!ctx) {
  9043. warn$1(`withAsyncContext called without active current instance. ` +
  9044. `This is likely a bug.`);
  9045. }
  9046. let awaitable = getAwaitable();
  9047. unsetCurrentInstance();
  9048. if (isPromise(awaitable)) {
  9049. awaitable = awaitable.catch(e => {
  9050. setCurrentInstance(ctx);
  9051. throw e;
  9052. });
  9053. }
  9054. return [awaitable, () => setCurrentInstance(ctx)];
  9055. }
  9056. // Actual implementation
  9057. function h(type, propsOrChildren, children) {
  9058. const l = arguments.length;
  9059. if (l === 2) {
  9060. if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
  9061. // single vnode without props
  9062. if (isVNode(propsOrChildren)) {
  9063. return createVNode(type, null, [propsOrChildren]);
  9064. }
  9065. // props without children
  9066. return createVNode(type, propsOrChildren);
  9067. }
  9068. else {
  9069. // omit props
  9070. return createVNode(type, null, propsOrChildren);
  9071. }
  9072. }
  9073. else {
  9074. if (l > 3) {
  9075. children = Array.prototype.slice.call(arguments, 2);
  9076. }
  9077. else if (l === 3 && isVNode(children)) {
  9078. children = [children];
  9079. }
  9080. return createVNode(type, propsOrChildren, children);
  9081. }
  9082. }
  9083. const ssrContextKey = Symbol(`ssrContext` );
  9084. const useSSRContext = () => {
  9085. {
  9086. const ctx = inject(ssrContextKey);
  9087. if (!ctx) {
  9088. warn$1(`Server rendering context not provided. Make sure to only call ` +
  9089. `useSSRContext() conditionally in the server build.`);
  9090. }
  9091. return ctx;
  9092. }
  9093. };
  9094. function initCustomFormatter() {
  9095. /* eslint-disable no-restricted-globals */
  9096. if (typeof window === 'undefined') {
  9097. return;
  9098. }
  9099. const vueStyle = { style: 'color:#3ba776' };
  9100. const numberStyle = { style: 'color:#0b1bc9' };
  9101. const stringStyle = { style: 'color:#b62e24' };
  9102. const keywordStyle = { style: 'color:#9d288c' };
  9103. // custom formatter for Chrome
  9104. // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
  9105. const formatter = {
  9106. header(obj) {
  9107. // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
  9108. if (!isObject(obj)) {
  9109. return null;
  9110. }
  9111. if (obj.__isVue) {
  9112. return ['div', vueStyle, `VueInstance`];
  9113. }
  9114. else if (isRef(obj)) {
  9115. return [
  9116. 'div',
  9117. {},
  9118. ['span', vueStyle, genRefFlag(obj)],
  9119. '<',
  9120. formatValue(obj.value),
  9121. `>`
  9122. ];
  9123. }
  9124. else if (isReactive(obj)) {
  9125. return [
  9126. 'div',
  9127. {},
  9128. ['span', vueStyle, isShallow(obj) ? 'ShallowReactive' : 'Reactive'],
  9129. '<',
  9130. formatValue(obj),
  9131. `>${isReadonly(obj) ? ` (readonly)` : ``}`
  9132. ];
  9133. }
  9134. else if (isReadonly(obj)) {
  9135. return [
  9136. 'div',
  9137. {},
  9138. ['span', vueStyle, isShallow(obj) ? 'ShallowReadonly' : 'Readonly'],
  9139. '<',
  9140. formatValue(obj),
  9141. '>'
  9142. ];
  9143. }
  9144. return null;
  9145. },
  9146. hasBody(obj) {
  9147. return obj && obj.__isVue;
  9148. },
  9149. body(obj) {
  9150. if (obj && obj.__isVue) {
  9151. return [
  9152. 'div',
  9153. {},
  9154. ...formatInstance(obj.$)
  9155. ];
  9156. }
  9157. }
  9158. };
  9159. function formatInstance(instance) {
  9160. const blocks = [];
  9161. if (instance.type.props && instance.props) {
  9162. blocks.push(createInstanceBlock('props', toRaw(instance.props)));
  9163. }
  9164. if (instance.setupState !== EMPTY_OBJ) {
  9165. blocks.push(createInstanceBlock('setup', instance.setupState));
  9166. }
  9167. if (instance.data !== EMPTY_OBJ) {
  9168. blocks.push(createInstanceBlock('data', toRaw(instance.data)));
  9169. }
  9170. const computed = extractKeys(instance, 'computed');
  9171. if (computed) {
  9172. blocks.push(createInstanceBlock('computed', computed));
  9173. }
  9174. const injected = extractKeys(instance, 'inject');
  9175. if (injected) {
  9176. blocks.push(createInstanceBlock('injected', injected));
  9177. }
  9178. blocks.push([
  9179. 'div',
  9180. {},
  9181. [
  9182. 'span',
  9183. {
  9184. style: keywordStyle.style + ';opacity:0.66'
  9185. },
  9186. '$ (internal): '
  9187. ],
  9188. ['object', { object: instance }]
  9189. ]);
  9190. return blocks;
  9191. }
  9192. function createInstanceBlock(type, target) {
  9193. target = extend({}, target);
  9194. if (!Object.keys(target).length) {
  9195. return ['span', {}];
  9196. }
  9197. return [
  9198. 'div',
  9199. { style: 'line-height:1.25em;margin-bottom:0.6em' },
  9200. [
  9201. 'div',
  9202. {
  9203. style: 'color:#476582'
  9204. },
  9205. type
  9206. ],
  9207. [
  9208. 'div',
  9209. {
  9210. style: 'padding-left:1.25em'
  9211. },
  9212. ...Object.keys(target).map(key => {
  9213. return [
  9214. 'div',
  9215. {},
  9216. ['span', keywordStyle, key + ': '],
  9217. formatValue(target[key], false)
  9218. ];
  9219. })
  9220. ]
  9221. ];
  9222. }
  9223. function formatValue(v, asRaw = true) {
  9224. if (typeof v === 'number') {
  9225. return ['span', numberStyle, v];
  9226. }
  9227. else if (typeof v === 'string') {
  9228. return ['span', stringStyle, JSON.stringify(v)];
  9229. }
  9230. else if (typeof v === 'boolean') {
  9231. return ['span', keywordStyle, v];
  9232. }
  9233. else if (isObject(v)) {
  9234. return ['object', { object: asRaw ? toRaw(v) : v }];
  9235. }
  9236. else {
  9237. return ['span', stringStyle, String(v)];
  9238. }
  9239. }
  9240. function extractKeys(instance, type) {
  9241. const Comp = instance.type;
  9242. if (isFunction(Comp)) {
  9243. return;
  9244. }
  9245. const extracted = {};
  9246. for (const key in instance.ctx) {
  9247. if (isKeyOfType(Comp, key, type)) {
  9248. extracted[key] = instance.ctx[key];
  9249. }
  9250. }
  9251. return extracted;
  9252. }
  9253. function isKeyOfType(Comp, key, type) {
  9254. const opts = Comp[type];
  9255. if ((isArray(opts) && opts.includes(key)) ||
  9256. (isObject(opts) && key in opts)) {
  9257. return true;
  9258. }
  9259. if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
  9260. return true;
  9261. }
  9262. if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
  9263. return true;
  9264. }
  9265. }
  9266. function genRefFlag(v) {
  9267. if (isShallow(v)) {
  9268. return `ShallowRef`;
  9269. }
  9270. if (v.effect) {
  9271. return `ComputedRef`;
  9272. }
  9273. return `Ref`;
  9274. }
  9275. if (window.devtoolsFormatters) {
  9276. window.devtoolsFormatters.push(formatter);
  9277. }
  9278. else {
  9279. window.devtoolsFormatters = [formatter];
  9280. }
  9281. }
  9282. function withMemo(memo, render, cache, index) {
  9283. const cached = cache[index];
  9284. if (cached && isMemoSame(cached, memo)) {
  9285. return cached;
  9286. }
  9287. const ret = render();
  9288. // shallow clone
  9289. ret.memo = memo.slice();
  9290. return (cache[index] = ret);
  9291. }
  9292. function isMemoSame(cached, memo) {
  9293. const prev = cached.memo;
  9294. if (prev.length != memo.length) {
  9295. return false;
  9296. }
  9297. for (let i = 0; i < prev.length; i++) {
  9298. if (hasChanged(prev[i], memo[i])) {
  9299. return false;
  9300. }
  9301. }
  9302. // make sure to let parent block track it when returning cached
  9303. if (isBlockTreeEnabled > 0 && currentBlock) {
  9304. currentBlock.push(cached);
  9305. }
  9306. return true;
  9307. }
  9308. // Core API ------------------------------------------------------------------
  9309. const version = "3.2.45";
  9310. /**
  9311. * SSR utils for \@vue/server-renderer. Only exposed in ssr-possible builds.
  9312. * @internal
  9313. */
  9314. const ssrUtils = (null);
  9315. /**
  9316. * @internal only exposed in compat builds
  9317. */
  9318. const resolveFilter = null;
  9319. /**
  9320. * @internal only exposed in compat builds.
  9321. */
  9322. const compatUtils = (null);
  9323. const svgNS = 'http://www.w3.org/2000/svg';
  9324. const doc = (typeof document !== 'undefined' ? document : null);
  9325. const templateContainer = doc && /*#__PURE__*/ doc.createElement('template');
  9326. const nodeOps = {
  9327. insert: (child, parent, anchor) => {
  9328. parent.insertBefore(child, anchor || null);
  9329. },
  9330. remove: child => {
  9331. const parent = child.parentNode;
  9332. if (parent) {
  9333. parent.removeChild(child);
  9334. }
  9335. },
  9336. createElement: (tag, isSVG, is, props) => {
  9337. const el = isSVG
  9338. ? doc.createElementNS(svgNS, tag)
  9339. : doc.createElement(tag, is ? { is } : undefined);
  9340. if (tag === 'select' && props && props.multiple != null) {
  9341. el.setAttribute('multiple', props.multiple);
  9342. }
  9343. return el;
  9344. },
  9345. createText: text => doc.createTextNode(text),
  9346. createComment: text => doc.createComment(text),
  9347. setText: (node, text) => {
  9348. node.nodeValue = text;
  9349. },
  9350. setElementText: (el, text) => {
  9351. el.textContent = text;
  9352. },
  9353. parentNode: node => node.parentNode,
  9354. nextSibling: node => node.nextSibling,
  9355. querySelector: selector => doc.querySelector(selector),
  9356. setScopeId(el, id) {
  9357. el.setAttribute(id, '');
  9358. },
  9359. // __UNSAFE__
  9360. // Reason: innerHTML.
  9361. // Static content here can only come from compiled templates.
  9362. // As long as the user only uses trusted templates, this is safe.
  9363. insertStaticContent(content, parent, anchor, isSVG, start, end) {
  9364. // <parent> before | first ... last | anchor </parent>
  9365. const before = anchor ? anchor.previousSibling : parent.lastChild;
  9366. // #5308 can only take cached path if:
  9367. // - has a single root node
  9368. // - nextSibling info is still available
  9369. if (start && (start === end || start.nextSibling)) {
  9370. // cached
  9371. while (true) {
  9372. parent.insertBefore(start.cloneNode(true), anchor);
  9373. if (start === end || !(start = start.nextSibling))
  9374. break;
  9375. }
  9376. }
  9377. else {
  9378. // fresh insert
  9379. templateContainer.innerHTML = isSVG ? `<svg>${content}</svg>` : content;
  9380. const template = templateContainer.content;
  9381. if (isSVG) {
  9382. // remove outer svg wrapper
  9383. const wrapper = template.firstChild;
  9384. while (wrapper.firstChild) {
  9385. template.appendChild(wrapper.firstChild);
  9386. }
  9387. template.removeChild(wrapper);
  9388. }
  9389. parent.insertBefore(template, anchor);
  9390. }
  9391. return [
  9392. // first
  9393. before ? before.nextSibling : parent.firstChild,
  9394. // last
  9395. anchor ? anchor.previousSibling : parent.lastChild
  9396. ];
  9397. }
  9398. };
  9399. // compiler should normalize class + :class bindings on the same element
  9400. // into a single binding ['staticClass', dynamic]
  9401. function patchClass(el, value, isSVG) {
  9402. // directly setting className should be faster than setAttribute in theory
  9403. // if this is an element during a transition, take the temporary transition
  9404. // classes into account.
  9405. const transitionClasses = el._vtc;
  9406. if (transitionClasses) {
  9407. value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(' ');
  9408. }
  9409. if (value == null) {
  9410. el.removeAttribute('class');
  9411. }
  9412. else if (isSVG) {
  9413. el.setAttribute('class', value);
  9414. }
  9415. else {
  9416. el.className = value;
  9417. }
  9418. }
  9419. function patchStyle(el, prev, next) {
  9420. const style = el.style;
  9421. const isCssString = isString(next);
  9422. if (next && !isCssString) {
  9423. for (const key in next) {
  9424. setStyle(style, key, next[key]);
  9425. }
  9426. if (prev && !isString(prev)) {
  9427. for (const key in prev) {
  9428. if (next[key] == null) {
  9429. setStyle(style, key, '');
  9430. }
  9431. }
  9432. }
  9433. }
  9434. else {
  9435. const currentDisplay = style.display;
  9436. if (isCssString) {
  9437. if (prev !== next) {
  9438. style.cssText = next;
  9439. }
  9440. }
  9441. else if (prev) {
  9442. el.removeAttribute('style');
  9443. }
  9444. // indicates that the `display` of the element is controlled by `v-show`,
  9445. // so we always keep the current `display` value regardless of the `style`
  9446. // value, thus handing over control to `v-show`.
  9447. if ('_vod' in el) {
  9448. style.display = currentDisplay;
  9449. }
  9450. }
  9451. }
  9452. const semicolonRE = /[^\\];\s*$/;
  9453. const importantRE = /\s*!important$/;
  9454. function setStyle(style, name, val) {
  9455. if (isArray(val)) {
  9456. val.forEach(v => setStyle(style, name, v));
  9457. }
  9458. else {
  9459. if (val == null)
  9460. val = '';
  9461. {
  9462. if (semicolonRE.test(val)) {
  9463. warn$1(`Unexpected semicolon at the end of '${name}' style value: '${val}'`);
  9464. }
  9465. }
  9466. if (name.startsWith('--')) {
  9467. // custom property definition
  9468. style.setProperty(name, val);
  9469. }
  9470. else {
  9471. const prefixed = autoPrefix(style, name);
  9472. if (importantRE.test(val)) {
  9473. // !important
  9474. style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
  9475. }
  9476. else {
  9477. style[prefixed] = val;
  9478. }
  9479. }
  9480. }
  9481. }
  9482. const prefixes = ['Webkit', 'Moz', 'ms'];
  9483. const prefixCache = {};
  9484. function autoPrefix(style, rawName) {
  9485. const cached = prefixCache[rawName];
  9486. if (cached) {
  9487. return cached;
  9488. }
  9489. let name = camelize(rawName);
  9490. if (name !== 'filter' && name in style) {
  9491. return (prefixCache[rawName] = name);
  9492. }
  9493. name = capitalize(name);
  9494. for (let i = 0; i < prefixes.length; i++) {
  9495. const prefixed = prefixes[i] + name;
  9496. if (prefixed in style) {
  9497. return (prefixCache[rawName] = prefixed);
  9498. }
  9499. }
  9500. return rawName;
  9501. }
  9502. const xlinkNS = 'http://www.w3.org/1999/xlink';
  9503. function patchAttr(el, key, value, isSVG, instance) {
  9504. if (isSVG && key.startsWith('xlink:')) {
  9505. if (value == null) {
  9506. el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
  9507. }
  9508. else {
  9509. el.setAttributeNS(xlinkNS, key, value);
  9510. }
  9511. }
  9512. else {
  9513. // note we are only checking boolean attributes that don't have a
  9514. // corresponding dom prop of the same name here.
  9515. const isBoolean = isSpecialBooleanAttr(key);
  9516. if (value == null || (isBoolean && !includeBooleanAttr(value))) {
  9517. el.removeAttribute(key);
  9518. }
  9519. else {
  9520. el.setAttribute(key, isBoolean ? '' : value);
  9521. }
  9522. }
  9523. }
  9524. // __UNSAFE__
  9525. // functions. The user is responsible for using them with only trusted content.
  9526. function patchDOMProp(el, key, value,
  9527. // the following args are passed only due to potential innerHTML/textContent
  9528. // overriding existing VNodes, in which case the old tree must be properly
  9529. // unmounted.
  9530. prevChildren, parentComponent, parentSuspense, unmountChildren) {
  9531. if (key === 'innerHTML' || key === 'textContent') {
  9532. if (prevChildren) {
  9533. unmountChildren(prevChildren, parentComponent, parentSuspense);
  9534. }
  9535. el[key] = value == null ? '' : value;
  9536. return;
  9537. }
  9538. if (key === 'value' &&
  9539. el.tagName !== 'PROGRESS' &&
  9540. // custom elements may use _value internally
  9541. !el.tagName.includes('-')) {
  9542. // store value as _value as well since
  9543. // non-string values will be stringified.
  9544. el._value = value;
  9545. const newValue = value == null ? '' : value;
  9546. if (el.value !== newValue ||
  9547. // #4956: always set for OPTION elements because its value falls back to
  9548. // textContent if no value attribute is present. And setting .value for
  9549. // OPTION has no side effect
  9550. el.tagName === 'OPTION') {
  9551. el.value = newValue;
  9552. }
  9553. if (value == null) {
  9554. el.removeAttribute(key);
  9555. }
  9556. return;
  9557. }
  9558. let needRemove = false;
  9559. if (value === '' || value == null) {
  9560. const type = typeof el[key];
  9561. if (type === 'boolean') {
  9562. // e.g. <select multiple> compiles to { multiple: '' }
  9563. value = includeBooleanAttr(value);
  9564. }
  9565. else if (value == null && type === 'string') {
  9566. // e.g. <div :id="null">
  9567. value = '';
  9568. needRemove = true;
  9569. }
  9570. else if (type === 'number') {
  9571. // e.g. <img :width="null">
  9572. value = 0;
  9573. needRemove = true;
  9574. }
  9575. }
  9576. // some properties perform value validation and throw,
  9577. // some properties has getter, no setter, will error in 'use strict'
  9578. // eg. <select :type="null"></select> <select :willValidate="null"></select>
  9579. try {
  9580. el[key] = value;
  9581. }
  9582. catch (e) {
  9583. // do not warn if value is auto-coerced from nullish values
  9584. if (!needRemove) {
  9585. warn$1(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
  9586. `value ${value} is invalid.`, e);
  9587. }
  9588. }
  9589. needRemove && el.removeAttribute(key);
  9590. }
  9591. function addEventListener(el, event, handler, options) {
  9592. el.addEventListener(event, handler, options);
  9593. }
  9594. function removeEventListener(el, event, handler, options) {
  9595. el.removeEventListener(event, handler, options);
  9596. }
  9597. function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
  9598. // vei = vue event invokers
  9599. const invokers = el._vei || (el._vei = {});
  9600. const existingInvoker = invokers[rawName];
  9601. if (nextValue && existingInvoker) {
  9602. // patch
  9603. existingInvoker.value = nextValue;
  9604. }
  9605. else {
  9606. const [name, options] = parseName(rawName);
  9607. if (nextValue) {
  9608. // add
  9609. const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
  9610. addEventListener(el, name, invoker, options);
  9611. }
  9612. else if (existingInvoker) {
  9613. // remove
  9614. removeEventListener(el, name, existingInvoker, options);
  9615. invokers[rawName] = undefined;
  9616. }
  9617. }
  9618. }
  9619. const optionsModifierRE = /(?:Once|Passive|Capture)$/;
  9620. function parseName(name) {
  9621. let options;
  9622. if (optionsModifierRE.test(name)) {
  9623. options = {};
  9624. let m;
  9625. while ((m = name.match(optionsModifierRE))) {
  9626. name = name.slice(0, name.length - m[0].length);
  9627. options[m[0].toLowerCase()] = true;
  9628. }
  9629. }
  9630. const event = name[2] === ':' ? name.slice(3) : hyphenate(name.slice(2));
  9631. return [event, options];
  9632. }
  9633. // To avoid the overhead of repeatedly calling Date.now(), we cache
  9634. // and use the same timestamp for all event listeners attached in the same tick.
  9635. let cachedNow = 0;
  9636. const p = /*#__PURE__*/ Promise.resolve();
  9637. const getNow = () => cachedNow || (p.then(() => (cachedNow = 0)), (cachedNow = Date.now()));
  9638. function createInvoker(initialValue, instance) {
  9639. const invoker = (e) => {
  9640. // async edge case vuejs/vue#6566
  9641. // inner click event triggers patch, event handler
  9642. // attached to outer element during patch, and triggered again. This
  9643. // happens because browsers fire microtask ticks between event propagation.
  9644. // this no longer happens for templates in Vue 3, but could still be
  9645. // theoretically possible for hand-written render functions.
  9646. // the solution: we save the timestamp when a handler is attached,
  9647. // and also attach the timestamp to any event that was handled by vue
  9648. // for the first time (to avoid inconsistent event timestamp implementations
  9649. // or events fired from iframes, e.g. #2513)
  9650. // The handler would only fire if the event passed to it was fired
  9651. // AFTER it was attached.
  9652. if (!e._vts) {
  9653. e._vts = Date.now();
  9654. }
  9655. else if (e._vts <= invoker.attached) {
  9656. return;
  9657. }
  9658. callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* ErrorCodes.NATIVE_EVENT_HANDLER */, [e]);
  9659. };
  9660. invoker.value = initialValue;
  9661. invoker.attached = getNow();
  9662. return invoker;
  9663. }
  9664. function patchStopImmediatePropagation(e, value) {
  9665. if (isArray(value)) {
  9666. const originalStop = e.stopImmediatePropagation;
  9667. e.stopImmediatePropagation = () => {
  9668. originalStop.call(e);
  9669. e._stopped = true;
  9670. };
  9671. return value.map(fn => (e) => !e._stopped && fn && fn(e));
  9672. }
  9673. else {
  9674. return value;
  9675. }
  9676. }
  9677. const nativeOnRE = /^on[a-z]/;
  9678. const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
  9679. if (key === 'class') {
  9680. patchClass(el, nextValue, isSVG);
  9681. }
  9682. else if (key === 'style') {
  9683. patchStyle(el, prevValue, nextValue);
  9684. }
  9685. else if (isOn(key)) {
  9686. // ignore v-model listeners
  9687. if (!isModelListener(key)) {
  9688. patchEvent(el, key, prevValue, nextValue, parentComponent);
  9689. }
  9690. }
  9691. else if (key[0] === '.'
  9692. ? ((key = key.slice(1)), true)
  9693. : key[0] === '^'
  9694. ? ((key = key.slice(1)), false)
  9695. : shouldSetAsProp(el, key, nextValue, isSVG)) {
  9696. patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
  9697. }
  9698. else {
  9699. // special case for <input v-model type="checkbox"> with
  9700. // :true-value & :false-value
  9701. // store value as dom properties since non-string values will be
  9702. // stringified.
  9703. if (key === 'true-value') {
  9704. el._trueValue = nextValue;
  9705. }
  9706. else if (key === 'false-value') {
  9707. el._falseValue = nextValue;
  9708. }
  9709. patchAttr(el, key, nextValue, isSVG);
  9710. }
  9711. };
  9712. function shouldSetAsProp(el, key, value, isSVG) {
  9713. if (isSVG) {
  9714. // most keys must be set as attribute on svg elements to work
  9715. // ...except innerHTML & textContent
  9716. if (key === 'innerHTML' || key === 'textContent') {
  9717. return true;
  9718. }
  9719. // or native onclick with function values
  9720. if (key in el && nativeOnRE.test(key) && isFunction(value)) {
  9721. return true;
  9722. }
  9723. return false;
  9724. }
  9725. // these are enumerated attrs, however their corresponding DOM properties
  9726. // are actually booleans - this leads to setting it with a string "false"
  9727. // value leading it to be coerced to `true`, so we need to always treat
  9728. // them as attributes.
  9729. // Note that `contentEditable` doesn't have this problem: its DOM
  9730. // property is also enumerated string values.
  9731. if (key === 'spellcheck' || key === 'draggable' || key === 'translate') {
  9732. return false;
  9733. }
  9734. // #1787, #2840 form property on form elements is readonly and must be set as
  9735. // attribute.
  9736. if (key === 'form') {
  9737. return false;
  9738. }
  9739. // #1526 <input list> must be set as attribute
  9740. if (key === 'list' && el.tagName === 'INPUT') {
  9741. return false;
  9742. }
  9743. // #2766 <textarea type> must be set as attribute
  9744. if (key === 'type' && el.tagName === 'TEXTAREA') {
  9745. return false;
  9746. }
  9747. // native onclick with string value, must be set as attribute
  9748. if (nativeOnRE.test(key) && isString(value)) {
  9749. return false;
  9750. }
  9751. return key in el;
  9752. }
  9753. function defineCustomElement(options, hydrate) {
  9754. const Comp = defineComponent(options);
  9755. class VueCustomElement extends VueElement {
  9756. constructor(initialProps) {
  9757. super(Comp, initialProps, hydrate);
  9758. }
  9759. }
  9760. VueCustomElement.def = Comp;
  9761. return VueCustomElement;
  9762. }
  9763. const defineSSRCustomElement = ((options) => {
  9764. // @ts-ignore
  9765. return defineCustomElement(options, hydrate);
  9766. });
  9767. const BaseClass = (typeof HTMLElement !== 'undefined' ? HTMLElement : class {
  9768. });
  9769. class VueElement extends BaseClass {
  9770. constructor(_def, _props = {}, hydrate) {
  9771. super();
  9772. this._def = _def;
  9773. this._props = _props;
  9774. /**
  9775. * @internal
  9776. */
  9777. this._instance = null;
  9778. this._connected = false;
  9779. this._resolved = false;
  9780. this._numberProps = null;
  9781. if (this.shadowRoot && hydrate) {
  9782. hydrate(this._createVNode(), this.shadowRoot);
  9783. }
  9784. else {
  9785. if (this.shadowRoot) {
  9786. warn$1(`Custom element has pre-rendered declarative shadow root but is not ` +
  9787. `defined as hydratable. Use \`defineSSRCustomElement\`.`);
  9788. }
  9789. this.attachShadow({ mode: 'open' });
  9790. if (!this._def.__asyncLoader) {
  9791. // for sync component defs we can immediately resolve props
  9792. this._resolveProps(this._def);
  9793. }
  9794. }
  9795. }
  9796. connectedCallback() {
  9797. this._connected = true;
  9798. if (!this._instance) {
  9799. if (this._resolved) {
  9800. this._update();
  9801. }
  9802. else {
  9803. this._resolveDef();
  9804. }
  9805. }
  9806. }
  9807. disconnectedCallback() {
  9808. this._connected = false;
  9809. nextTick(() => {
  9810. if (!this._connected) {
  9811. render(null, this.shadowRoot);
  9812. this._instance = null;
  9813. }
  9814. });
  9815. }
  9816. /**
  9817. * resolve inner component definition (handle possible async component)
  9818. */
  9819. _resolveDef() {
  9820. this._resolved = true;
  9821. // set initial attrs
  9822. for (let i = 0; i < this.attributes.length; i++) {
  9823. this._setAttr(this.attributes[i].name);
  9824. }
  9825. // watch future attr changes
  9826. new MutationObserver(mutations => {
  9827. for (const m of mutations) {
  9828. this._setAttr(m.attributeName);
  9829. }
  9830. }).observe(this, { attributes: true });
  9831. const resolve = (def, isAsync = false) => {
  9832. const { props, styles } = def;
  9833. // cast Number-type props set before resolve
  9834. let numberProps;
  9835. if (props && !isArray(props)) {
  9836. for (const key in props) {
  9837. const opt = props[key];
  9838. if (opt === Number || (opt && opt.type === Number)) {
  9839. if (key in this._props) {
  9840. this._props[key] = toNumber(this._props[key]);
  9841. }
  9842. (numberProps || (numberProps = Object.create(null)))[camelize(key)] = true;
  9843. }
  9844. }
  9845. }
  9846. this._numberProps = numberProps;
  9847. if (isAsync) {
  9848. // defining getter/setters on prototype
  9849. // for sync defs, this already happened in the constructor
  9850. this._resolveProps(def);
  9851. }
  9852. // apply CSS
  9853. this._applyStyles(styles);
  9854. // initial render
  9855. this._update();
  9856. };
  9857. const asyncDef = this._def.__asyncLoader;
  9858. if (asyncDef) {
  9859. asyncDef().then(def => resolve(def, true));
  9860. }
  9861. else {
  9862. resolve(this._def);
  9863. }
  9864. }
  9865. _resolveProps(def) {
  9866. const { props } = def;
  9867. const declaredPropKeys = isArray(props) ? props : Object.keys(props || {});
  9868. // check if there are props set pre-upgrade or connect
  9869. for (const key of Object.keys(this)) {
  9870. if (key[0] !== '_' && declaredPropKeys.includes(key)) {
  9871. this._setProp(key, this[key], true, false);
  9872. }
  9873. }
  9874. // defining getter/setters on prototype
  9875. for (const key of declaredPropKeys.map(camelize)) {
  9876. Object.defineProperty(this, key, {
  9877. get() {
  9878. return this._getProp(key);
  9879. },
  9880. set(val) {
  9881. this._setProp(key, val);
  9882. }
  9883. });
  9884. }
  9885. }
  9886. _setAttr(key) {
  9887. let value = this.getAttribute(key);
  9888. const camelKey = camelize(key);
  9889. if (this._numberProps && this._numberProps[camelKey]) {
  9890. value = toNumber(value);
  9891. }
  9892. this._setProp(camelKey, value, false);
  9893. }
  9894. /**
  9895. * @internal
  9896. */
  9897. _getProp(key) {
  9898. return this._props[key];
  9899. }
  9900. /**
  9901. * @internal
  9902. */
  9903. _setProp(key, val, shouldReflect = true, shouldUpdate = true) {
  9904. if (val !== this._props[key]) {
  9905. this._props[key] = val;
  9906. if (shouldUpdate && this._instance) {
  9907. this._update();
  9908. }
  9909. // reflect
  9910. if (shouldReflect) {
  9911. if (val === true) {
  9912. this.setAttribute(hyphenate(key), '');
  9913. }
  9914. else if (typeof val === 'string' || typeof val === 'number') {
  9915. this.setAttribute(hyphenate(key), val + '');
  9916. }
  9917. else if (!val) {
  9918. this.removeAttribute(hyphenate(key));
  9919. }
  9920. }
  9921. }
  9922. }
  9923. _update() {
  9924. render(this._createVNode(), this.shadowRoot);
  9925. }
  9926. _createVNode() {
  9927. const vnode = createVNode(this._def, extend({}, this._props));
  9928. if (!this._instance) {
  9929. vnode.ce = instance => {
  9930. this._instance = instance;
  9931. instance.isCE = true;
  9932. // HMR
  9933. {
  9934. instance.ceReload = newStyles => {
  9935. // always reset styles
  9936. if (this._styles) {
  9937. this._styles.forEach(s => this.shadowRoot.removeChild(s));
  9938. this._styles.length = 0;
  9939. }
  9940. this._applyStyles(newStyles);
  9941. this._instance = null;
  9942. this._update();
  9943. };
  9944. }
  9945. const dispatch = (event, args) => {
  9946. this.dispatchEvent(new CustomEvent(event, {
  9947. detail: args
  9948. }));
  9949. };
  9950. // intercept emit
  9951. instance.emit = (event, ...args) => {
  9952. // dispatch both the raw and hyphenated versions of an event
  9953. // to match Vue behavior
  9954. dispatch(event, args);
  9955. if (hyphenate(event) !== event) {
  9956. dispatch(hyphenate(event), args);
  9957. }
  9958. };
  9959. // locate nearest Vue custom element parent for provide/inject
  9960. let parent = this;
  9961. while ((parent =
  9962. parent && (parent.parentNode || parent.host))) {
  9963. if (parent instanceof VueElement) {
  9964. instance.parent = parent._instance;
  9965. instance.provides = parent._instance.provides;
  9966. break;
  9967. }
  9968. }
  9969. };
  9970. }
  9971. return vnode;
  9972. }
  9973. _applyStyles(styles) {
  9974. if (styles) {
  9975. styles.forEach(css => {
  9976. const s = document.createElement('style');
  9977. s.textContent = css;
  9978. this.shadowRoot.appendChild(s);
  9979. // record for HMR
  9980. {
  9981. (this._styles || (this._styles = [])).push(s);
  9982. }
  9983. });
  9984. }
  9985. }
  9986. }
  9987. function useCssModule(name = '$style') {
  9988. /* istanbul ignore else */
  9989. {
  9990. const instance = getCurrentInstance();
  9991. if (!instance) {
  9992. warn$1(`useCssModule must be called inside setup()`);
  9993. return EMPTY_OBJ;
  9994. }
  9995. const modules = instance.type.__cssModules;
  9996. if (!modules) {
  9997. warn$1(`Current instance does not have CSS modules injected.`);
  9998. return EMPTY_OBJ;
  9999. }
  10000. const mod = modules[name];
  10001. if (!mod) {
  10002. warn$1(`Current instance does not have CSS module named "${name}".`);
  10003. return EMPTY_OBJ;
  10004. }
  10005. return mod;
  10006. }
  10007. }
  10008. /**
  10009. * Runtime helper for SFC's CSS variable injection feature.
  10010. * @private
  10011. */
  10012. function useCssVars(getter) {
  10013. const instance = getCurrentInstance();
  10014. /* istanbul ignore next */
  10015. if (!instance) {
  10016. warn$1(`useCssVars is called without current active component instance.`);
  10017. return;
  10018. }
  10019. const updateTeleports = (instance.ut = (vars = getter(instance.proxy)) => {
  10020. Array.from(document.querySelectorAll(`[data-v-owner="${instance.uid}"]`)).forEach(node => setVarsOnNode(node, vars));
  10021. });
  10022. const setVars = () => {
  10023. const vars = getter(instance.proxy);
  10024. setVarsOnVNode(instance.subTree, vars);
  10025. updateTeleports(vars);
  10026. };
  10027. watchPostEffect(setVars);
  10028. onMounted(() => {
  10029. const ob = new MutationObserver(setVars);
  10030. ob.observe(instance.subTree.el.parentNode, { childList: true });
  10031. onUnmounted(() => ob.disconnect());
  10032. });
  10033. }
  10034. function setVarsOnVNode(vnode, vars) {
  10035. if (vnode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  10036. const suspense = vnode.suspense;
  10037. vnode = suspense.activeBranch;
  10038. if (suspense.pendingBranch && !suspense.isHydrating) {
  10039. suspense.effects.push(() => {
  10040. setVarsOnVNode(suspense.activeBranch, vars);
  10041. });
  10042. }
  10043. }
  10044. // drill down HOCs until it's a non-component vnode
  10045. while (vnode.component) {
  10046. vnode = vnode.component.subTree;
  10047. }
  10048. if (vnode.shapeFlag & 1 /* ShapeFlags.ELEMENT */ && vnode.el) {
  10049. setVarsOnNode(vnode.el, vars);
  10050. }
  10051. else if (vnode.type === Fragment) {
  10052. vnode.children.forEach(c => setVarsOnVNode(c, vars));
  10053. }
  10054. else if (vnode.type === Static) {
  10055. let { el, anchor } = vnode;
  10056. while (el) {
  10057. setVarsOnNode(el, vars);
  10058. if (el === anchor)
  10059. break;
  10060. el = el.nextSibling;
  10061. }
  10062. }
  10063. }
  10064. function setVarsOnNode(el, vars) {
  10065. if (el.nodeType === 1) {
  10066. const style = el.style;
  10067. for (const key in vars) {
  10068. style.setProperty(`--${key}`, vars[key]);
  10069. }
  10070. }
  10071. }
  10072. const TRANSITION = 'transition';
  10073. const ANIMATION = 'animation';
  10074. // DOM Transition is a higher-order-component based on the platform-agnostic
  10075. // base Transition component, with DOM-specific logic.
  10076. const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
  10077. Transition.displayName = 'Transition';
  10078. const DOMTransitionPropsValidators = {
  10079. name: String,
  10080. type: String,
  10081. css: {
  10082. type: Boolean,
  10083. default: true
  10084. },
  10085. duration: [String, Number, Object],
  10086. enterFromClass: String,
  10087. enterActiveClass: String,
  10088. enterToClass: String,
  10089. appearFromClass: String,
  10090. appearActiveClass: String,
  10091. appearToClass: String,
  10092. leaveFromClass: String,
  10093. leaveActiveClass: String,
  10094. leaveToClass: String
  10095. };
  10096. const TransitionPropsValidators = (Transition.props =
  10097. /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
  10098. /**
  10099. * #3227 Incoming hooks may be merged into arrays when wrapping Transition
  10100. * with custom HOCs.
  10101. */
  10102. const callHook$1 = (hook, args = []) => {
  10103. if (isArray(hook)) {
  10104. hook.forEach(h => h(...args));
  10105. }
  10106. else if (hook) {
  10107. hook(...args);
  10108. }
  10109. };
  10110. /**
  10111. * Check if a hook expects a callback (2nd arg), which means the user
  10112. * intends to explicitly control the end of the transition.
  10113. */
  10114. const hasExplicitCallback = (hook) => {
  10115. return hook
  10116. ? isArray(hook)
  10117. ? hook.some(h => h.length > 1)
  10118. : hook.length > 1
  10119. : false;
  10120. };
  10121. function resolveTransitionProps(rawProps) {
  10122. const baseProps = {};
  10123. for (const key in rawProps) {
  10124. if (!(key in DOMTransitionPropsValidators)) {
  10125. baseProps[key] = rawProps[key];
  10126. }
  10127. }
  10128. if (rawProps.css === false) {
  10129. return baseProps;
  10130. }
  10131. const { name = 'v', type, 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;
  10132. const durations = normalizeDuration(duration);
  10133. const enterDuration = durations && durations[0];
  10134. const leaveDuration = durations && durations[1];
  10135. const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
  10136. const finishEnter = (el, isAppear, done) => {
  10137. removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
  10138. removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
  10139. done && done();
  10140. };
  10141. const finishLeave = (el, done) => {
  10142. el._isLeaving = false;
  10143. removeTransitionClass(el, leaveFromClass);
  10144. removeTransitionClass(el, leaveToClass);
  10145. removeTransitionClass(el, leaveActiveClass);
  10146. done && done();
  10147. };
  10148. const makeEnterHook = (isAppear) => {
  10149. return (el, done) => {
  10150. const hook = isAppear ? onAppear : onEnter;
  10151. const resolve = () => finishEnter(el, isAppear, done);
  10152. callHook$1(hook, [el, resolve]);
  10153. nextFrame(() => {
  10154. removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
  10155. addTransitionClass(el, isAppear ? appearToClass : enterToClass);
  10156. if (!hasExplicitCallback(hook)) {
  10157. whenTransitionEnds(el, type, enterDuration, resolve);
  10158. }
  10159. });
  10160. };
  10161. };
  10162. return extend(baseProps, {
  10163. onBeforeEnter(el) {
  10164. callHook$1(onBeforeEnter, [el]);
  10165. addTransitionClass(el, enterFromClass);
  10166. addTransitionClass(el, enterActiveClass);
  10167. },
  10168. onBeforeAppear(el) {
  10169. callHook$1(onBeforeAppear, [el]);
  10170. addTransitionClass(el, appearFromClass);
  10171. addTransitionClass(el, appearActiveClass);
  10172. },
  10173. onEnter: makeEnterHook(false),
  10174. onAppear: makeEnterHook(true),
  10175. onLeave(el, done) {
  10176. el._isLeaving = true;
  10177. const resolve = () => finishLeave(el, done);
  10178. addTransitionClass(el, leaveFromClass);
  10179. // force reflow so *-leave-from classes immediately take effect (#2593)
  10180. forceReflow();
  10181. addTransitionClass(el, leaveActiveClass);
  10182. nextFrame(() => {
  10183. if (!el._isLeaving) {
  10184. // cancelled
  10185. return;
  10186. }
  10187. removeTransitionClass(el, leaveFromClass);
  10188. addTransitionClass(el, leaveToClass);
  10189. if (!hasExplicitCallback(onLeave)) {
  10190. whenTransitionEnds(el, type, leaveDuration, resolve);
  10191. }
  10192. });
  10193. callHook$1(onLeave, [el, resolve]);
  10194. },
  10195. onEnterCancelled(el) {
  10196. finishEnter(el, false);
  10197. callHook$1(onEnterCancelled, [el]);
  10198. },
  10199. onAppearCancelled(el) {
  10200. finishEnter(el, true);
  10201. callHook$1(onAppearCancelled, [el]);
  10202. },
  10203. onLeaveCancelled(el) {
  10204. finishLeave(el);
  10205. callHook$1(onLeaveCancelled, [el]);
  10206. }
  10207. });
  10208. }
  10209. function normalizeDuration(duration) {
  10210. if (duration == null) {
  10211. return null;
  10212. }
  10213. else if (isObject(duration)) {
  10214. return [NumberOf(duration.enter), NumberOf(duration.leave)];
  10215. }
  10216. else {
  10217. const n = NumberOf(duration);
  10218. return [n, n];
  10219. }
  10220. }
  10221. function NumberOf(val) {
  10222. const res = toNumber(val);
  10223. validateDuration(res);
  10224. return res;
  10225. }
  10226. function validateDuration(val) {
  10227. if (typeof val !== 'number') {
  10228. warn$1(`<transition> explicit duration is not a valid number - ` +
  10229. `got ${JSON.stringify(val)}.`);
  10230. }
  10231. else if (isNaN(val)) {
  10232. warn$1(`<transition> explicit duration is NaN - ` +
  10233. 'the duration expression might be incorrect.');
  10234. }
  10235. }
  10236. function addTransitionClass(el, cls) {
  10237. cls.split(/\s+/).forEach(c => c && el.classList.add(c));
  10238. (el._vtc ||
  10239. (el._vtc = new Set())).add(cls);
  10240. }
  10241. function removeTransitionClass(el, cls) {
  10242. cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
  10243. const { _vtc } = el;
  10244. if (_vtc) {
  10245. _vtc.delete(cls);
  10246. if (!_vtc.size) {
  10247. el._vtc = undefined;
  10248. }
  10249. }
  10250. }
  10251. function nextFrame(cb) {
  10252. requestAnimationFrame(() => {
  10253. requestAnimationFrame(cb);
  10254. });
  10255. }
  10256. let endId = 0;
  10257. function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
  10258. const id = (el._endId = ++endId);
  10259. const resolveIfNotStale = () => {
  10260. if (id === el._endId) {
  10261. resolve();
  10262. }
  10263. };
  10264. if (explicitTimeout) {
  10265. return setTimeout(resolveIfNotStale, explicitTimeout);
  10266. }
  10267. const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
  10268. if (!type) {
  10269. return resolve();
  10270. }
  10271. const endEvent = type + 'end';
  10272. let ended = 0;
  10273. const end = () => {
  10274. el.removeEventListener(endEvent, onEnd);
  10275. resolveIfNotStale();
  10276. };
  10277. const onEnd = (e) => {
  10278. if (e.target === el && ++ended >= propCount) {
  10279. end();
  10280. }
  10281. };
  10282. setTimeout(() => {
  10283. if (ended < propCount) {
  10284. end();
  10285. }
  10286. }, timeout + 1);
  10287. el.addEventListener(endEvent, onEnd);
  10288. }
  10289. function getTransitionInfo(el, expectedType) {
  10290. const styles = window.getComputedStyle(el);
  10291. // JSDOM may return undefined for transition properties
  10292. const getStyleProperties = (key) => (styles[key] || '').split(', ');
  10293. const transitionDelays = getStyleProperties(`${TRANSITION}Delay`);
  10294. const transitionDurations = getStyleProperties(`${TRANSITION}Duration`);
  10295. const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
  10296. const animationDelays = getStyleProperties(`${ANIMATION}Delay`);
  10297. const animationDurations = getStyleProperties(`${ANIMATION}Duration`);
  10298. const animationTimeout = getTimeout(animationDelays, animationDurations);
  10299. let type = null;
  10300. let timeout = 0;
  10301. let propCount = 0;
  10302. /* istanbul ignore if */
  10303. if (expectedType === TRANSITION) {
  10304. if (transitionTimeout > 0) {
  10305. type = TRANSITION;
  10306. timeout = transitionTimeout;
  10307. propCount = transitionDurations.length;
  10308. }
  10309. }
  10310. else if (expectedType === ANIMATION) {
  10311. if (animationTimeout > 0) {
  10312. type = ANIMATION;
  10313. timeout = animationTimeout;
  10314. propCount = animationDurations.length;
  10315. }
  10316. }
  10317. else {
  10318. timeout = Math.max(transitionTimeout, animationTimeout);
  10319. type =
  10320. timeout > 0
  10321. ? transitionTimeout > animationTimeout
  10322. ? TRANSITION
  10323. : ANIMATION
  10324. : null;
  10325. propCount = type
  10326. ? type === TRANSITION
  10327. ? transitionDurations.length
  10328. : animationDurations.length
  10329. : 0;
  10330. }
  10331. const hasTransform = type === TRANSITION &&
  10332. /\b(transform|all)(,|$)/.test(getStyleProperties(`${TRANSITION}Property`).toString());
  10333. return {
  10334. type,
  10335. timeout,
  10336. propCount,
  10337. hasTransform
  10338. };
  10339. }
  10340. function getTimeout(delays, durations) {
  10341. while (delays.length < durations.length) {
  10342. delays = delays.concat(delays);
  10343. }
  10344. return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
  10345. }
  10346. // Old versions of Chromium (below 61.0.3163.100) formats floating pointer
  10347. // numbers in a locale-dependent way, using a comma instead of a dot.
  10348. // If comma is not replaced with a dot, the input will be rounded down
  10349. // (i.e. acting as a floor function) causing unexpected behaviors
  10350. function toMs(s) {
  10351. return Number(s.slice(0, -1).replace(',', '.')) * 1000;
  10352. }
  10353. // synchronously force layout to put elements into a certain state
  10354. function forceReflow() {
  10355. return document.body.offsetHeight;
  10356. }
  10357. const positionMap = new WeakMap();
  10358. const newPositionMap = new WeakMap();
  10359. const TransitionGroupImpl = {
  10360. name: 'TransitionGroup',
  10361. props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
  10362. tag: String,
  10363. moveClass: String
  10364. }),
  10365. setup(props, { slots }) {
  10366. const instance = getCurrentInstance();
  10367. const state = useTransitionState();
  10368. let prevChildren;
  10369. let children;
  10370. onUpdated(() => {
  10371. // children is guaranteed to exist after initial render
  10372. if (!prevChildren.length) {
  10373. return;
  10374. }
  10375. const moveClass = props.moveClass || `${props.name || 'v'}-move`;
  10376. if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
  10377. return;
  10378. }
  10379. // we divide the work into three loops to avoid mixing DOM reads and writes
  10380. // in each iteration - which helps prevent layout thrashing.
  10381. prevChildren.forEach(callPendingCbs);
  10382. prevChildren.forEach(recordPosition);
  10383. const movedChildren = prevChildren.filter(applyTranslation);
  10384. // force reflow to put everything in position
  10385. forceReflow();
  10386. movedChildren.forEach(c => {
  10387. const el = c.el;
  10388. const style = el.style;
  10389. addTransitionClass(el, moveClass);
  10390. style.transform = style.webkitTransform = style.transitionDuration = '';
  10391. const cb = (el._moveCb = (e) => {
  10392. if (e && e.target !== el) {
  10393. return;
  10394. }
  10395. if (!e || /transform$/.test(e.propertyName)) {
  10396. el.removeEventListener('transitionend', cb);
  10397. el._moveCb = null;
  10398. removeTransitionClass(el, moveClass);
  10399. }
  10400. });
  10401. el.addEventListener('transitionend', cb);
  10402. });
  10403. });
  10404. return () => {
  10405. const rawProps = toRaw(props);
  10406. const cssTransitionProps = resolveTransitionProps(rawProps);
  10407. let tag = rawProps.tag || Fragment;
  10408. prevChildren = children;
  10409. children = slots.default ? getTransitionRawChildren(slots.default()) : [];
  10410. for (let i = 0; i < children.length; i++) {
  10411. const child = children[i];
  10412. if (child.key != null) {
  10413. setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
  10414. }
  10415. else {
  10416. warn$1(`<TransitionGroup> children must be keyed.`);
  10417. }
  10418. }
  10419. if (prevChildren) {
  10420. for (let i = 0; i < prevChildren.length; i++) {
  10421. const child = prevChildren[i];
  10422. setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
  10423. positionMap.set(child, child.el.getBoundingClientRect());
  10424. }
  10425. }
  10426. return createVNode(tag, null, children);
  10427. };
  10428. }
  10429. };
  10430. const TransitionGroup = TransitionGroupImpl;
  10431. function callPendingCbs(c) {
  10432. const el = c.el;
  10433. if (el._moveCb) {
  10434. el._moveCb();
  10435. }
  10436. if (el._enterCb) {
  10437. el._enterCb();
  10438. }
  10439. }
  10440. function recordPosition(c) {
  10441. newPositionMap.set(c, c.el.getBoundingClientRect());
  10442. }
  10443. function applyTranslation(c) {
  10444. const oldPos = positionMap.get(c);
  10445. const newPos = newPositionMap.get(c);
  10446. const dx = oldPos.left - newPos.left;
  10447. const dy = oldPos.top - newPos.top;
  10448. if (dx || dy) {
  10449. const s = c.el.style;
  10450. s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
  10451. s.transitionDuration = '0s';
  10452. return c;
  10453. }
  10454. }
  10455. function hasCSSTransform(el, root, moveClass) {
  10456. // Detect whether an element with the move class applied has
  10457. // CSS transitions. Since the element may be inside an entering
  10458. // transition at this very moment, we make a clone of it and remove
  10459. // all other transition classes applied to ensure only the move class
  10460. // is applied.
  10461. const clone = el.cloneNode();
  10462. if (el._vtc) {
  10463. el._vtc.forEach(cls => {
  10464. cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
  10465. });
  10466. }
  10467. moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
  10468. clone.style.display = 'none';
  10469. const container = (root.nodeType === 1 ? root : root.parentNode);
  10470. container.appendChild(clone);
  10471. const { hasTransform } = getTransitionInfo(clone);
  10472. container.removeChild(clone);
  10473. return hasTransform;
  10474. }
  10475. const getModelAssigner = (vnode) => {
  10476. const fn = vnode.props['onUpdate:modelValue'] ||
  10477. (false );
  10478. return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
  10479. };
  10480. function onCompositionStart(e) {
  10481. e.target.composing = true;
  10482. }
  10483. function onCompositionEnd(e) {
  10484. const target = e.target;
  10485. if (target.composing) {
  10486. target.composing = false;
  10487. target.dispatchEvent(new Event('input'));
  10488. }
  10489. }
  10490. // We are exporting the v-model runtime directly as vnode hooks so that it can
  10491. // be tree-shaken in case v-model is never used.
  10492. const vModelText = {
  10493. created(el, { modifiers: { lazy, trim, number } }, vnode) {
  10494. el._assign = getModelAssigner(vnode);
  10495. const castToNumber = number || (vnode.props && vnode.props.type === 'number');
  10496. addEventListener(el, lazy ? 'change' : 'input', e => {
  10497. if (e.target.composing)
  10498. return;
  10499. let domValue = el.value;
  10500. if (trim) {
  10501. domValue = domValue.trim();
  10502. }
  10503. if (castToNumber) {
  10504. domValue = toNumber(domValue);
  10505. }
  10506. el._assign(domValue);
  10507. });
  10508. if (trim) {
  10509. addEventListener(el, 'change', () => {
  10510. el.value = el.value.trim();
  10511. });
  10512. }
  10513. if (!lazy) {
  10514. addEventListener(el, 'compositionstart', onCompositionStart);
  10515. addEventListener(el, 'compositionend', onCompositionEnd);
  10516. // Safari < 10.2 & UIWebView doesn't fire compositionend when
  10517. // switching focus before confirming composition choice
  10518. // this also fixes the issue where some browsers e.g. iOS Chrome
  10519. // fires "change" instead of "input" on autocomplete.
  10520. addEventListener(el, 'change', onCompositionEnd);
  10521. }
  10522. },
  10523. // set value on mounted so it's after min/max for type="range"
  10524. mounted(el, { value }) {
  10525. el.value = value == null ? '' : value;
  10526. },
  10527. beforeUpdate(el, { value, modifiers: { lazy, trim, number } }, vnode) {
  10528. el._assign = getModelAssigner(vnode);
  10529. // avoid clearing unresolved text. #2302
  10530. if (el.composing)
  10531. return;
  10532. if (document.activeElement === el && el.type !== 'range') {
  10533. if (lazy) {
  10534. return;
  10535. }
  10536. if (trim && el.value.trim() === value) {
  10537. return;
  10538. }
  10539. if ((number || el.type === 'number') && toNumber(el.value) === value) {
  10540. return;
  10541. }
  10542. }
  10543. const newValue = value == null ? '' : value;
  10544. if (el.value !== newValue) {
  10545. el.value = newValue;
  10546. }
  10547. }
  10548. };
  10549. const vModelCheckbox = {
  10550. // #4096 array checkboxes need to be deep traversed
  10551. deep: true,
  10552. created(el, _, vnode) {
  10553. el._assign = getModelAssigner(vnode);
  10554. addEventListener(el, 'change', () => {
  10555. const modelValue = el._modelValue;
  10556. const elementValue = getValue(el);
  10557. const checked = el.checked;
  10558. const assign = el._assign;
  10559. if (isArray(modelValue)) {
  10560. const index = looseIndexOf(modelValue, elementValue);
  10561. const found = index !== -1;
  10562. if (checked && !found) {
  10563. assign(modelValue.concat(elementValue));
  10564. }
  10565. else if (!checked && found) {
  10566. const filtered = [...modelValue];
  10567. filtered.splice(index, 1);
  10568. assign(filtered);
  10569. }
  10570. }
  10571. else if (isSet(modelValue)) {
  10572. const cloned = new Set(modelValue);
  10573. if (checked) {
  10574. cloned.add(elementValue);
  10575. }
  10576. else {
  10577. cloned.delete(elementValue);
  10578. }
  10579. assign(cloned);
  10580. }
  10581. else {
  10582. assign(getCheckboxValue(el, checked));
  10583. }
  10584. });
  10585. },
  10586. // set initial checked on mount to wait for true-value/false-value
  10587. mounted: setChecked,
  10588. beforeUpdate(el, binding, vnode) {
  10589. el._assign = getModelAssigner(vnode);
  10590. setChecked(el, binding, vnode);
  10591. }
  10592. };
  10593. function setChecked(el, { value, oldValue }, vnode) {
  10594. el._modelValue = value;
  10595. if (isArray(value)) {
  10596. el.checked = looseIndexOf(value, vnode.props.value) > -1;
  10597. }
  10598. else if (isSet(value)) {
  10599. el.checked = value.has(vnode.props.value);
  10600. }
  10601. else if (value !== oldValue) {
  10602. el.checked = looseEqual(value, getCheckboxValue(el, true));
  10603. }
  10604. }
  10605. const vModelRadio = {
  10606. created(el, { value }, vnode) {
  10607. el.checked = looseEqual(value, vnode.props.value);
  10608. el._assign = getModelAssigner(vnode);
  10609. addEventListener(el, 'change', () => {
  10610. el._assign(getValue(el));
  10611. });
  10612. },
  10613. beforeUpdate(el, { value, oldValue }, vnode) {
  10614. el._assign = getModelAssigner(vnode);
  10615. if (value !== oldValue) {
  10616. el.checked = looseEqual(value, vnode.props.value);
  10617. }
  10618. }
  10619. };
  10620. const vModelSelect = {
  10621. // <select multiple> value need to be deep traversed
  10622. deep: true,
  10623. created(el, { value, modifiers: { number } }, vnode) {
  10624. const isSetModel = isSet(value);
  10625. addEventListener(el, 'change', () => {
  10626. const selectedVal = Array.prototype.filter
  10627. .call(el.options, (o) => o.selected)
  10628. .map((o) => number ? toNumber(getValue(o)) : getValue(o));
  10629. el._assign(el.multiple
  10630. ? isSetModel
  10631. ? new Set(selectedVal)
  10632. : selectedVal
  10633. : selectedVal[0]);
  10634. });
  10635. el._assign = getModelAssigner(vnode);
  10636. },
  10637. // set value in mounted & updated because <select> relies on its children
  10638. // <option>s.
  10639. mounted(el, { value }) {
  10640. setSelected(el, value);
  10641. },
  10642. beforeUpdate(el, _binding, vnode) {
  10643. el._assign = getModelAssigner(vnode);
  10644. },
  10645. updated(el, { value }) {
  10646. setSelected(el, value);
  10647. }
  10648. };
  10649. function setSelected(el, value) {
  10650. const isMultiple = el.multiple;
  10651. if (isMultiple && !isArray(value) && !isSet(value)) {
  10652. warn$1(`<select multiple v-model> expects an Array or Set value for its binding, ` +
  10653. `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
  10654. return;
  10655. }
  10656. for (let i = 0, l = el.options.length; i < l; i++) {
  10657. const option = el.options[i];
  10658. const optionValue = getValue(option);
  10659. if (isMultiple) {
  10660. if (isArray(value)) {
  10661. option.selected = looseIndexOf(value, optionValue) > -1;
  10662. }
  10663. else {
  10664. option.selected = value.has(optionValue);
  10665. }
  10666. }
  10667. else {
  10668. if (looseEqual(getValue(option), value)) {
  10669. if (el.selectedIndex !== i)
  10670. el.selectedIndex = i;
  10671. return;
  10672. }
  10673. }
  10674. }
  10675. if (!isMultiple && el.selectedIndex !== -1) {
  10676. el.selectedIndex = -1;
  10677. }
  10678. }
  10679. // retrieve raw value set via :value bindings
  10680. function getValue(el) {
  10681. return '_value' in el ? el._value : el.value;
  10682. }
  10683. // retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
  10684. function getCheckboxValue(el, checked) {
  10685. const key = checked ? '_trueValue' : '_falseValue';
  10686. return key in el ? el[key] : checked;
  10687. }
  10688. const vModelDynamic = {
  10689. created(el, binding, vnode) {
  10690. callModelHook(el, binding, vnode, null, 'created');
  10691. },
  10692. mounted(el, binding, vnode) {
  10693. callModelHook(el, binding, vnode, null, 'mounted');
  10694. },
  10695. beforeUpdate(el, binding, vnode, prevVNode) {
  10696. callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
  10697. },
  10698. updated(el, binding, vnode, prevVNode) {
  10699. callModelHook(el, binding, vnode, prevVNode, 'updated');
  10700. }
  10701. };
  10702. function resolveDynamicModel(tagName, type) {
  10703. switch (tagName) {
  10704. case 'SELECT':
  10705. return vModelSelect;
  10706. case 'TEXTAREA':
  10707. return vModelText;
  10708. default:
  10709. switch (type) {
  10710. case 'checkbox':
  10711. return vModelCheckbox;
  10712. case 'radio':
  10713. return vModelRadio;
  10714. default:
  10715. return vModelText;
  10716. }
  10717. }
  10718. }
  10719. function callModelHook(el, binding, vnode, prevVNode, hook) {
  10720. const modelToUse = resolveDynamicModel(el.tagName, vnode.props && vnode.props.type);
  10721. const fn = modelToUse[hook];
  10722. fn && fn(el, binding, vnode, prevVNode);
  10723. }
  10724. const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
  10725. const modifierGuards = {
  10726. stop: e => e.stopPropagation(),
  10727. prevent: e => e.preventDefault(),
  10728. self: e => e.target !== e.currentTarget,
  10729. ctrl: e => !e.ctrlKey,
  10730. shift: e => !e.shiftKey,
  10731. alt: e => !e.altKey,
  10732. meta: e => !e.metaKey,
  10733. left: e => 'button' in e && e.button !== 0,
  10734. middle: e => 'button' in e && e.button !== 1,
  10735. right: e => 'button' in e && e.button !== 2,
  10736. exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
  10737. };
  10738. /**
  10739. * @private
  10740. */
  10741. const withModifiers = (fn, modifiers) => {
  10742. return (event, ...args) => {
  10743. for (let i = 0; i < modifiers.length; i++) {
  10744. const guard = modifierGuards[modifiers[i]];
  10745. if (guard && guard(event, modifiers))
  10746. return;
  10747. }
  10748. return fn(event, ...args);
  10749. };
  10750. };
  10751. // Kept for 2.x compat.
  10752. // Note: IE11 compat for `spacebar` and `del` is removed for now.
  10753. const keyNames = {
  10754. esc: 'escape',
  10755. space: ' ',
  10756. up: 'arrow-up',
  10757. left: 'arrow-left',
  10758. right: 'arrow-right',
  10759. down: 'arrow-down',
  10760. delete: 'backspace'
  10761. };
  10762. /**
  10763. * @private
  10764. */
  10765. const withKeys = (fn, modifiers) => {
  10766. return (event) => {
  10767. if (!('key' in event)) {
  10768. return;
  10769. }
  10770. const eventKey = hyphenate(event.key);
  10771. if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
  10772. return fn(event);
  10773. }
  10774. };
  10775. };
  10776. const vShow = {
  10777. beforeMount(el, { value }, { transition }) {
  10778. el._vod = el.style.display === 'none' ? '' : el.style.display;
  10779. if (transition && value) {
  10780. transition.beforeEnter(el);
  10781. }
  10782. else {
  10783. setDisplay(el, value);
  10784. }
  10785. },
  10786. mounted(el, { value }, { transition }) {
  10787. if (transition && value) {
  10788. transition.enter(el);
  10789. }
  10790. },
  10791. updated(el, { value, oldValue }, { transition }) {
  10792. if (!value === !oldValue)
  10793. return;
  10794. if (transition) {
  10795. if (value) {
  10796. transition.beforeEnter(el);
  10797. setDisplay(el, true);
  10798. transition.enter(el);
  10799. }
  10800. else {
  10801. transition.leave(el, () => {
  10802. setDisplay(el, false);
  10803. });
  10804. }
  10805. }
  10806. else {
  10807. setDisplay(el, value);
  10808. }
  10809. },
  10810. beforeUnmount(el, { value }) {
  10811. setDisplay(el, value);
  10812. }
  10813. };
  10814. function setDisplay(el, value) {
  10815. el.style.display = value ? el._vod : 'none';
  10816. }
  10817. const rendererOptions = /*#__PURE__*/ extend({ patchProp }, nodeOps);
  10818. // lazy create the renderer - this makes core renderer logic tree-shakable
  10819. // in case the user only imports reactivity utilities from Vue.
  10820. let renderer;
  10821. let enabledHydration = false;
  10822. function ensureRenderer() {
  10823. return (renderer ||
  10824. (renderer = createRenderer(rendererOptions)));
  10825. }
  10826. function ensureHydrationRenderer() {
  10827. renderer = enabledHydration
  10828. ? renderer
  10829. : createHydrationRenderer(rendererOptions);
  10830. enabledHydration = true;
  10831. return renderer;
  10832. }
  10833. // use explicit type casts here to avoid import() calls in rolled-up d.ts
  10834. const render = ((...args) => {
  10835. ensureRenderer().render(...args);
  10836. });
  10837. const hydrate = ((...args) => {
  10838. ensureHydrationRenderer().hydrate(...args);
  10839. });
  10840. const createApp = ((...args) => {
  10841. const app = ensureRenderer().createApp(...args);
  10842. {
  10843. injectNativeTagCheck(app);
  10844. injectCompilerOptionsCheck(app);
  10845. }
  10846. const { mount } = app;
  10847. app.mount = (containerOrSelector) => {
  10848. const container = normalizeContainer(containerOrSelector);
  10849. if (!container)
  10850. return;
  10851. const component = app._component;
  10852. if (!isFunction(component) && !component.render && !component.template) {
  10853. // __UNSAFE__
  10854. // Reason: potential execution of JS expressions in in-DOM template.
  10855. // The user must make sure the in-DOM template is trusted. If it's
  10856. // rendered by the server, the template should not contain any user data.
  10857. component.template = container.innerHTML;
  10858. }
  10859. // clear content before mounting
  10860. container.innerHTML = '';
  10861. const proxy = mount(container, false, container instanceof SVGElement);
  10862. if (container instanceof Element) {
  10863. container.removeAttribute('v-cloak');
  10864. container.setAttribute('data-v-app', '');
  10865. }
  10866. return proxy;
  10867. };
  10868. return app;
  10869. });
  10870. const createSSRApp = ((...args) => {
  10871. const app = ensureHydrationRenderer().createApp(...args);
  10872. {
  10873. injectNativeTagCheck(app);
  10874. injectCompilerOptionsCheck(app);
  10875. }
  10876. const { mount } = app;
  10877. app.mount = (containerOrSelector) => {
  10878. const container = normalizeContainer(containerOrSelector);
  10879. if (container) {
  10880. return mount(container, true, container instanceof SVGElement);
  10881. }
  10882. };
  10883. return app;
  10884. });
  10885. function injectNativeTagCheck(app) {
  10886. // Inject `isNativeTag`
  10887. // this is used for component name validation (dev only)
  10888. Object.defineProperty(app.config, 'isNativeTag', {
  10889. value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
  10890. writable: false
  10891. });
  10892. }
  10893. // dev only
  10894. function injectCompilerOptionsCheck(app) {
  10895. if (isRuntimeOnly()) {
  10896. const isCustomElement = app.config.isCustomElement;
  10897. Object.defineProperty(app.config, 'isCustomElement', {
  10898. get() {
  10899. return isCustomElement;
  10900. },
  10901. set() {
  10902. warn$1(`The \`isCustomElement\` config option is deprecated. Use ` +
  10903. `\`compilerOptions.isCustomElement\` instead.`);
  10904. }
  10905. });
  10906. const compilerOptions = app.config.compilerOptions;
  10907. const msg = `The \`compilerOptions\` config option is only respected when using ` +
  10908. `a build of Vue.js that includes the runtime compiler (aka "full build"). ` +
  10909. `Since you are using the runtime-only build, \`compilerOptions\` ` +
  10910. `must be passed to \`@vue/compiler-dom\` in the build setup instead.\n` +
  10911. `- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option.\n` +
  10912. `- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader\n` +
  10913. `- For vite: pass it via @vitejs/plugin-vue options. See https://github.com/vitejs/vite/tree/main/packages/plugin-vue#example-for-passing-options-to-vuecompiler-dom`;
  10914. Object.defineProperty(app.config, 'compilerOptions', {
  10915. get() {
  10916. warn$1(msg);
  10917. return compilerOptions;
  10918. },
  10919. set() {
  10920. warn$1(msg);
  10921. }
  10922. });
  10923. }
  10924. }
  10925. function normalizeContainer(container) {
  10926. if (isString(container)) {
  10927. const res = document.querySelector(container);
  10928. if (!res) {
  10929. warn$1(`Failed to mount app: mount target selector "${container}" returned null.`);
  10930. }
  10931. return res;
  10932. }
  10933. if (window.ShadowRoot &&
  10934. container instanceof window.ShadowRoot &&
  10935. container.mode === 'closed') {
  10936. warn$1(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
  10937. }
  10938. return container;
  10939. }
  10940. /**
  10941. * @internal
  10942. */
  10943. const initDirectivesForSSR = NOOP;
  10944. var runtimeDom = /*#__PURE__*/Object.freeze({
  10945. __proto__: null,
  10946. render: render,
  10947. hydrate: hydrate,
  10948. createApp: createApp,
  10949. createSSRApp: createSSRApp,
  10950. initDirectivesForSSR: initDirectivesForSSR,
  10951. defineCustomElement: defineCustomElement,
  10952. defineSSRCustomElement: defineSSRCustomElement,
  10953. VueElement: VueElement,
  10954. useCssModule: useCssModule,
  10955. useCssVars: useCssVars,
  10956. Transition: Transition,
  10957. TransitionGroup: TransitionGroup,
  10958. vModelText: vModelText,
  10959. vModelCheckbox: vModelCheckbox,
  10960. vModelRadio: vModelRadio,
  10961. vModelSelect: vModelSelect,
  10962. vModelDynamic: vModelDynamic,
  10963. withModifiers: withModifiers,
  10964. withKeys: withKeys,
  10965. vShow: vShow,
  10966. reactive: reactive,
  10967. ref: ref,
  10968. readonly: readonly,
  10969. unref: unref,
  10970. proxyRefs: proxyRefs,
  10971. isRef: isRef,
  10972. toRef: toRef,
  10973. toRefs: toRefs,
  10974. isProxy: isProxy,
  10975. isReactive: isReactive,
  10976. isReadonly: isReadonly,
  10977. isShallow: isShallow,
  10978. customRef: customRef,
  10979. triggerRef: triggerRef,
  10980. shallowRef: shallowRef,
  10981. shallowReactive: shallowReactive,
  10982. shallowReadonly: shallowReadonly,
  10983. markRaw: markRaw,
  10984. toRaw: toRaw,
  10985. effect: effect,
  10986. stop: stop,
  10987. ReactiveEffect: ReactiveEffect,
  10988. effectScope: effectScope,
  10989. EffectScope: EffectScope,
  10990. getCurrentScope: getCurrentScope,
  10991. onScopeDispose: onScopeDispose,
  10992. computed: computed$1,
  10993. watch: watch,
  10994. watchEffect: watchEffect,
  10995. watchPostEffect: watchPostEffect,
  10996. watchSyncEffect: watchSyncEffect,
  10997. onBeforeMount: onBeforeMount,
  10998. onMounted: onMounted,
  10999. onBeforeUpdate: onBeforeUpdate,
  11000. onUpdated: onUpdated,
  11001. onBeforeUnmount: onBeforeUnmount,
  11002. onUnmounted: onUnmounted,
  11003. onActivated: onActivated,
  11004. onDeactivated: onDeactivated,
  11005. onRenderTracked: onRenderTracked,
  11006. onRenderTriggered: onRenderTriggered,
  11007. onErrorCaptured: onErrorCaptured,
  11008. onServerPrefetch: onServerPrefetch,
  11009. provide: provide,
  11010. inject: inject,
  11011. nextTick: nextTick,
  11012. defineComponent: defineComponent,
  11013. defineAsyncComponent: defineAsyncComponent,
  11014. useAttrs: useAttrs,
  11015. useSlots: useSlots,
  11016. defineProps: defineProps,
  11017. defineEmits: defineEmits,
  11018. defineExpose: defineExpose,
  11019. withDefaults: withDefaults,
  11020. mergeDefaults: mergeDefaults,
  11021. createPropsRestProxy: createPropsRestProxy,
  11022. withAsyncContext: withAsyncContext,
  11023. getCurrentInstance: getCurrentInstance,
  11024. h: h,
  11025. createVNode: createVNode,
  11026. cloneVNode: cloneVNode,
  11027. mergeProps: mergeProps,
  11028. isVNode: isVNode,
  11029. Fragment: Fragment,
  11030. Text: Text,
  11031. Comment: Comment,
  11032. Static: Static,
  11033. Teleport: Teleport,
  11034. Suspense: Suspense,
  11035. KeepAlive: KeepAlive,
  11036. BaseTransition: BaseTransition,
  11037. withDirectives: withDirectives,
  11038. useSSRContext: useSSRContext,
  11039. ssrContextKey: ssrContextKey,
  11040. createRenderer: createRenderer,
  11041. createHydrationRenderer: createHydrationRenderer,
  11042. queuePostFlushCb: queuePostFlushCb,
  11043. warn: warn$1,
  11044. handleError: handleError,
  11045. callWithErrorHandling: callWithErrorHandling,
  11046. callWithAsyncErrorHandling: callWithAsyncErrorHandling,
  11047. resolveComponent: resolveComponent,
  11048. resolveDirective: resolveDirective,
  11049. resolveDynamicComponent: resolveDynamicComponent,
  11050. registerRuntimeCompiler: registerRuntimeCompiler,
  11051. isRuntimeOnly: isRuntimeOnly,
  11052. useTransitionState: useTransitionState,
  11053. resolveTransitionHooks: resolveTransitionHooks,
  11054. setTransitionHooks: setTransitionHooks,
  11055. getTransitionRawChildren: getTransitionRawChildren,
  11056. initCustomFormatter: initCustomFormatter,
  11057. get devtools () { return devtools; },
  11058. setDevtoolsHook: setDevtoolsHook,
  11059. withCtx: withCtx,
  11060. pushScopeId: pushScopeId,
  11061. popScopeId: popScopeId,
  11062. withScopeId: withScopeId,
  11063. renderList: renderList,
  11064. toHandlers: toHandlers,
  11065. renderSlot: renderSlot,
  11066. createSlots: createSlots,
  11067. withMemo: withMemo,
  11068. isMemoSame: isMemoSame,
  11069. openBlock: openBlock,
  11070. createBlock: createBlock,
  11071. setBlockTracking: setBlockTracking,
  11072. createTextVNode: createTextVNode,
  11073. createCommentVNode: createCommentVNode,
  11074. createStaticVNode: createStaticVNode,
  11075. createElementVNode: createBaseVNode,
  11076. createElementBlock: createElementBlock,
  11077. guardReactiveProps: guardReactiveProps,
  11078. toDisplayString: toDisplayString,
  11079. camelize: camelize,
  11080. capitalize: capitalize,
  11081. toHandlerKey: toHandlerKey,
  11082. normalizeProps: normalizeProps,
  11083. normalizeClass: normalizeClass,
  11084. normalizeStyle: normalizeStyle,
  11085. transformVNodeArgs: transformVNodeArgs,
  11086. version: version,
  11087. ssrUtils: ssrUtils,
  11088. resolveFilter: resolveFilter,
  11089. compatUtils: compatUtils
  11090. });
  11091. function initDev() {
  11092. {
  11093. {
  11094. console.info(`You are running a development build of Vue.\n` +
  11095. `Make sure to use the production build (*.prod.js) when deploying for production.`);
  11096. }
  11097. initCustomFormatter();
  11098. }
  11099. }
  11100. function defaultOnError(error) {
  11101. throw error;
  11102. }
  11103. function defaultOnWarn(msg) {
  11104. console.warn(`[Vue warn] ${msg.message}`);
  11105. }
  11106. function createCompilerError(code, loc, messages, additionalMessage) {
  11107. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  11108. ;
  11109. const error = new SyntaxError(String(msg));
  11110. error.code = code;
  11111. error.loc = loc;
  11112. return error;
  11113. }
  11114. const errorMessages = {
  11115. // parse errors
  11116. [0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  11117. [1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  11118. [2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  11119. [3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  11120. [4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  11121. [5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  11122. [6 /* ErrorCodes.EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  11123. [7 /* ErrorCodes.EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  11124. [8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  11125. [9 /* ErrorCodes.EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  11126. [10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  11127. [11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  11128. [12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  11129. [13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  11130. [14 /* ErrorCodes.MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  11131. [15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  11132. [16 /* ErrorCodes.NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  11133. [17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  11134. [18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  11135. [19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  11136. [21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  11137. [20 /* ErrorCodes.UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
  11138. [22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  11139. // Vue-specific parse errors
  11140. [23 /* ErrorCodes.X_INVALID_END_TAG */]: 'Invalid end tag.',
  11141. [24 /* ErrorCodes.X_MISSING_END_TAG */]: 'Element is missing end tag.',
  11142. [25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  11143. [27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  11144. 'Note that dynamic directive argument cannot contain spaces.',
  11145. [26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
  11146. // transform errors
  11147. [28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  11148. [29 /* ErrorCodes.X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  11149. [30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
  11150. [31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  11151. [32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  11152. [33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  11153. [34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  11154. [35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  11155. [36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  11156. [37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
  11157. `When there are multiple named slots, all slots should use <template> ` +
  11158. `syntax to avoid scope ambiguity.`,
  11159. [38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  11160. [39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  11161. `default slot. These children will be ignored.`,
  11162. [40 /* ErrorCodes.X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  11163. [41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  11164. [42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  11165. [43 /* ErrorCodes.X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  11166. [44 /* ErrorCodes.X_V_MODEL_ON_PROPS */]: `v-model cannot be used on a prop, because local prop bindings are not writable.\nUse a v-bind binding combined with a v-on listener that emits update:x event instead.`,
  11167. [45 /* ErrorCodes.X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  11168. [46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  11169. // generic errors
  11170. [47 /* ErrorCodes.X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  11171. [48 /* ErrorCodes.X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  11172. [49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  11173. [50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
  11174. // just to fulfill types
  11175. [51 /* ErrorCodes.__EXTEND_POINT__ */]: ``
  11176. };
  11177. const FRAGMENT = Symbol(`Fragment` );
  11178. const TELEPORT = Symbol(`Teleport` );
  11179. const SUSPENSE = Symbol(`Suspense` );
  11180. const KEEP_ALIVE = Symbol(`KeepAlive` );
  11181. const BASE_TRANSITION = Symbol(`BaseTransition` );
  11182. const OPEN_BLOCK = Symbol(`openBlock` );
  11183. const CREATE_BLOCK = Symbol(`createBlock` );
  11184. const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
  11185. const CREATE_VNODE = Symbol(`createVNode` );
  11186. const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
  11187. const CREATE_COMMENT = Symbol(`createCommentVNode` );
  11188. const CREATE_TEXT = Symbol(`createTextVNode` );
  11189. const CREATE_STATIC = Symbol(`createStaticVNode` );
  11190. const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
  11191. const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
  11192. const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
  11193. const RESOLVE_FILTER = Symbol(`resolveFilter` );
  11194. const WITH_DIRECTIVES = Symbol(`withDirectives` );
  11195. const RENDER_LIST = Symbol(`renderList` );
  11196. const RENDER_SLOT = Symbol(`renderSlot` );
  11197. const CREATE_SLOTS = Symbol(`createSlots` );
  11198. const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
  11199. const MERGE_PROPS = Symbol(`mergeProps` );
  11200. const NORMALIZE_CLASS = Symbol(`normalizeClass` );
  11201. const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
  11202. const NORMALIZE_PROPS = Symbol(`normalizeProps` );
  11203. const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
  11204. const TO_HANDLERS = Symbol(`toHandlers` );
  11205. const CAMELIZE = Symbol(`camelize` );
  11206. const CAPITALIZE = Symbol(`capitalize` );
  11207. const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
  11208. const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
  11209. const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
  11210. const POP_SCOPE_ID = Symbol(`popScopeId` );
  11211. const WITH_CTX = Symbol(`withCtx` );
  11212. const UNREF = Symbol(`unref` );
  11213. const IS_REF = Symbol(`isRef` );
  11214. const WITH_MEMO = Symbol(`withMemo` );
  11215. const IS_MEMO_SAME = Symbol(`isMemoSame` );
  11216. // Name mapping for runtime helpers that need to be imported from 'vue' in
  11217. // generated code. Make sure these are correctly exported in the runtime!
  11218. const helperNameMap = {
  11219. [FRAGMENT]: `Fragment`,
  11220. [TELEPORT]: `Teleport`,
  11221. [SUSPENSE]: `Suspense`,
  11222. [KEEP_ALIVE]: `KeepAlive`,
  11223. [BASE_TRANSITION]: `BaseTransition`,
  11224. [OPEN_BLOCK]: `openBlock`,
  11225. [CREATE_BLOCK]: `createBlock`,
  11226. [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
  11227. [CREATE_VNODE]: `createVNode`,
  11228. [CREATE_ELEMENT_VNODE]: `createElementVNode`,
  11229. [CREATE_COMMENT]: `createCommentVNode`,
  11230. [CREATE_TEXT]: `createTextVNode`,
  11231. [CREATE_STATIC]: `createStaticVNode`,
  11232. [RESOLVE_COMPONENT]: `resolveComponent`,
  11233. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  11234. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  11235. [RESOLVE_FILTER]: `resolveFilter`,
  11236. [WITH_DIRECTIVES]: `withDirectives`,
  11237. [RENDER_LIST]: `renderList`,
  11238. [RENDER_SLOT]: `renderSlot`,
  11239. [CREATE_SLOTS]: `createSlots`,
  11240. [TO_DISPLAY_STRING]: `toDisplayString`,
  11241. [MERGE_PROPS]: `mergeProps`,
  11242. [NORMALIZE_CLASS]: `normalizeClass`,
  11243. [NORMALIZE_STYLE]: `normalizeStyle`,
  11244. [NORMALIZE_PROPS]: `normalizeProps`,
  11245. [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
  11246. [TO_HANDLERS]: `toHandlers`,
  11247. [CAMELIZE]: `camelize`,
  11248. [CAPITALIZE]: `capitalize`,
  11249. [TO_HANDLER_KEY]: `toHandlerKey`,
  11250. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  11251. [PUSH_SCOPE_ID]: `pushScopeId`,
  11252. [POP_SCOPE_ID]: `popScopeId`,
  11253. [WITH_CTX]: `withCtx`,
  11254. [UNREF]: `unref`,
  11255. [IS_REF]: `isRef`,
  11256. [WITH_MEMO]: `withMemo`,
  11257. [IS_MEMO_SAME]: `isMemoSame`
  11258. };
  11259. function registerRuntimeHelpers(helpers) {
  11260. Object.getOwnPropertySymbols(helpers).forEach(s => {
  11261. helperNameMap[s] = helpers[s];
  11262. });
  11263. }
  11264. // AST Utilities ---------------------------------------------------------------
  11265. // Some expressions, e.g. sequence and conditional expressions, are never
  11266. // associated with template nodes, so their source locations are just a stub.
  11267. // Container types like CompoundExpression also don't need a real location.
  11268. const locStub = {
  11269. source: '',
  11270. start: { line: 1, column: 1, offset: 0 },
  11271. end: { line: 1, column: 1, offset: 0 }
  11272. };
  11273. function createRoot(children, loc = locStub) {
  11274. return {
  11275. type: 0 /* NodeTypes.ROOT */,
  11276. children,
  11277. helpers: [],
  11278. components: [],
  11279. directives: [],
  11280. hoists: [],
  11281. imports: [],
  11282. cached: 0,
  11283. temps: 0,
  11284. codegenNode: undefined,
  11285. loc
  11286. };
  11287. }
  11288. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
  11289. if (context) {
  11290. if (isBlock) {
  11291. context.helper(OPEN_BLOCK);
  11292. context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
  11293. }
  11294. else {
  11295. context.helper(getVNodeHelper(context.inSSR, isComponent));
  11296. }
  11297. if (directives) {
  11298. context.helper(WITH_DIRECTIVES);
  11299. }
  11300. }
  11301. return {
  11302. type: 13 /* NodeTypes.VNODE_CALL */,
  11303. tag,
  11304. props,
  11305. children,
  11306. patchFlag,
  11307. dynamicProps,
  11308. directives,
  11309. isBlock,
  11310. disableTracking,
  11311. isComponent,
  11312. loc
  11313. };
  11314. }
  11315. function createArrayExpression(elements, loc = locStub) {
  11316. return {
  11317. type: 17 /* NodeTypes.JS_ARRAY_EXPRESSION */,
  11318. loc,
  11319. elements
  11320. };
  11321. }
  11322. function createObjectExpression(properties, loc = locStub) {
  11323. return {
  11324. type: 15 /* NodeTypes.JS_OBJECT_EXPRESSION */,
  11325. loc,
  11326. properties
  11327. };
  11328. }
  11329. function createObjectProperty(key, value) {
  11330. return {
  11331. type: 16 /* NodeTypes.JS_PROPERTY */,
  11332. loc: locStub,
  11333. key: isString(key) ? createSimpleExpression(key, true) : key,
  11334. value
  11335. };
  11336. }
  11337. function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* ConstantTypes.NOT_CONSTANT */) {
  11338. return {
  11339. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  11340. loc,
  11341. content,
  11342. isStatic,
  11343. constType: isStatic ? 3 /* ConstantTypes.CAN_STRINGIFY */ : constType
  11344. };
  11345. }
  11346. function createCompoundExpression(children, loc = locStub) {
  11347. return {
  11348. type: 8 /* NodeTypes.COMPOUND_EXPRESSION */,
  11349. loc,
  11350. children
  11351. };
  11352. }
  11353. function createCallExpression(callee, args = [], loc = locStub) {
  11354. return {
  11355. type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
  11356. loc,
  11357. callee,
  11358. arguments: args
  11359. };
  11360. }
  11361. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  11362. return {
  11363. type: 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */,
  11364. params,
  11365. returns,
  11366. newline,
  11367. isSlot,
  11368. loc
  11369. };
  11370. }
  11371. function createConditionalExpression(test, consequent, alternate, newline = true) {
  11372. return {
  11373. type: 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */,
  11374. test,
  11375. consequent,
  11376. alternate,
  11377. newline,
  11378. loc: locStub
  11379. };
  11380. }
  11381. function createCacheExpression(index, value, isVNode = false) {
  11382. return {
  11383. type: 20 /* NodeTypes.JS_CACHE_EXPRESSION */,
  11384. index,
  11385. value,
  11386. isVNode,
  11387. loc: locStub
  11388. };
  11389. }
  11390. function createBlockStatement(body) {
  11391. return {
  11392. type: 21 /* NodeTypes.JS_BLOCK_STATEMENT */,
  11393. body,
  11394. loc: locStub
  11395. };
  11396. }
  11397. const isStaticExp = (p) => p.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && p.isStatic;
  11398. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  11399. function isCoreComponent(tag) {
  11400. if (isBuiltInType(tag, 'Teleport')) {
  11401. return TELEPORT;
  11402. }
  11403. else if (isBuiltInType(tag, 'Suspense')) {
  11404. return SUSPENSE;
  11405. }
  11406. else if (isBuiltInType(tag, 'KeepAlive')) {
  11407. return KEEP_ALIVE;
  11408. }
  11409. else if (isBuiltInType(tag, 'BaseTransition')) {
  11410. return BASE_TRANSITION;
  11411. }
  11412. }
  11413. const nonIdentifierRE = /^\d|[^\$\w]/;
  11414. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  11415. const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
  11416. const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
  11417. const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
  11418. /**
  11419. * Simple lexer to check if an expression is a member expression. This is
  11420. * lax and only checks validity at the root level (i.e. does not validate exps
  11421. * inside square brackets), but it's ok since these are only used on template
  11422. * expressions and false positives are invalid expressions in the first place.
  11423. */
  11424. const isMemberExpressionBrowser = (path) => {
  11425. // remove whitespaces around . or [ first
  11426. path = path.trim().replace(whitespaceRE, s => s.trim());
  11427. let state = 0 /* MemberExpLexState.inMemberExp */;
  11428. let stateStack = [];
  11429. let currentOpenBracketCount = 0;
  11430. let currentOpenParensCount = 0;
  11431. let currentStringType = null;
  11432. for (let i = 0; i < path.length; i++) {
  11433. const char = path.charAt(i);
  11434. switch (state) {
  11435. case 0 /* MemberExpLexState.inMemberExp */:
  11436. if (char === '[') {
  11437. stateStack.push(state);
  11438. state = 1 /* MemberExpLexState.inBrackets */;
  11439. currentOpenBracketCount++;
  11440. }
  11441. else if (char === '(') {
  11442. stateStack.push(state);
  11443. state = 2 /* MemberExpLexState.inParens */;
  11444. currentOpenParensCount++;
  11445. }
  11446. else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
  11447. return false;
  11448. }
  11449. break;
  11450. case 1 /* MemberExpLexState.inBrackets */:
  11451. if (char === `'` || char === `"` || char === '`') {
  11452. stateStack.push(state);
  11453. state = 3 /* MemberExpLexState.inString */;
  11454. currentStringType = char;
  11455. }
  11456. else if (char === `[`) {
  11457. currentOpenBracketCount++;
  11458. }
  11459. else if (char === `]`) {
  11460. if (!--currentOpenBracketCount) {
  11461. state = stateStack.pop();
  11462. }
  11463. }
  11464. break;
  11465. case 2 /* MemberExpLexState.inParens */:
  11466. if (char === `'` || char === `"` || char === '`') {
  11467. stateStack.push(state);
  11468. state = 3 /* MemberExpLexState.inString */;
  11469. currentStringType = char;
  11470. }
  11471. else if (char === `(`) {
  11472. currentOpenParensCount++;
  11473. }
  11474. else if (char === `)`) {
  11475. // if the exp ends as a call then it should not be considered valid
  11476. if (i === path.length - 1) {
  11477. return false;
  11478. }
  11479. if (!--currentOpenParensCount) {
  11480. state = stateStack.pop();
  11481. }
  11482. }
  11483. break;
  11484. case 3 /* MemberExpLexState.inString */:
  11485. if (char === currentStringType) {
  11486. state = stateStack.pop();
  11487. currentStringType = null;
  11488. }
  11489. break;
  11490. }
  11491. }
  11492. return !currentOpenBracketCount && !currentOpenParensCount;
  11493. };
  11494. const isMemberExpression = isMemberExpressionBrowser
  11495. ;
  11496. function getInnerRange(loc, offset, length) {
  11497. const source = loc.source.slice(offset, offset + length);
  11498. const newLoc = {
  11499. source,
  11500. start: advancePositionWithClone(loc.start, loc.source, offset),
  11501. end: loc.end
  11502. };
  11503. if (length != null) {
  11504. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  11505. }
  11506. return newLoc;
  11507. }
  11508. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  11509. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  11510. }
  11511. // advance by mutation without cloning (for performance reasons), since this
  11512. // gets called a lot in the parser
  11513. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  11514. let linesCount = 0;
  11515. let lastNewLinePos = -1;
  11516. for (let i = 0; i < numberOfCharacters; i++) {
  11517. if (source.charCodeAt(i) === 10 /* newline char code */) {
  11518. linesCount++;
  11519. lastNewLinePos = i;
  11520. }
  11521. }
  11522. pos.offset += numberOfCharacters;
  11523. pos.line += linesCount;
  11524. pos.column =
  11525. lastNewLinePos === -1
  11526. ? pos.column + numberOfCharacters
  11527. : numberOfCharacters - lastNewLinePos;
  11528. return pos;
  11529. }
  11530. function assert(condition, msg) {
  11531. /* istanbul ignore if */
  11532. if (!condition) {
  11533. throw new Error(msg || `unexpected compiler condition`);
  11534. }
  11535. }
  11536. function findDir(node, name, allowEmpty = false) {
  11537. for (let i = 0; i < node.props.length; i++) {
  11538. const p = node.props[i];
  11539. if (p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  11540. (allowEmpty || p.exp) &&
  11541. (isString(name) ? p.name === name : name.test(p.name))) {
  11542. return p;
  11543. }
  11544. }
  11545. }
  11546. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  11547. for (let i = 0; i < node.props.length; i++) {
  11548. const p = node.props[i];
  11549. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  11550. if (dynamicOnly)
  11551. continue;
  11552. if (p.name === name && (p.value || allowEmpty)) {
  11553. return p;
  11554. }
  11555. }
  11556. else if (p.name === 'bind' &&
  11557. (p.exp || allowEmpty) &&
  11558. isStaticArgOf(p.arg, name)) {
  11559. return p;
  11560. }
  11561. }
  11562. }
  11563. function isStaticArgOf(arg, name) {
  11564. return !!(arg && isStaticExp(arg) && arg.content === name);
  11565. }
  11566. function hasDynamicKeyVBind(node) {
  11567. return node.props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  11568. p.name === 'bind' &&
  11569. (!p.arg || // v-bind="obj"
  11570. p.arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  11571. !p.arg.isStatic) // v-bind:[foo]
  11572. );
  11573. }
  11574. function isText(node) {
  11575. return node.type === 5 /* NodeTypes.INTERPOLATION */ || node.type === 2 /* NodeTypes.TEXT */;
  11576. }
  11577. function isVSlot(p) {
  11578. return p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'slot';
  11579. }
  11580. function isTemplateNode(node) {
  11581. return (node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 3 /* ElementTypes.TEMPLATE */);
  11582. }
  11583. function isSlotOutlet(node) {
  11584. return node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 2 /* ElementTypes.SLOT */;
  11585. }
  11586. function getVNodeHelper(ssr, isComponent) {
  11587. return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
  11588. }
  11589. function getVNodeBlockHelper(ssr, isComponent) {
  11590. return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
  11591. }
  11592. const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
  11593. function getUnnormalizedProps(props, callPath = []) {
  11594. if (props &&
  11595. !isString(props) &&
  11596. props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  11597. const callee = props.callee;
  11598. if (!isString(callee) && propsHelperSet.has(callee)) {
  11599. return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
  11600. }
  11601. }
  11602. return [props, callPath];
  11603. }
  11604. function injectProp(node, prop, context) {
  11605. let propsWithInjection;
  11606. /**
  11607. * 1. mergeProps(...)
  11608. * 2. toHandlers(...)
  11609. * 3. normalizeProps(...)
  11610. * 4. normalizeProps(guardReactiveProps(...))
  11611. *
  11612. * we need to get the real props before normalization
  11613. */
  11614. let props = node.type === 13 /* NodeTypes.VNODE_CALL */ ? node.props : node.arguments[2];
  11615. let callPath = [];
  11616. let parentCall;
  11617. if (props &&
  11618. !isString(props) &&
  11619. props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  11620. const ret = getUnnormalizedProps(props);
  11621. props = ret[0];
  11622. callPath = ret[1];
  11623. parentCall = callPath[callPath.length - 1];
  11624. }
  11625. if (props == null || isString(props)) {
  11626. propsWithInjection = createObjectExpression([prop]);
  11627. }
  11628. else if (props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  11629. // merged props... add ours
  11630. // only inject key to object literal if it's the first argument so that
  11631. // if doesn't override user provided keys
  11632. const first = props.arguments[0];
  11633. if (!isString(first) && first.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  11634. // #6631
  11635. if (!hasProp(prop, first)) {
  11636. first.properties.unshift(prop);
  11637. }
  11638. }
  11639. else {
  11640. if (props.callee === TO_HANDLERS) {
  11641. // #2366
  11642. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  11643. createObjectExpression([prop]),
  11644. props
  11645. ]);
  11646. }
  11647. else {
  11648. props.arguments.unshift(createObjectExpression([prop]));
  11649. }
  11650. }
  11651. !propsWithInjection && (propsWithInjection = props);
  11652. }
  11653. else if (props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  11654. if (!hasProp(prop, props)) {
  11655. props.properties.unshift(prop);
  11656. }
  11657. propsWithInjection = props;
  11658. }
  11659. else {
  11660. // single v-bind with expression, return a merged replacement
  11661. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  11662. createObjectExpression([prop]),
  11663. props
  11664. ]);
  11665. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
  11666. // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
  11667. // the `guardReactiveProps` will no longer be needed
  11668. if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
  11669. parentCall = callPath[callPath.length - 2];
  11670. }
  11671. }
  11672. if (node.type === 13 /* NodeTypes.VNODE_CALL */) {
  11673. if (parentCall) {
  11674. parentCall.arguments[0] = propsWithInjection;
  11675. }
  11676. else {
  11677. node.props = propsWithInjection;
  11678. }
  11679. }
  11680. else {
  11681. if (parentCall) {
  11682. parentCall.arguments[0] = propsWithInjection;
  11683. }
  11684. else {
  11685. node.arguments[2] = propsWithInjection;
  11686. }
  11687. }
  11688. }
  11689. // check existing key to avoid overriding user provided keys
  11690. function hasProp(prop, props) {
  11691. let result = false;
  11692. if (prop.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  11693. const propKeyName = prop.key.content;
  11694. result = props.properties.some(p => p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  11695. p.key.content === propKeyName);
  11696. }
  11697. return result;
  11698. }
  11699. function toValidAssetId(name, type) {
  11700. // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
  11701. return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
  11702. return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
  11703. })}`;
  11704. }
  11705. function getMemoedVNodeCall(node) {
  11706. if (node.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
  11707. return node.arguments[1].returns;
  11708. }
  11709. else {
  11710. return node;
  11711. }
  11712. }
  11713. function makeBlock(node, { helper, removeHelper, inSSR }) {
  11714. if (!node.isBlock) {
  11715. node.isBlock = true;
  11716. removeHelper(getVNodeHelper(inSSR, node.isComponent));
  11717. helper(OPEN_BLOCK);
  11718. helper(getVNodeBlockHelper(inSSR, node.isComponent));
  11719. }
  11720. }
  11721. const deprecationData = {
  11722. ["COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */]: {
  11723. message: `Platform-native elements with "is" prop will no longer be ` +
  11724. `treated as components in Vue 3 unless the "is" value is explicitly ` +
  11725. `prefixed with "vue:".`,
  11726. link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
  11727. },
  11728. ["COMPILER_V_BIND_SYNC" /* CompilerDeprecationTypes.COMPILER_V_BIND_SYNC */]: {
  11729. message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
  11730. `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
  11731. `\`v-model:${key}\`.`,
  11732. link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
  11733. },
  11734. ["COMPILER_V_BIND_PROP" /* CompilerDeprecationTypes.COMPILER_V_BIND_PROP */]: {
  11735. message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
  11736. `Vue 3 will automatically set a binding as DOM property when appropriate.`
  11737. },
  11738. ["COMPILER_V_BIND_OBJECT_ORDER" /* CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER */]: {
  11739. message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
  11740. `object spread: it will now overwrite an existing non-mergeable attribute ` +
  11741. `that appears before v-bind in the case of conflict. ` +
  11742. `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
  11743. `You can also suppress this warning if the usage is intended.`,
  11744. link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
  11745. },
  11746. ["COMPILER_V_ON_NATIVE" /* CompilerDeprecationTypes.COMPILER_V_ON_NATIVE */]: {
  11747. message: `.native modifier for v-on has been removed as is no longer necessary.`,
  11748. link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
  11749. },
  11750. ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* CompilerDeprecationTypes.COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
  11751. message: `v-if / v-for precedence when used on the same element has changed ` +
  11752. `in Vue 3: v-if now takes higher precedence and will no longer have ` +
  11753. `access to v-for scope variables. It is best to avoid the ambiguity ` +
  11754. `with <template> tags or use a computed property that filters v-for ` +
  11755. `data source.`,
  11756. link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
  11757. },
  11758. ["COMPILER_NATIVE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_NATIVE_TEMPLATE */]: {
  11759. message: `<template> with no special directives will render as a native template ` +
  11760. `element instead of its inner content in Vue 3.`
  11761. },
  11762. ["COMPILER_INLINE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_INLINE_TEMPLATE */]: {
  11763. message: `"inline-template" has been removed in Vue 3.`,
  11764. link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
  11765. },
  11766. ["COMPILER_FILTER" /* CompilerDeprecationTypes.COMPILER_FILTERS */]: {
  11767. message: `filters have been removed in Vue 3. ` +
  11768. `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
  11769. `Use method calls or computed properties instead.`,
  11770. link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
  11771. }
  11772. };
  11773. function getCompatValue(key, context) {
  11774. const config = context.options
  11775. ? context.options.compatConfig
  11776. : context.compatConfig;
  11777. const value = config && config[key];
  11778. if (key === 'MODE') {
  11779. return value || 3; // compiler defaults to v3 behavior
  11780. }
  11781. else {
  11782. return value;
  11783. }
  11784. }
  11785. function isCompatEnabled(key, context) {
  11786. const mode = getCompatValue('MODE', context);
  11787. const value = getCompatValue(key, context);
  11788. // in v3 mode, only enable if explicitly set to true
  11789. // otherwise enable for any non-false value
  11790. return mode === 3 ? value === true : value !== false;
  11791. }
  11792. function checkCompatEnabled(key, context, loc, ...args) {
  11793. const enabled = isCompatEnabled(key, context);
  11794. if (enabled) {
  11795. warnDeprecation(key, context, loc, ...args);
  11796. }
  11797. return enabled;
  11798. }
  11799. function warnDeprecation(key, context, loc, ...args) {
  11800. const val = getCompatValue(key, context);
  11801. if (val === 'suppress-warning') {
  11802. return;
  11803. }
  11804. const { message, link } = deprecationData[key];
  11805. const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
  11806. const err = new SyntaxError(msg);
  11807. err.code = key;
  11808. if (loc)
  11809. err.loc = loc;
  11810. context.onWarn(err);
  11811. }
  11812. // The default decoder only provides escapes for characters reserved as part of
  11813. // the template syntax, and is only used if the custom renderer did not provide
  11814. // a platform-specific decoder.
  11815. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  11816. const decodeMap = {
  11817. gt: '>',
  11818. lt: '<',
  11819. amp: '&',
  11820. apos: "'",
  11821. quot: '"'
  11822. };
  11823. const defaultParserOptions = {
  11824. delimiters: [`{{`, `}}`],
  11825. getNamespace: () => 0 /* Namespaces.HTML */,
  11826. getTextMode: () => 0 /* TextModes.DATA */,
  11827. isVoidTag: NO,
  11828. isPreTag: NO,
  11829. isCustomElement: NO,
  11830. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  11831. onError: defaultOnError,
  11832. onWarn: defaultOnWarn,
  11833. comments: true
  11834. };
  11835. function baseParse(content, options = {}) {
  11836. const context = createParserContext(content, options);
  11837. const start = getCursor(context);
  11838. return createRoot(parseChildren(context, 0 /* TextModes.DATA */, []), getSelection(context, start));
  11839. }
  11840. function createParserContext(content, rawOptions) {
  11841. const options = extend({}, defaultParserOptions);
  11842. let key;
  11843. for (key in rawOptions) {
  11844. // @ts-ignore
  11845. options[key] =
  11846. rawOptions[key] === undefined
  11847. ? defaultParserOptions[key]
  11848. : rawOptions[key];
  11849. }
  11850. return {
  11851. options,
  11852. column: 1,
  11853. line: 1,
  11854. offset: 0,
  11855. originalSource: content,
  11856. source: content,
  11857. inPre: false,
  11858. inVPre: false,
  11859. onWarn: options.onWarn
  11860. };
  11861. }
  11862. function parseChildren(context, mode, ancestors) {
  11863. const parent = last(ancestors);
  11864. const ns = parent ? parent.ns : 0 /* Namespaces.HTML */;
  11865. const nodes = [];
  11866. while (!isEnd(context, mode, ancestors)) {
  11867. const s = context.source;
  11868. let node = undefined;
  11869. if (mode === 0 /* TextModes.DATA */ || mode === 1 /* TextModes.RCDATA */) {
  11870. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  11871. // '{{'
  11872. node = parseInterpolation(context, mode);
  11873. }
  11874. else if (mode === 0 /* TextModes.DATA */ && s[0] === '<') {
  11875. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  11876. if (s.length === 1) {
  11877. emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 1);
  11878. }
  11879. else if (s[1] === '!') {
  11880. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  11881. if (startsWith(s, '<!--')) {
  11882. node = parseComment(context);
  11883. }
  11884. else if (startsWith(s, '<!DOCTYPE')) {
  11885. // Ignore DOCTYPE by a limitation.
  11886. node = parseBogusComment(context);
  11887. }
  11888. else if (startsWith(s, '<![CDATA[')) {
  11889. if (ns !== 0 /* Namespaces.HTML */) {
  11890. node = parseCDATA(context, ancestors);
  11891. }
  11892. else {
  11893. emitError(context, 1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */);
  11894. node = parseBogusComment(context);
  11895. }
  11896. }
  11897. else {
  11898. emitError(context, 11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */);
  11899. node = parseBogusComment(context);
  11900. }
  11901. }
  11902. else if (s[1] === '/') {
  11903. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  11904. if (s.length === 2) {
  11905. emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 2);
  11906. }
  11907. else if (s[2] === '>') {
  11908. emitError(context, 14 /* ErrorCodes.MISSING_END_TAG_NAME */, 2);
  11909. advanceBy(context, 3);
  11910. continue;
  11911. }
  11912. else if (/[a-z]/i.test(s[2])) {
  11913. emitError(context, 23 /* ErrorCodes.X_INVALID_END_TAG */);
  11914. parseTag(context, 1 /* TagType.End */, parent);
  11915. continue;
  11916. }
  11917. else {
  11918. emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  11919. node = parseBogusComment(context);
  11920. }
  11921. }
  11922. else if (/[a-z]/i.test(s[1])) {
  11923. node = parseElement(context, ancestors);
  11924. }
  11925. else if (s[1] === '?') {
  11926. emitError(context, 21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  11927. node = parseBogusComment(context);
  11928. }
  11929. else {
  11930. emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  11931. }
  11932. }
  11933. }
  11934. if (!node) {
  11935. node = parseText(context, mode);
  11936. }
  11937. if (isArray(node)) {
  11938. for (let i = 0; i < node.length; i++) {
  11939. pushNode(nodes, node[i]);
  11940. }
  11941. }
  11942. else {
  11943. pushNode(nodes, node);
  11944. }
  11945. }
  11946. // Whitespace handling strategy like v2
  11947. let removedWhitespace = false;
  11948. if (mode !== 2 /* TextModes.RAWTEXT */ && mode !== 1 /* TextModes.RCDATA */) {
  11949. const shouldCondense = context.options.whitespace !== 'preserve';
  11950. for (let i = 0; i < nodes.length; i++) {
  11951. const node = nodes[i];
  11952. if (node.type === 2 /* NodeTypes.TEXT */) {
  11953. if (!context.inPre) {
  11954. if (!/[^\t\r\n\f ]/.test(node.content)) {
  11955. const prev = nodes[i - 1];
  11956. const next = nodes[i + 1];
  11957. // Remove if:
  11958. // - the whitespace is the first or last node, or:
  11959. // - (condense mode) the whitespace is between twos comments, or:
  11960. // - (condense mode) the whitespace is between comment and element, or:
  11961. // - (condense mode) the whitespace is between two elements AND contains newline
  11962. if (!prev ||
  11963. !next ||
  11964. (shouldCondense &&
  11965. ((prev.type === 3 /* NodeTypes.COMMENT */ &&
  11966. next.type === 3 /* NodeTypes.COMMENT */) ||
  11967. (prev.type === 3 /* NodeTypes.COMMENT */ &&
  11968. next.type === 1 /* NodeTypes.ELEMENT */) ||
  11969. (prev.type === 1 /* NodeTypes.ELEMENT */ &&
  11970. next.type === 3 /* NodeTypes.COMMENT */) ||
  11971. (prev.type === 1 /* NodeTypes.ELEMENT */ &&
  11972. next.type === 1 /* NodeTypes.ELEMENT */ &&
  11973. /[\r\n]/.test(node.content))))) {
  11974. removedWhitespace = true;
  11975. nodes[i] = null;
  11976. }
  11977. else {
  11978. // Otherwise, the whitespace is condensed into a single space
  11979. node.content = ' ';
  11980. }
  11981. }
  11982. else if (shouldCondense) {
  11983. // in condense mode, consecutive whitespaces in text are condensed
  11984. // down to a single space.
  11985. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  11986. }
  11987. }
  11988. else {
  11989. // #6410 normalize windows newlines in <pre>:
  11990. // in SSR, browsers normalize server-rendered \r\n into a single \n
  11991. // in the DOM
  11992. node.content = node.content.replace(/\r\n/g, '\n');
  11993. }
  11994. }
  11995. // Remove comment nodes if desired by configuration.
  11996. else if (node.type === 3 /* NodeTypes.COMMENT */ && !context.options.comments) {
  11997. removedWhitespace = true;
  11998. nodes[i] = null;
  11999. }
  12000. }
  12001. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  12002. // remove leading newline per html spec
  12003. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  12004. const first = nodes[0];
  12005. if (first && first.type === 2 /* NodeTypes.TEXT */) {
  12006. first.content = first.content.replace(/^\r?\n/, '');
  12007. }
  12008. }
  12009. }
  12010. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  12011. }
  12012. function pushNode(nodes, node) {
  12013. if (node.type === 2 /* NodeTypes.TEXT */) {
  12014. const prev = last(nodes);
  12015. // Merge if both this and the previous node are text and those are
  12016. // consecutive. This happens for cases like "a < b".
  12017. if (prev &&
  12018. prev.type === 2 /* NodeTypes.TEXT */ &&
  12019. prev.loc.end.offset === node.loc.start.offset) {
  12020. prev.content += node.content;
  12021. prev.loc.end = node.loc.end;
  12022. prev.loc.source += node.loc.source;
  12023. return;
  12024. }
  12025. }
  12026. nodes.push(node);
  12027. }
  12028. function parseCDATA(context, ancestors) {
  12029. advanceBy(context, 9);
  12030. const nodes = parseChildren(context, 3 /* TextModes.CDATA */, ancestors);
  12031. if (context.source.length === 0) {
  12032. emitError(context, 6 /* ErrorCodes.EOF_IN_CDATA */);
  12033. }
  12034. else {
  12035. advanceBy(context, 3);
  12036. }
  12037. return nodes;
  12038. }
  12039. function parseComment(context) {
  12040. const start = getCursor(context);
  12041. let content;
  12042. // Regular comment.
  12043. const match = /--(\!)?>/.exec(context.source);
  12044. if (!match) {
  12045. content = context.source.slice(4);
  12046. advanceBy(context, context.source.length);
  12047. emitError(context, 7 /* ErrorCodes.EOF_IN_COMMENT */);
  12048. }
  12049. else {
  12050. if (match.index <= 3) {
  12051. emitError(context, 0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  12052. }
  12053. if (match[1]) {
  12054. emitError(context, 10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */);
  12055. }
  12056. content = context.source.slice(4, match.index);
  12057. // Advancing with reporting nested comments.
  12058. const s = context.source.slice(0, match.index);
  12059. let prevIndex = 1, nestedIndex = 0;
  12060. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  12061. advanceBy(context, nestedIndex - prevIndex + 1);
  12062. if (nestedIndex + 4 < s.length) {
  12063. emitError(context, 16 /* ErrorCodes.NESTED_COMMENT */);
  12064. }
  12065. prevIndex = nestedIndex + 1;
  12066. }
  12067. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  12068. }
  12069. return {
  12070. type: 3 /* NodeTypes.COMMENT */,
  12071. content,
  12072. loc: getSelection(context, start)
  12073. };
  12074. }
  12075. function parseBogusComment(context) {
  12076. const start = getCursor(context);
  12077. const contentStart = context.source[1] === '?' ? 1 : 2;
  12078. let content;
  12079. const closeIndex = context.source.indexOf('>');
  12080. if (closeIndex === -1) {
  12081. content = context.source.slice(contentStart);
  12082. advanceBy(context, context.source.length);
  12083. }
  12084. else {
  12085. content = context.source.slice(contentStart, closeIndex);
  12086. advanceBy(context, closeIndex + 1);
  12087. }
  12088. return {
  12089. type: 3 /* NodeTypes.COMMENT */,
  12090. content,
  12091. loc: getSelection(context, start)
  12092. };
  12093. }
  12094. function parseElement(context, ancestors) {
  12095. // Start tag.
  12096. const wasInPre = context.inPre;
  12097. const wasInVPre = context.inVPre;
  12098. const parent = last(ancestors);
  12099. const element = parseTag(context, 0 /* TagType.Start */, parent);
  12100. const isPreBoundary = context.inPre && !wasInPre;
  12101. const isVPreBoundary = context.inVPre && !wasInVPre;
  12102. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  12103. // #4030 self-closing <pre> tag
  12104. if (isPreBoundary) {
  12105. context.inPre = false;
  12106. }
  12107. if (isVPreBoundary) {
  12108. context.inVPre = false;
  12109. }
  12110. return element;
  12111. }
  12112. // Children.
  12113. ancestors.push(element);
  12114. const mode = context.options.getTextMode(element, parent);
  12115. const children = parseChildren(context, mode, ancestors);
  12116. ancestors.pop();
  12117. element.children = children;
  12118. // End tag.
  12119. if (startsWithEndTagOpen(context.source, element.tag)) {
  12120. parseTag(context, 1 /* TagType.End */, parent);
  12121. }
  12122. else {
  12123. emitError(context, 24 /* ErrorCodes.X_MISSING_END_TAG */, 0, element.loc.start);
  12124. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  12125. const first = children[0];
  12126. if (first && startsWith(first.loc.source, '<!--')) {
  12127. emitError(context, 8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  12128. }
  12129. }
  12130. }
  12131. element.loc = getSelection(context, element.loc.start);
  12132. if (isPreBoundary) {
  12133. context.inPre = false;
  12134. }
  12135. if (isVPreBoundary) {
  12136. context.inVPre = false;
  12137. }
  12138. return element;
  12139. }
  12140. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  12141. function parseTag(context, type, parent) {
  12142. // Tag open.
  12143. const start = getCursor(context);
  12144. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  12145. const tag = match[1];
  12146. const ns = context.options.getNamespace(tag, parent);
  12147. advanceBy(context, match[0].length);
  12148. advanceSpaces(context);
  12149. // save current state in case we need to re-parse attributes with v-pre
  12150. const cursor = getCursor(context);
  12151. const currentSource = context.source;
  12152. // check <pre> tag
  12153. if (context.options.isPreTag(tag)) {
  12154. context.inPre = true;
  12155. }
  12156. // Attributes.
  12157. let props = parseAttributes(context, type);
  12158. // check v-pre
  12159. if (type === 0 /* TagType.Start */ &&
  12160. !context.inVPre &&
  12161. props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'pre')) {
  12162. context.inVPre = true;
  12163. // reset context
  12164. extend(context, cursor);
  12165. context.source = currentSource;
  12166. // re-parse attrs and filter out v-pre itself
  12167. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  12168. }
  12169. // Tag close.
  12170. let isSelfClosing = false;
  12171. if (context.source.length === 0) {
  12172. emitError(context, 9 /* ErrorCodes.EOF_IN_TAG */);
  12173. }
  12174. else {
  12175. isSelfClosing = startsWith(context.source, '/>');
  12176. if (type === 1 /* TagType.End */ && isSelfClosing) {
  12177. emitError(context, 4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */);
  12178. }
  12179. advanceBy(context, isSelfClosing ? 2 : 1);
  12180. }
  12181. if (type === 1 /* TagType.End */) {
  12182. return;
  12183. }
  12184. let tagType = 0 /* ElementTypes.ELEMENT */;
  12185. if (!context.inVPre) {
  12186. if (tag === 'slot') {
  12187. tagType = 2 /* ElementTypes.SLOT */;
  12188. }
  12189. else if (tag === 'template') {
  12190. if (props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
  12191. tagType = 3 /* ElementTypes.TEMPLATE */;
  12192. }
  12193. }
  12194. else if (isComponent(tag, props, context)) {
  12195. tagType = 1 /* ElementTypes.COMPONENT */;
  12196. }
  12197. }
  12198. return {
  12199. type: 1 /* NodeTypes.ELEMENT */,
  12200. ns,
  12201. tag,
  12202. tagType,
  12203. props,
  12204. isSelfClosing,
  12205. children: [],
  12206. loc: getSelection(context, start),
  12207. codegenNode: undefined // to be created during transform phase
  12208. };
  12209. }
  12210. function isComponent(tag, props, context) {
  12211. const options = context.options;
  12212. if (options.isCustomElement(tag)) {
  12213. return false;
  12214. }
  12215. if (tag === 'component' ||
  12216. /^[A-Z]/.test(tag) ||
  12217. isCoreComponent(tag) ||
  12218. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  12219. (options.isNativeTag && !options.isNativeTag(tag))) {
  12220. return true;
  12221. }
  12222. // at this point the tag should be a native tag, but check for potential "is"
  12223. // casting
  12224. for (let i = 0; i < props.length; i++) {
  12225. const p = props[i];
  12226. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  12227. if (p.name === 'is' && p.value) {
  12228. if (p.value.content.startsWith('vue:')) {
  12229. return true;
  12230. }
  12231. }
  12232. }
  12233. else {
  12234. // directive
  12235. // v-is (TODO Deprecate)
  12236. if (p.name === 'is') {
  12237. return true;
  12238. }
  12239. else if (
  12240. // :is on plain element - only treat as component in compat mode
  12241. p.name === 'bind' &&
  12242. isStaticArgOf(p.arg, 'is') &&
  12243. false &&
  12244. checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
  12245. return true;
  12246. }
  12247. }
  12248. }
  12249. }
  12250. function parseAttributes(context, type) {
  12251. const props = [];
  12252. const attributeNames = new Set();
  12253. while (context.source.length > 0 &&
  12254. !startsWith(context.source, '>') &&
  12255. !startsWith(context.source, '/>')) {
  12256. if (startsWith(context.source, '/')) {
  12257. emitError(context, 22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */);
  12258. advanceBy(context, 1);
  12259. advanceSpaces(context);
  12260. continue;
  12261. }
  12262. if (type === 1 /* TagType.End */) {
  12263. emitError(context, 3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */);
  12264. }
  12265. const attr = parseAttribute(context, attributeNames);
  12266. // Trim whitespace between class
  12267. // https://github.com/vuejs/core/issues/4251
  12268. if (attr.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  12269. attr.value &&
  12270. attr.name === 'class') {
  12271. attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
  12272. }
  12273. if (type === 0 /* TagType.Start */) {
  12274. props.push(attr);
  12275. }
  12276. if (/^[^\t\r\n\f />]/.test(context.source)) {
  12277. emitError(context, 15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  12278. }
  12279. advanceSpaces(context);
  12280. }
  12281. return props;
  12282. }
  12283. function parseAttribute(context, nameSet) {
  12284. // Name.
  12285. const start = getCursor(context);
  12286. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  12287. const name = match[0];
  12288. if (nameSet.has(name)) {
  12289. emitError(context, 2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */);
  12290. }
  12291. nameSet.add(name);
  12292. if (name[0] === '=') {
  12293. emitError(context, 19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  12294. }
  12295. {
  12296. const pattern = /["'<]/g;
  12297. let m;
  12298. while ((m = pattern.exec(name))) {
  12299. emitError(context, 17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  12300. }
  12301. }
  12302. advanceBy(context, name.length);
  12303. // Value
  12304. let value = undefined;
  12305. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  12306. advanceSpaces(context);
  12307. advanceBy(context, 1);
  12308. advanceSpaces(context);
  12309. value = parseAttributeValue(context);
  12310. if (!value) {
  12311. emitError(context, 13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */);
  12312. }
  12313. }
  12314. const loc = getSelection(context, start);
  12315. if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
  12316. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  12317. let isPropShorthand = startsWith(name, '.');
  12318. let dirName = match[1] ||
  12319. (isPropShorthand || startsWith(name, ':')
  12320. ? 'bind'
  12321. : startsWith(name, '@')
  12322. ? 'on'
  12323. : 'slot');
  12324. let arg;
  12325. if (match[2]) {
  12326. const isSlot = dirName === 'slot';
  12327. const startOffset = name.lastIndexOf(match[2]);
  12328. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  12329. let content = match[2];
  12330. let isStatic = true;
  12331. if (content.startsWith('[')) {
  12332. isStatic = false;
  12333. if (!content.endsWith(']')) {
  12334. emitError(context, 27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  12335. content = content.slice(1);
  12336. }
  12337. else {
  12338. content = content.slice(1, content.length - 1);
  12339. }
  12340. }
  12341. else if (isSlot) {
  12342. // #1241 special case for v-slot: vuetify relies extensively on slot
  12343. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  12344. // supports such usage so we are keeping it consistent with 2.x.
  12345. content += match[3] || '';
  12346. }
  12347. arg = {
  12348. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  12349. content,
  12350. isStatic,
  12351. constType: isStatic
  12352. ? 3 /* ConstantTypes.CAN_STRINGIFY */
  12353. : 0 /* ConstantTypes.NOT_CONSTANT */,
  12354. loc
  12355. };
  12356. }
  12357. if (value && value.isQuoted) {
  12358. const valueLoc = value.loc;
  12359. valueLoc.start.offset++;
  12360. valueLoc.start.column++;
  12361. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  12362. valueLoc.source = valueLoc.source.slice(1, -1);
  12363. }
  12364. const modifiers = match[3] ? match[3].slice(1).split('.') : [];
  12365. if (isPropShorthand)
  12366. modifiers.push('prop');
  12367. return {
  12368. type: 7 /* NodeTypes.DIRECTIVE */,
  12369. name: dirName,
  12370. exp: value && {
  12371. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  12372. content: value.content,
  12373. isStatic: false,
  12374. // Treat as non-constant by default. This can be potentially set to
  12375. // other values by `transformExpression` to make it eligible for hoisting.
  12376. constType: 0 /* ConstantTypes.NOT_CONSTANT */,
  12377. loc: value.loc
  12378. },
  12379. arg,
  12380. modifiers,
  12381. loc
  12382. };
  12383. }
  12384. // missing directive name or illegal directive name
  12385. if (!context.inVPre && startsWith(name, 'v-')) {
  12386. emitError(context, 26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */);
  12387. }
  12388. return {
  12389. type: 6 /* NodeTypes.ATTRIBUTE */,
  12390. name,
  12391. value: value && {
  12392. type: 2 /* NodeTypes.TEXT */,
  12393. content: value.content,
  12394. loc: value.loc
  12395. },
  12396. loc
  12397. };
  12398. }
  12399. function parseAttributeValue(context) {
  12400. const start = getCursor(context);
  12401. let content;
  12402. const quote = context.source[0];
  12403. const isQuoted = quote === `"` || quote === `'`;
  12404. if (isQuoted) {
  12405. // Quoted value.
  12406. advanceBy(context, 1);
  12407. const endIndex = context.source.indexOf(quote);
  12408. if (endIndex === -1) {
  12409. content = parseTextData(context, context.source.length, 4 /* TextModes.ATTRIBUTE_VALUE */);
  12410. }
  12411. else {
  12412. content = parseTextData(context, endIndex, 4 /* TextModes.ATTRIBUTE_VALUE */);
  12413. advanceBy(context, 1);
  12414. }
  12415. }
  12416. else {
  12417. // Unquoted
  12418. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  12419. if (!match) {
  12420. return undefined;
  12421. }
  12422. const unexpectedChars = /["'<=`]/g;
  12423. let m;
  12424. while ((m = unexpectedChars.exec(match[0]))) {
  12425. emitError(context, 18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  12426. }
  12427. content = parseTextData(context, match[0].length, 4 /* TextModes.ATTRIBUTE_VALUE */);
  12428. }
  12429. return { content, isQuoted, loc: getSelection(context, start) };
  12430. }
  12431. function parseInterpolation(context, mode) {
  12432. const [open, close] = context.options.delimiters;
  12433. const closeIndex = context.source.indexOf(close, open.length);
  12434. if (closeIndex === -1) {
  12435. emitError(context, 25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */);
  12436. return undefined;
  12437. }
  12438. const start = getCursor(context);
  12439. advanceBy(context, open.length);
  12440. const innerStart = getCursor(context);
  12441. const innerEnd = getCursor(context);
  12442. const rawContentLength = closeIndex - open.length;
  12443. const rawContent = context.source.slice(0, rawContentLength);
  12444. const preTrimContent = parseTextData(context, rawContentLength, mode);
  12445. const content = preTrimContent.trim();
  12446. const startOffset = preTrimContent.indexOf(content);
  12447. if (startOffset > 0) {
  12448. advancePositionWithMutation(innerStart, rawContent, startOffset);
  12449. }
  12450. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  12451. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  12452. advanceBy(context, close.length);
  12453. return {
  12454. type: 5 /* NodeTypes.INTERPOLATION */,
  12455. content: {
  12456. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  12457. isStatic: false,
  12458. // Set `isConstant` to false by default and will decide in transformExpression
  12459. constType: 0 /* ConstantTypes.NOT_CONSTANT */,
  12460. content,
  12461. loc: getSelection(context, innerStart, innerEnd)
  12462. },
  12463. loc: getSelection(context, start)
  12464. };
  12465. }
  12466. function parseText(context, mode) {
  12467. const endTokens = mode === 3 /* TextModes.CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
  12468. let endIndex = context.source.length;
  12469. for (let i = 0; i < endTokens.length; i++) {
  12470. const index = context.source.indexOf(endTokens[i], 1);
  12471. if (index !== -1 && endIndex > index) {
  12472. endIndex = index;
  12473. }
  12474. }
  12475. const start = getCursor(context);
  12476. const content = parseTextData(context, endIndex, mode);
  12477. return {
  12478. type: 2 /* NodeTypes.TEXT */,
  12479. content,
  12480. loc: getSelection(context, start)
  12481. };
  12482. }
  12483. /**
  12484. * Get text data with a given length from the current location.
  12485. * This translates HTML entities in the text data.
  12486. */
  12487. function parseTextData(context, length, mode) {
  12488. const rawText = context.source.slice(0, length);
  12489. advanceBy(context, length);
  12490. if (mode === 2 /* TextModes.RAWTEXT */ ||
  12491. mode === 3 /* TextModes.CDATA */ ||
  12492. !rawText.includes('&')) {
  12493. return rawText;
  12494. }
  12495. else {
  12496. // DATA or RCDATA containing "&"". Entity decoding required.
  12497. return context.options.decodeEntities(rawText, mode === 4 /* TextModes.ATTRIBUTE_VALUE */);
  12498. }
  12499. }
  12500. function getCursor(context) {
  12501. const { column, line, offset } = context;
  12502. return { column, line, offset };
  12503. }
  12504. function getSelection(context, start, end) {
  12505. end = end || getCursor(context);
  12506. return {
  12507. start,
  12508. end,
  12509. source: context.originalSource.slice(start.offset, end.offset)
  12510. };
  12511. }
  12512. function last(xs) {
  12513. return xs[xs.length - 1];
  12514. }
  12515. function startsWith(source, searchString) {
  12516. return source.startsWith(searchString);
  12517. }
  12518. function advanceBy(context, numberOfCharacters) {
  12519. const { source } = context;
  12520. advancePositionWithMutation(context, source, numberOfCharacters);
  12521. context.source = source.slice(numberOfCharacters);
  12522. }
  12523. function advanceSpaces(context) {
  12524. const match = /^[\t\r\n\f ]+/.exec(context.source);
  12525. if (match) {
  12526. advanceBy(context, match[0].length);
  12527. }
  12528. }
  12529. function getNewPosition(context, start, numberOfCharacters) {
  12530. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  12531. }
  12532. function emitError(context, code, offset, loc = getCursor(context)) {
  12533. if (offset) {
  12534. loc.offset += offset;
  12535. loc.column += offset;
  12536. }
  12537. context.options.onError(createCompilerError(code, {
  12538. start: loc,
  12539. end: loc,
  12540. source: ''
  12541. }));
  12542. }
  12543. function isEnd(context, mode, ancestors) {
  12544. const s = context.source;
  12545. switch (mode) {
  12546. case 0 /* TextModes.DATA */:
  12547. if (startsWith(s, '</')) {
  12548. // TODO: probably bad performance
  12549. for (let i = ancestors.length - 1; i >= 0; --i) {
  12550. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  12551. return true;
  12552. }
  12553. }
  12554. }
  12555. break;
  12556. case 1 /* TextModes.RCDATA */:
  12557. case 2 /* TextModes.RAWTEXT */: {
  12558. const parent = last(ancestors);
  12559. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  12560. return true;
  12561. }
  12562. break;
  12563. }
  12564. case 3 /* TextModes.CDATA */:
  12565. if (startsWith(s, ']]>')) {
  12566. return true;
  12567. }
  12568. break;
  12569. }
  12570. return !s;
  12571. }
  12572. function startsWithEndTagOpen(source, tag) {
  12573. return (startsWith(source, '</') &&
  12574. source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
  12575. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  12576. }
  12577. function hoistStatic(root, context) {
  12578. walk(root, context,
  12579. // Root node is unfortunately non-hoistable due to potential parent
  12580. // fallthrough attributes.
  12581. isSingleElementRoot(root, root.children[0]));
  12582. }
  12583. function isSingleElementRoot(root, child) {
  12584. const { children } = root;
  12585. return (children.length === 1 &&
  12586. child.type === 1 /* NodeTypes.ELEMENT */ &&
  12587. !isSlotOutlet(child));
  12588. }
  12589. function walk(node, context, doNotHoistNode = false) {
  12590. const { children } = node;
  12591. const originalCount = children.length;
  12592. let hoistedCount = 0;
  12593. for (let i = 0; i < children.length; i++) {
  12594. const child = children[i];
  12595. // only plain elements & text calls are eligible for hoisting.
  12596. if (child.type === 1 /* NodeTypes.ELEMENT */ &&
  12597. child.tagType === 0 /* ElementTypes.ELEMENT */) {
  12598. const constantType = doNotHoistNode
  12599. ? 0 /* ConstantTypes.NOT_CONSTANT */
  12600. : getConstantType(child, context);
  12601. if (constantType > 0 /* ConstantTypes.NOT_CONSTANT */) {
  12602. if (constantType >= 2 /* ConstantTypes.CAN_HOIST */) {
  12603. child.codegenNode.patchFlag =
  12604. -1 /* PatchFlags.HOISTED */ + (` /* HOISTED */` );
  12605. child.codegenNode = context.hoist(child.codegenNode);
  12606. hoistedCount++;
  12607. continue;
  12608. }
  12609. }
  12610. else {
  12611. // node may contain dynamic children, but its props may be eligible for
  12612. // hoisting.
  12613. const codegenNode = child.codegenNode;
  12614. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  12615. const flag = getPatchFlag(codegenNode);
  12616. if ((!flag ||
  12617. flag === 512 /* PatchFlags.NEED_PATCH */ ||
  12618. flag === 1 /* PatchFlags.TEXT */) &&
  12619. getGeneratedPropsConstantType(child, context) >=
  12620. 2 /* ConstantTypes.CAN_HOIST */) {
  12621. const props = getNodeProps(child);
  12622. if (props) {
  12623. codegenNode.props = context.hoist(props);
  12624. }
  12625. }
  12626. if (codegenNode.dynamicProps) {
  12627. codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
  12628. }
  12629. }
  12630. }
  12631. }
  12632. // walk further
  12633. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  12634. const isComponent = child.tagType === 1 /* ElementTypes.COMPONENT */;
  12635. if (isComponent) {
  12636. context.scopes.vSlot++;
  12637. }
  12638. walk(child, context);
  12639. if (isComponent) {
  12640. context.scopes.vSlot--;
  12641. }
  12642. }
  12643. else if (child.type === 11 /* NodeTypes.FOR */) {
  12644. // Do not hoist v-for single child because it has to be a block
  12645. walk(child, context, child.children.length === 1);
  12646. }
  12647. else if (child.type === 9 /* NodeTypes.IF */) {
  12648. for (let i = 0; i < child.branches.length; i++) {
  12649. // Do not hoist v-if single child because it has to be a block
  12650. walk(child.branches[i], context, child.branches[i].children.length === 1);
  12651. }
  12652. }
  12653. }
  12654. if (hoistedCount && context.transformHoist) {
  12655. context.transformHoist(children, context, node);
  12656. }
  12657. // all children were hoisted - the entire children array is hoistable.
  12658. if (hoistedCount &&
  12659. hoistedCount === originalCount &&
  12660. node.type === 1 /* NodeTypes.ELEMENT */ &&
  12661. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  12662. node.codegenNode &&
  12663. node.codegenNode.type === 13 /* NodeTypes.VNODE_CALL */ &&
  12664. isArray(node.codegenNode.children)) {
  12665. node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
  12666. }
  12667. }
  12668. function getConstantType(node, context) {
  12669. const { constantCache } = context;
  12670. switch (node.type) {
  12671. case 1 /* NodeTypes.ELEMENT */:
  12672. if (node.tagType !== 0 /* ElementTypes.ELEMENT */) {
  12673. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12674. }
  12675. const cached = constantCache.get(node);
  12676. if (cached !== undefined) {
  12677. return cached;
  12678. }
  12679. const codegenNode = node.codegenNode;
  12680. if (codegenNode.type !== 13 /* NodeTypes.VNODE_CALL */) {
  12681. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12682. }
  12683. if (codegenNode.isBlock &&
  12684. node.tag !== 'svg' &&
  12685. node.tag !== 'foreignObject') {
  12686. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12687. }
  12688. const flag = getPatchFlag(codegenNode);
  12689. if (!flag) {
  12690. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  12691. // Element itself has no patch flag. However we still need to check:
  12692. // 1. Even for a node with no patch flag, it is possible for it to contain
  12693. // non-hoistable expressions that refers to scope variables, e.g. compiler
  12694. // injected keys or cached event handlers. Therefore we need to always
  12695. // check the codegenNode's props to be sure.
  12696. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  12697. if (generatedPropsType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  12698. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  12699. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12700. }
  12701. if (generatedPropsType < returnType) {
  12702. returnType = generatedPropsType;
  12703. }
  12704. // 2. its children.
  12705. for (let i = 0; i < node.children.length; i++) {
  12706. const childType = getConstantType(node.children[i], context);
  12707. if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  12708. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  12709. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12710. }
  12711. if (childType < returnType) {
  12712. returnType = childType;
  12713. }
  12714. }
  12715. // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
  12716. // type, check if any of the props can cause the type to be lowered
  12717. // we can skip can_patch because it's guaranteed by the absence of a
  12718. // patchFlag.
  12719. if (returnType > 1 /* ConstantTypes.CAN_SKIP_PATCH */) {
  12720. for (let i = 0; i < node.props.length; i++) {
  12721. const p = node.props[i];
  12722. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'bind' && p.exp) {
  12723. const expType = getConstantType(p.exp, context);
  12724. if (expType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  12725. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  12726. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12727. }
  12728. if (expType < returnType) {
  12729. returnType = expType;
  12730. }
  12731. }
  12732. }
  12733. }
  12734. // only svg/foreignObject could be block here, however if they are
  12735. // static then they don't need to be blocks since there will be no
  12736. // nested updates.
  12737. if (codegenNode.isBlock) {
  12738. // except set custom directives.
  12739. for (let i = 0; i < node.props.length; i++) {
  12740. const p = node.props[i];
  12741. if (p.type === 7 /* NodeTypes.DIRECTIVE */) {
  12742. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  12743. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12744. }
  12745. }
  12746. context.removeHelper(OPEN_BLOCK);
  12747. context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
  12748. codegenNode.isBlock = false;
  12749. context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
  12750. }
  12751. constantCache.set(node, returnType);
  12752. return returnType;
  12753. }
  12754. else {
  12755. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  12756. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12757. }
  12758. case 2 /* NodeTypes.TEXT */:
  12759. case 3 /* NodeTypes.COMMENT */:
  12760. return 3 /* ConstantTypes.CAN_STRINGIFY */;
  12761. case 9 /* NodeTypes.IF */:
  12762. case 11 /* NodeTypes.FOR */:
  12763. case 10 /* NodeTypes.IF_BRANCH */:
  12764. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12765. case 5 /* NodeTypes.INTERPOLATION */:
  12766. case 12 /* NodeTypes.TEXT_CALL */:
  12767. return getConstantType(node.content, context);
  12768. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  12769. return node.constType;
  12770. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  12771. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  12772. for (let i = 0; i < node.children.length; i++) {
  12773. const child = node.children[i];
  12774. if (isString(child) || isSymbol(child)) {
  12775. continue;
  12776. }
  12777. const childType = getConstantType(child, context);
  12778. if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  12779. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12780. }
  12781. else if (childType < returnType) {
  12782. returnType = childType;
  12783. }
  12784. }
  12785. return returnType;
  12786. default:
  12787. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12788. }
  12789. }
  12790. const allowHoistedHelperSet = new Set([
  12791. NORMALIZE_CLASS,
  12792. NORMALIZE_STYLE,
  12793. NORMALIZE_PROPS,
  12794. GUARD_REACTIVE_PROPS
  12795. ]);
  12796. function getConstantTypeOfHelperCall(value, context) {
  12797. if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ &&
  12798. !isString(value.callee) &&
  12799. allowHoistedHelperSet.has(value.callee)) {
  12800. const arg = value.arguments[0];
  12801. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  12802. return getConstantType(arg, context);
  12803. }
  12804. else if (arg.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  12805. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
  12806. return getConstantTypeOfHelperCall(arg, context);
  12807. }
  12808. }
  12809. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12810. }
  12811. function getGeneratedPropsConstantType(node, context) {
  12812. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  12813. const props = getNodeProps(node);
  12814. if (props && props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  12815. const { properties } = props;
  12816. for (let i = 0; i < properties.length; i++) {
  12817. const { key, value } = properties[i];
  12818. const keyType = getConstantType(key, context);
  12819. if (keyType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  12820. return keyType;
  12821. }
  12822. if (keyType < returnType) {
  12823. returnType = keyType;
  12824. }
  12825. let valueType;
  12826. if (value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  12827. valueType = getConstantType(value, context);
  12828. }
  12829. else if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  12830. // some helper calls can be hoisted,
  12831. // such as the `normalizeProps` generated by the compiler for pre-normalize class,
  12832. // in this case we need to respect the ConstantType of the helper's arguments
  12833. valueType = getConstantTypeOfHelperCall(value, context);
  12834. }
  12835. else {
  12836. valueType = 0 /* ConstantTypes.NOT_CONSTANT */;
  12837. }
  12838. if (valueType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  12839. return valueType;
  12840. }
  12841. if (valueType < returnType) {
  12842. returnType = valueType;
  12843. }
  12844. }
  12845. }
  12846. return returnType;
  12847. }
  12848. function getNodeProps(node) {
  12849. const codegenNode = node.codegenNode;
  12850. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  12851. return codegenNode.props;
  12852. }
  12853. }
  12854. function getPatchFlag(node) {
  12855. const flag = node.patchFlag;
  12856. return flag ? parseInt(flag, 10) : undefined;
  12857. }
  12858. function createTransformContext(root, { filename = '', prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = NOOP, isCustomElement = NOOP, expressionPlugins = [], scopeId = null, slotted = true, ssr = false, inSSR = false, ssrCssVars = ``, bindingMetadata = EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError, onWarn = defaultOnWarn, compatConfig }) {
  12859. const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
  12860. const context = {
  12861. // options
  12862. selfName: nameMatch && capitalize(camelize(nameMatch[1])),
  12863. prefixIdentifiers,
  12864. hoistStatic,
  12865. cacheHandlers,
  12866. nodeTransforms,
  12867. directiveTransforms,
  12868. transformHoist,
  12869. isBuiltInComponent,
  12870. isCustomElement,
  12871. expressionPlugins,
  12872. scopeId,
  12873. slotted,
  12874. ssr,
  12875. inSSR,
  12876. ssrCssVars,
  12877. bindingMetadata,
  12878. inline,
  12879. isTS,
  12880. onError,
  12881. onWarn,
  12882. compatConfig,
  12883. // state
  12884. root,
  12885. helpers: new Map(),
  12886. components: new Set(),
  12887. directives: new Set(),
  12888. hoists: [],
  12889. imports: [],
  12890. constantCache: new Map(),
  12891. temps: 0,
  12892. cached: 0,
  12893. identifiers: Object.create(null),
  12894. scopes: {
  12895. vFor: 0,
  12896. vSlot: 0,
  12897. vPre: 0,
  12898. vOnce: 0
  12899. },
  12900. parent: null,
  12901. currentNode: root,
  12902. childIndex: 0,
  12903. inVOnce: false,
  12904. // methods
  12905. helper(name) {
  12906. const count = context.helpers.get(name) || 0;
  12907. context.helpers.set(name, count + 1);
  12908. return name;
  12909. },
  12910. removeHelper(name) {
  12911. const count = context.helpers.get(name);
  12912. if (count) {
  12913. const currentCount = count - 1;
  12914. if (!currentCount) {
  12915. context.helpers.delete(name);
  12916. }
  12917. else {
  12918. context.helpers.set(name, currentCount);
  12919. }
  12920. }
  12921. },
  12922. helperString(name) {
  12923. return `_${helperNameMap[context.helper(name)]}`;
  12924. },
  12925. replaceNode(node) {
  12926. /* istanbul ignore if */
  12927. {
  12928. if (!context.currentNode) {
  12929. throw new Error(`Node being replaced is already removed.`);
  12930. }
  12931. if (!context.parent) {
  12932. throw new Error(`Cannot replace root node.`);
  12933. }
  12934. }
  12935. context.parent.children[context.childIndex] = context.currentNode = node;
  12936. },
  12937. removeNode(node) {
  12938. if (!context.parent) {
  12939. throw new Error(`Cannot remove root node.`);
  12940. }
  12941. const list = context.parent.children;
  12942. const removalIndex = node
  12943. ? list.indexOf(node)
  12944. : context.currentNode
  12945. ? context.childIndex
  12946. : -1;
  12947. /* istanbul ignore if */
  12948. if (removalIndex < 0) {
  12949. throw new Error(`node being removed is not a child of current parent`);
  12950. }
  12951. if (!node || node === context.currentNode) {
  12952. // current node removed
  12953. context.currentNode = null;
  12954. context.onNodeRemoved();
  12955. }
  12956. else {
  12957. // sibling node removed
  12958. if (context.childIndex > removalIndex) {
  12959. context.childIndex--;
  12960. context.onNodeRemoved();
  12961. }
  12962. }
  12963. context.parent.children.splice(removalIndex, 1);
  12964. },
  12965. onNodeRemoved: () => { },
  12966. addIdentifiers(exp) {
  12967. },
  12968. removeIdentifiers(exp) {
  12969. },
  12970. hoist(exp) {
  12971. if (isString(exp))
  12972. exp = createSimpleExpression(exp);
  12973. context.hoists.push(exp);
  12974. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* ConstantTypes.CAN_HOIST */);
  12975. identifier.hoisted = exp;
  12976. return identifier;
  12977. },
  12978. cache(exp, isVNode = false) {
  12979. return createCacheExpression(context.cached++, exp, isVNode);
  12980. }
  12981. };
  12982. return context;
  12983. }
  12984. function transform(root, options) {
  12985. const context = createTransformContext(root, options);
  12986. traverseNode(root, context);
  12987. if (options.hoistStatic) {
  12988. hoistStatic(root, context);
  12989. }
  12990. if (!options.ssr) {
  12991. createRootCodegen(root, context);
  12992. }
  12993. // finalize meta information
  12994. root.helpers = [...context.helpers.keys()];
  12995. root.components = [...context.components];
  12996. root.directives = [...context.directives];
  12997. root.imports = context.imports;
  12998. root.hoists = context.hoists;
  12999. root.temps = context.temps;
  13000. root.cached = context.cached;
  13001. }
  13002. function createRootCodegen(root, context) {
  13003. const { helper } = context;
  13004. const { children } = root;
  13005. if (children.length === 1) {
  13006. const child = children[0];
  13007. // if the single child is an element, turn it into a block.
  13008. if (isSingleElementRoot(root, child) && child.codegenNode) {
  13009. // single element root is never hoisted so codegenNode will never be
  13010. // SimpleExpressionNode
  13011. const codegenNode = child.codegenNode;
  13012. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  13013. makeBlock(codegenNode, context);
  13014. }
  13015. root.codegenNode = codegenNode;
  13016. }
  13017. else {
  13018. // - single <slot/>, IfNode, ForNode: already blocks.
  13019. // - single text node: always patched.
  13020. // root codegen falls through via genNode()
  13021. root.codegenNode = child;
  13022. }
  13023. }
  13024. else if (children.length > 1) {
  13025. // root has multiple nodes - return a fragment block.
  13026. let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
  13027. let patchFlagText = PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
  13028. // check if the fragment actually contains a single valid child with
  13029. // the rest being comments
  13030. if (children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
  13031. patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
  13032. patchFlagText += `, ${PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
  13033. }
  13034. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
  13035. }
  13036. else ;
  13037. }
  13038. function traverseChildren(parent, context) {
  13039. let i = 0;
  13040. const nodeRemoved = () => {
  13041. i--;
  13042. };
  13043. for (; i < parent.children.length; i++) {
  13044. const child = parent.children[i];
  13045. if (isString(child))
  13046. continue;
  13047. context.parent = parent;
  13048. context.childIndex = i;
  13049. context.onNodeRemoved = nodeRemoved;
  13050. traverseNode(child, context);
  13051. }
  13052. }
  13053. function traverseNode(node, context) {
  13054. context.currentNode = node;
  13055. // apply transform plugins
  13056. const { nodeTransforms } = context;
  13057. const exitFns = [];
  13058. for (let i = 0; i < nodeTransforms.length; i++) {
  13059. const onExit = nodeTransforms[i](node, context);
  13060. if (onExit) {
  13061. if (isArray(onExit)) {
  13062. exitFns.push(...onExit);
  13063. }
  13064. else {
  13065. exitFns.push(onExit);
  13066. }
  13067. }
  13068. if (!context.currentNode) {
  13069. // node was removed
  13070. return;
  13071. }
  13072. else {
  13073. // node may have been replaced
  13074. node = context.currentNode;
  13075. }
  13076. }
  13077. switch (node.type) {
  13078. case 3 /* NodeTypes.COMMENT */:
  13079. if (!context.ssr) {
  13080. // inject import for the Comment symbol, which is needed for creating
  13081. // comment nodes with `createVNode`
  13082. context.helper(CREATE_COMMENT);
  13083. }
  13084. break;
  13085. case 5 /* NodeTypes.INTERPOLATION */:
  13086. // no need to traverse, but we need to inject toString helper
  13087. if (!context.ssr) {
  13088. context.helper(TO_DISPLAY_STRING);
  13089. }
  13090. break;
  13091. // for container types, further traverse downwards
  13092. case 9 /* NodeTypes.IF */:
  13093. for (let i = 0; i < node.branches.length; i++) {
  13094. traverseNode(node.branches[i], context);
  13095. }
  13096. break;
  13097. case 10 /* NodeTypes.IF_BRANCH */:
  13098. case 11 /* NodeTypes.FOR */:
  13099. case 1 /* NodeTypes.ELEMENT */:
  13100. case 0 /* NodeTypes.ROOT */:
  13101. traverseChildren(node, context);
  13102. break;
  13103. }
  13104. // exit transforms
  13105. context.currentNode = node;
  13106. let i = exitFns.length;
  13107. while (i--) {
  13108. exitFns[i]();
  13109. }
  13110. }
  13111. function createStructuralDirectiveTransform(name, fn) {
  13112. const matches = isString(name)
  13113. ? (n) => n === name
  13114. : (n) => name.test(n);
  13115. return (node, context) => {
  13116. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  13117. const { props } = node;
  13118. // structural directive transforms are not concerned with slots
  13119. // as they are handled separately in vSlot.ts
  13120. if (node.tagType === 3 /* ElementTypes.TEMPLATE */ && props.some(isVSlot)) {
  13121. return;
  13122. }
  13123. const exitFns = [];
  13124. for (let i = 0; i < props.length; i++) {
  13125. const prop = props[i];
  13126. if (prop.type === 7 /* NodeTypes.DIRECTIVE */ && matches(prop.name)) {
  13127. // structural directives are removed to avoid infinite recursion
  13128. // also we remove them *before* applying so that it can further
  13129. // traverse itself in case it moves the node around
  13130. props.splice(i, 1);
  13131. i--;
  13132. const onExit = fn(node, prop, context);
  13133. if (onExit)
  13134. exitFns.push(onExit);
  13135. }
  13136. }
  13137. return exitFns;
  13138. }
  13139. };
  13140. }
  13141. const PURE_ANNOTATION = `/*#__PURE__*/`;
  13142. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  13143. function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssrRuntimeModuleName = 'vue/server-renderer', ssr = false, isTS = false, inSSR = false }) {
  13144. const context = {
  13145. mode,
  13146. prefixIdentifiers,
  13147. sourceMap,
  13148. filename,
  13149. scopeId,
  13150. optimizeImports,
  13151. runtimeGlobalName,
  13152. runtimeModuleName,
  13153. ssrRuntimeModuleName,
  13154. ssr,
  13155. isTS,
  13156. inSSR,
  13157. source: ast.loc.source,
  13158. code: ``,
  13159. column: 1,
  13160. line: 1,
  13161. offset: 0,
  13162. indentLevel: 0,
  13163. pure: false,
  13164. map: undefined,
  13165. helper(key) {
  13166. return `_${helperNameMap[key]}`;
  13167. },
  13168. push(code, node) {
  13169. context.code += code;
  13170. },
  13171. indent() {
  13172. newline(++context.indentLevel);
  13173. },
  13174. deindent(withoutNewLine = false) {
  13175. if (withoutNewLine) {
  13176. --context.indentLevel;
  13177. }
  13178. else {
  13179. newline(--context.indentLevel);
  13180. }
  13181. },
  13182. newline() {
  13183. newline(context.indentLevel);
  13184. }
  13185. };
  13186. function newline(n) {
  13187. context.push('\n' + ` `.repeat(n));
  13188. }
  13189. return context;
  13190. }
  13191. function generate(ast, options = {}) {
  13192. const context = createCodegenContext(ast, options);
  13193. if (options.onContextCreated)
  13194. options.onContextCreated(context);
  13195. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  13196. const hasHelpers = ast.helpers.length > 0;
  13197. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  13198. // preambles
  13199. // in setup() inline mode, the preamble is generated in a sub context
  13200. // and returned separately.
  13201. const preambleContext = context;
  13202. {
  13203. genFunctionPreamble(ast, preambleContext);
  13204. }
  13205. // enter render function
  13206. const functionName = ssr ? `ssrRender` : `render`;
  13207. const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
  13208. const signature = args.join(', ');
  13209. {
  13210. push(`function ${functionName}(${signature}) {`);
  13211. }
  13212. indent();
  13213. if (useWithBlock) {
  13214. push(`with (_ctx) {`);
  13215. indent();
  13216. // function mode const declarations should be inside with block
  13217. // also they should be renamed to avoid collision with user properties
  13218. if (hasHelpers) {
  13219. push(`const { ${ast.helpers.map(aliasHelper).join(', ')} } = _Vue`);
  13220. push(`\n`);
  13221. newline();
  13222. }
  13223. }
  13224. // generate asset resolution statements
  13225. if (ast.components.length) {
  13226. genAssets(ast.components, 'component', context);
  13227. if (ast.directives.length || ast.temps > 0) {
  13228. newline();
  13229. }
  13230. }
  13231. if (ast.directives.length) {
  13232. genAssets(ast.directives, 'directive', context);
  13233. if (ast.temps > 0) {
  13234. newline();
  13235. }
  13236. }
  13237. if (ast.temps > 0) {
  13238. push(`let `);
  13239. for (let i = 0; i < ast.temps; i++) {
  13240. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  13241. }
  13242. }
  13243. if (ast.components.length || ast.directives.length || ast.temps) {
  13244. push(`\n`);
  13245. newline();
  13246. }
  13247. // generate the VNode tree expression
  13248. if (!ssr) {
  13249. push(`return `);
  13250. }
  13251. if (ast.codegenNode) {
  13252. genNode(ast.codegenNode, context);
  13253. }
  13254. else {
  13255. push(`null`);
  13256. }
  13257. if (useWithBlock) {
  13258. deindent();
  13259. push(`}`);
  13260. }
  13261. deindent();
  13262. push(`}`);
  13263. return {
  13264. ast,
  13265. code: context.code,
  13266. preamble: ``,
  13267. // SourceMapGenerator does have toJSON() method but it's not in the types
  13268. map: context.map ? context.map.toJSON() : undefined
  13269. };
  13270. }
  13271. function genFunctionPreamble(ast, context) {
  13272. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
  13273. const VueBinding = runtimeGlobalName;
  13274. // Generate const declaration for helpers
  13275. // In prefix mode, we place the const declaration at top so it's done
  13276. // only once; But if we not prefixing, we place the declaration inside the
  13277. // with block so it doesn't incur the `in` check cost for every helper access.
  13278. if (ast.helpers.length > 0) {
  13279. {
  13280. // "with" mode.
  13281. // save Vue in a separate variable to avoid collision
  13282. push(`const _Vue = ${VueBinding}\n`);
  13283. // in "with" mode, helpers are declared inside the with block to avoid
  13284. // has check cost, but hoists are lifted out of the function - we need
  13285. // to provide the helper here.
  13286. if (ast.hoists.length) {
  13287. const staticHelpers = [
  13288. CREATE_VNODE,
  13289. CREATE_ELEMENT_VNODE,
  13290. CREATE_COMMENT,
  13291. CREATE_TEXT,
  13292. CREATE_STATIC
  13293. ]
  13294. .filter(helper => ast.helpers.includes(helper))
  13295. .map(aliasHelper)
  13296. .join(', ');
  13297. push(`const { ${staticHelpers} } = _Vue\n`);
  13298. }
  13299. }
  13300. }
  13301. genHoists(ast.hoists, context);
  13302. newline();
  13303. push(`return `);
  13304. }
  13305. function genAssets(assets, type, { helper, push, newline, isTS }) {
  13306. const resolver = helper(type === 'component'
  13307. ? RESOLVE_COMPONENT
  13308. : RESOLVE_DIRECTIVE);
  13309. for (let i = 0; i < assets.length; i++) {
  13310. let id = assets[i];
  13311. // potential component implicit self-reference inferred from SFC filename
  13312. const maybeSelfReference = id.endsWith('__self');
  13313. if (maybeSelfReference) {
  13314. id = id.slice(0, -6);
  13315. }
  13316. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
  13317. if (i < assets.length - 1) {
  13318. newline();
  13319. }
  13320. }
  13321. }
  13322. function genHoists(hoists, context) {
  13323. if (!hoists.length) {
  13324. return;
  13325. }
  13326. context.pure = true;
  13327. const { push, newline, helper, scopeId, mode } = context;
  13328. newline();
  13329. for (let i = 0; i < hoists.length; i++) {
  13330. const exp = hoists[i];
  13331. if (exp) {
  13332. push(`const _hoisted_${i + 1} = ${``}`);
  13333. genNode(exp, context);
  13334. newline();
  13335. }
  13336. }
  13337. context.pure = false;
  13338. }
  13339. function isText$1(n) {
  13340. return (isString(n) ||
  13341. n.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  13342. n.type === 2 /* NodeTypes.TEXT */ ||
  13343. n.type === 5 /* NodeTypes.INTERPOLATION */ ||
  13344. n.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */);
  13345. }
  13346. function genNodeListAsArray(nodes, context) {
  13347. const multilines = nodes.length > 3 ||
  13348. (nodes.some(n => isArray(n) || !isText$1(n)));
  13349. context.push(`[`);
  13350. multilines && context.indent();
  13351. genNodeList(nodes, context, multilines);
  13352. multilines && context.deindent();
  13353. context.push(`]`);
  13354. }
  13355. function genNodeList(nodes, context, multilines = false, comma = true) {
  13356. const { push, newline } = context;
  13357. for (let i = 0; i < nodes.length; i++) {
  13358. const node = nodes[i];
  13359. if (isString(node)) {
  13360. push(node);
  13361. }
  13362. else if (isArray(node)) {
  13363. genNodeListAsArray(node, context);
  13364. }
  13365. else {
  13366. genNode(node, context);
  13367. }
  13368. if (i < nodes.length - 1) {
  13369. if (multilines) {
  13370. comma && push(',');
  13371. newline();
  13372. }
  13373. else {
  13374. comma && push(', ');
  13375. }
  13376. }
  13377. }
  13378. }
  13379. function genNode(node, context) {
  13380. if (isString(node)) {
  13381. context.push(node);
  13382. return;
  13383. }
  13384. if (isSymbol(node)) {
  13385. context.push(context.helper(node));
  13386. return;
  13387. }
  13388. switch (node.type) {
  13389. case 1 /* NodeTypes.ELEMENT */:
  13390. case 9 /* NodeTypes.IF */:
  13391. case 11 /* NodeTypes.FOR */:
  13392. assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  13393. `Apply appropriate transforms first.`);
  13394. genNode(node.codegenNode, context);
  13395. break;
  13396. case 2 /* NodeTypes.TEXT */:
  13397. genText(node, context);
  13398. break;
  13399. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  13400. genExpression(node, context);
  13401. break;
  13402. case 5 /* NodeTypes.INTERPOLATION */:
  13403. genInterpolation(node, context);
  13404. break;
  13405. case 12 /* NodeTypes.TEXT_CALL */:
  13406. genNode(node.codegenNode, context);
  13407. break;
  13408. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  13409. genCompoundExpression(node, context);
  13410. break;
  13411. case 3 /* NodeTypes.COMMENT */:
  13412. genComment(node, context);
  13413. break;
  13414. case 13 /* NodeTypes.VNODE_CALL */:
  13415. genVNodeCall(node, context);
  13416. break;
  13417. case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
  13418. genCallExpression(node, context);
  13419. break;
  13420. case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
  13421. genObjectExpression(node, context);
  13422. break;
  13423. case 17 /* NodeTypes.JS_ARRAY_EXPRESSION */:
  13424. genArrayExpression(node, context);
  13425. break;
  13426. case 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */:
  13427. genFunctionExpression(node, context);
  13428. break;
  13429. case 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */:
  13430. genConditionalExpression(node, context);
  13431. break;
  13432. case 20 /* NodeTypes.JS_CACHE_EXPRESSION */:
  13433. genCacheExpression(node, context);
  13434. break;
  13435. case 21 /* NodeTypes.JS_BLOCK_STATEMENT */:
  13436. genNodeList(node.body, context, true, false);
  13437. break;
  13438. // SSR only types
  13439. case 22 /* NodeTypes.JS_TEMPLATE_LITERAL */:
  13440. break;
  13441. case 23 /* NodeTypes.JS_IF_STATEMENT */:
  13442. break;
  13443. case 24 /* NodeTypes.JS_ASSIGNMENT_EXPRESSION */:
  13444. break;
  13445. case 25 /* NodeTypes.JS_SEQUENCE_EXPRESSION */:
  13446. break;
  13447. case 26 /* NodeTypes.JS_RETURN_STATEMENT */:
  13448. break;
  13449. /* istanbul ignore next */
  13450. case 10 /* NodeTypes.IF_BRANCH */:
  13451. // noop
  13452. break;
  13453. default:
  13454. {
  13455. assert(false, `unhandled codegen node type: ${node.type}`);
  13456. // make sure we exhaust all possible types
  13457. const exhaustiveCheck = node;
  13458. return exhaustiveCheck;
  13459. }
  13460. }
  13461. }
  13462. function genText(node, context) {
  13463. context.push(JSON.stringify(node.content), node);
  13464. }
  13465. function genExpression(node, context) {
  13466. const { content, isStatic } = node;
  13467. context.push(isStatic ? JSON.stringify(content) : content, node);
  13468. }
  13469. function genInterpolation(node, context) {
  13470. const { push, helper, pure } = context;
  13471. if (pure)
  13472. push(PURE_ANNOTATION);
  13473. push(`${helper(TO_DISPLAY_STRING)}(`);
  13474. genNode(node.content, context);
  13475. push(`)`);
  13476. }
  13477. function genCompoundExpression(node, context) {
  13478. for (let i = 0; i < node.children.length; i++) {
  13479. const child = node.children[i];
  13480. if (isString(child)) {
  13481. context.push(child);
  13482. }
  13483. else {
  13484. genNode(child, context);
  13485. }
  13486. }
  13487. }
  13488. function genExpressionAsPropertyKey(node, context) {
  13489. const { push } = context;
  13490. if (node.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  13491. push(`[`);
  13492. genCompoundExpression(node, context);
  13493. push(`]`);
  13494. }
  13495. else if (node.isStatic) {
  13496. // only quote keys if necessary
  13497. const text = isSimpleIdentifier(node.content)
  13498. ? node.content
  13499. : JSON.stringify(node.content);
  13500. push(text, node);
  13501. }
  13502. else {
  13503. push(`[${node.content}]`, node);
  13504. }
  13505. }
  13506. function genComment(node, context) {
  13507. const { push, helper, pure } = context;
  13508. if (pure) {
  13509. push(PURE_ANNOTATION);
  13510. }
  13511. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  13512. }
  13513. function genVNodeCall(node, context) {
  13514. const { push, helper, pure } = context;
  13515. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
  13516. if (directives) {
  13517. push(helper(WITH_DIRECTIVES) + `(`);
  13518. }
  13519. if (isBlock) {
  13520. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  13521. }
  13522. if (pure) {
  13523. push(PURE_ANNOTATION);
  13524. }
  13525. const callHelper = isBlock
  13526. ? getVNodeBlockHelper(context.inSSR, isComponent)
  13527. : getVNodeHelper(context.inSSR, isComponent);
  13528. push(helper(callHelper) + `(`, node);
  13529. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  13530. push(`)`);
  13531. if (isBlock) {
  13532. push(`)`);
  13533. }
  13534. if (directives) {
  13535. push(`, `);
  13536. genNode(directives, context);
  13537. push(`)`);
  13538. }
  13539. }
  13540. function genNullableArgs(args) {
  13541. let i = args.length;
  13542. while (i--) {
  13543. if (args[i] != null)
  13544. break;
  13545. }
  13546. return args.slice(0, i + 1).map(arg => arg || `null`);
  13547. }
  13548. // JavaScript
  13549. function genCallExpression(node, context) {
  13550. const { push, helper, pure } = context;
  13551. const callee = isString(node.callee) ? node.callee : helper(node.callee);
  13552. if (pure) {
  13553. push(PURE_ANNOTATION);
  13554. }
  13555. push(callee + `(`, node);
  13556. genNodeList(node.arguments, context);
  13557. push(`)`);
  13558. }
  13559. function genObjectExpression(node, context) {
  13560. const { push, indent, deindent, newline } = context;
  13561. const { properties } = node;
  13562. if (!properties.length) {
  13563. push(`{}`, node);
  13564. return;
  13565. }
  13566. const multilines = properties.length > 1 ||
  13567. (properties.some(p => p.value.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */));
  13568. push(multilines ? `{` : `{ `);
  13569. multilines && indent();
  13570. for (let i = 0; i < properties.length; i++) {
  13571. const { key, value } = properties[i];
  13572. // key
  13573. genExpressionAsPropertyKey(key, context);
  13574. push(`: `);
  13575. // value
  13576. genNode(value, context);
  13577. if (i < properties.length - 1) {
  13578. // will only reach this if it's multilines
  13579. push(`,`);
  13580. newline();
  13581. }
  13582. }
  13583. multilines && deindent();
  13584. push(multilines ? `}` : ` }`);
  13585. }
  13586. function genArrayExpression(node, context) {
  13587. genNodeListAsArray(node.elements, context);
  13588. }
  13589. function genFunctionExpression(node, context) {
  13590. const { push, indent, deindent } = context;
  13591. const { params, returns, body, newline, isSlot } = node;
  13592. if (isSlot) {
  13593. // wrap slot functions with owner context
  13594. push(`_${helperNameMap[WITH_CTX]}(`);
  13595. }
  13596. push(`(`, node);
  13597. if (isArray(params)) {
  13598. genNodeList(params, context);
  13599. }
  13600. else if (params) {
  13601. genNode(params, context);
  13602. }
  13603. push(`) => `);
  13604. if (newline || body) {
  13605. push(`{`);
  13606. indent();
  13607. }
  13608. if (returns) {
  13609. if (newline) {
  13610. push(`return `);
  13611. }
  13612. if (isArray(returns)) {
  13613. genNodeListAsArray(returns, context);
  13614. }
  13615. else {
  13616. genNode(returns, context);
  13617. }
  13618. }
  13619. else if (body) {
  13620. genNode(body, context);
  13621. }
  13622. if (newline || body) {
  13623. deindent();
  13624. push(`}`);
  13625. }
  13626. if (isSlot) {
  13627. push(`)`);
  13628. }
  13629. }
  13630. function genConditionalExpression(node, context) {
  13631. const { test, consequent, alternate, newline: needNewline } = node;
  13632. const { push, indent, deindent, newline } = context;
  13633. if (test.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  13634. const needsParens = !isSimpleIdentifier(test.content);
  13635. needsParens && push(`(`);
  13636. genExpression(test, context);
  13637. needsParens && push(`)`);
  13638. }
  13639. else {
  13640. push(`(`);
  13641. genNode(test, context);
  13642. push(`)`);
  13643. }
  13644. needNewline && indent();
  13645. context.indentLevel++;
  13646. needNewline || push(` `);
  13647. push(`? `);
  13648. genNode(consequent, context);
  13649. context.indentLevel--;
  13650. needNewline && newline();
  13651. needNewline || push(` `);
  13652. push(`: `);
  13653. const isNested = alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */;
  13654. if (!isNested) {
  13655. context.indentLevel++;
  13656. }
  13657. genNode(alternate, context);
  13658. if (!isNested) {
  13659. context.indentLevel--;
  13660. }
  13661. needNewline && deindent(true /* without newline */);
  13662. }
  13663. function genCacheExpression(node, context) {
  13664. const { push, helper, indent, deindent, newline } = context;
  13665. push(`_cache[${node.index}] || (`);
  13666. if (node.isVNode) {
  13667. indent();
  13668. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  13669. newline();
  13670. }
  13671. push(`_cache[${node.index}] = `);
  13672. genNode(node.value, context);
  13673. if (node.isVNode) {
  13674. push(`,`);
  13675. newline();
  13676. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  13677. newline();
  13678. push(`_cache[${node.index}]`);
  13679. deindent();
  13680. }
  13681. push(`)`);
  13682. }
  13683. // these keywords should not appear inside expressions, but operators like
  13684. // typeof, instanceof and in are allowed
  13685. const prohibitedKeywordRE = new RegExp('\\b' +
  13686. ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
  13687. 'super,throw,while,yield,delete,export,import,return,switch,default,' +
  13688. 'extends,finally,continue,debugger,function,arguments,typeof,void')
  13689. .split(',')
  13690. .join('\\b|\\b') +
  13691. '\\b');
  13692. // strip strings in expressions
  13693. const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
  13694. /**
  13695. * Validate a non-prefixed expression.
  13696. * This is only called when using the in-browser runtime compiler since it
  13697. * doesn't prefix expressions.
  13698. */
  13699. function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
  13700. const exp = node.content;
  13701. // empty expressions are validated per-directive since some directives
  13702. // do allow empty expressions.
  13703. if (!exp.trim()) {
  13704. return;
  13705. }
  13706. try {
  13707. new Function(asRawStatements
  13708. ? ` ${exp} `
  13709. : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
  13710. }
  13711. catch (e) {
  13712. let message = e.message;
  13713. const keywordMatch = exp
  13714. .replace(stripStringRE, '')
  13715. .match(prohibitedKeywordRE);
  13716. if (keywordMatch) {
  13717. message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
  13718. }
  13719. context.onError(createCompilerError(45 /* ErrorCodes.X_INVALID_EXPRESSION */, node.loc, undefined, message));
  13720. }
  13721. }
  13722. const transformExpression = (node, context) => {
  13723. if (node.type === 5 /* NodeTypes.INTERPOLATION */) {
  13724. node.content = processExpression(node.content, context);
  13725. }
  13726. else if (node.type === 1 /* NodeTypes.ELEMENT */) {
  13727. // handle directives on element
  13728. for (let i = 0; i < node.props.length; i++) {
  13729. const dir = node.props[i];
  13730. // do not process for v-on & v-for since they are special handled
  13731. if (dir.type === 7 /* NodeTypes.DIRECTIVE */ && dir.name !== 'for') {
  13732. const exp = dir.exp;
  13733. const arg = dir.arg;
  13734. // do not process exp if this is v-on:arg - we need special handling
  13735. // for wrapping inline statements.
  13736. if (exp &&
  13737. exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  13738. !(dir.name === 'on' && arg)) {
  13739. dir.exp = processExpression(exp, context,
  13740. // slot args must be processed as function params
  13741. dir.name === 'slot');
  13742. }
  13743. if (arg && arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !arg.isStatic) {
  13744. dir.arg = processExpression(arg, context);
  13745. }
  13746. }
  13747. }
  13748. }
  13749. };
  13750. // Important: since this function uses Node.js only dependencies, it should
  13751. // always be used with a leading !true check so that it can be
  13752. // tree-shaken from the browser build.
  13753. function processExpression(node, context,
  13754. // some expressions like v-slot props & v-for aliases should be parsed as
  13755. // function params
  13756. asParams = false,
  13757. // v-on handler values may contain multiple statements
  13758. asRawStatements = false, localVars = Object.create(context.identifiers)) {
  13759. {
  13760. {
  13761. // simple in-browser validation (same logic in 2.x)
  13762. validateBrowserExpression(node, context, asParams, asRawStatements);
  13763. }
  13764. return node;
  13765. }
  13766. }
  13767. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  13768. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  13769. // #1587: We need to dynamically increment the key based on the current
  13770. // node's sibling nodes, since chained v-if/else branches are
  13771. // rendered at the same depth
  13772. const siblings = context.parent.children;
  13773. let i = siblings.indexOf(ifNode);
  13774. let key = 0;
  13775. while (i-- >= 0) {
  13776. const sibling = siblings[i];
  13777. if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
  13778. key += sibling.branches.length;
  13779. }
  13780. }
  13781. // Exit callback. Complete the codegenNode when all children have been
  13782. // transformed.
  13783. return () => {
  13784. if (isRoot) {
  13785. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  13786. }
  13787. else {
  13788. // attach this branch's codegen node to the v-if root.
  13789. const parentCondition = getParentCondition(ifNode.codegenNode);
  13790. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  13791. }
  13792. };
  13793. });
  13794. });
  13795. // target-agnostic transform used for both Client and SSR
  13796. function processIf(node, dir, context, processCodegen) {
  13797. if (dir.name !== 'else' &&
  13798. (!dir.exp || !dir.exp.content.trim())) {
  13799. const loc = dir.exp ? dir.exp.loc : node.loc;
  13800. context.onError(createCompilerError(28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */, dir.loc));
  13801. dir.exp = createSimpleExpression(`true`, false, loc);
  13802. }
  13803. if (dir.exp) {
  13804. validateBrowserExpression(dir.exp, context);
  13805. }
  13806. if (dir.name === 'if') {
  13807. const branch = createIfBranch(node, dir);
  13808. const ifNode = {
  13809. type: 9 /* NodeTypes.IF */,
  13810. loc: node.loc,
  13811. branches: [branch]
  13812. };
  13813. context.replaceNode(ifNode);
  13814. if (processCodegen) {
  13815. return processCodegen(ifNode, branch, true);
  13816. }
  13817. }
  13818. else {
  13819. // locate the adjacent v-if
  13820. const siblings = context.parent.children;
  13821. const comments = [];
  13822. let i = siblings.indexOf(node);
  13823. while (i-- >= -1) {
  13824. const sibling = siblings[i];
  13825. if (sibling && sibling.type === 3 /* NodeTypes.COMMENT */) {
  13826. context.removeNode(sibling);
  13827. comments.unshift(sibling);
  13828. continue;
  13829. }
  13830. if (sibling &&
  13831. sibling.type === 2 /* NodeTypes.TEXT */ &&
  13832. !sibling.content.trim().length) {
  13833. context.removeNode(sibling);
  13834. continue;
  13835. }
  13836. if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
  13837. // Check if v-else was followed by v-else-if
  13838. if (dir.name === 'else-if' &&
  13839. sibling.branches[sibling.branches.length - 1].condition === undefined) {
  13840. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  13841. }
  13842. // move the node to the if node's branches
  13843. context.removeNode();
  13844. const branch = createIfBranch(node, dir);
  13845. if (comments.length &&
  13846. // #3619 ignore comments if the v-if is direct child of <transition>
  13847. !(context.parent &&
  13848. context.parent.type === 1 /* NodeTypes.ELEMENT */ &&
  13849. isBuiltInType(context.parent.tag, 'transition'))) {
  13850. branch.children = [...comments, ...branch.children];
  13851. }
  13852. // check if user is forcing same key on different branches
  13853. {
  13854. const key = branch.userKey;
  13855. if (key) {
  13856. sibling.branches.forEach(({ userKey }) => {
  13857. if (isSameKey(userKey, key)) {
  13858. context.onError(createCompilerError(29 /* ErrorCodes.X_V_IF_SAME_KEY */, branch.userKey.loc));
  13859. }
  13860. });
  13861. }
  13862. }
  13863. sibling.branches.push(branch);
  13864. const onExit = processCodegen && processCodegen(sibling, branch, false);
  13865. // since the branch was removed, it will not be traversed.
  13866. // make sure to traverse here.
  13867. traverseNode(branch, context);
  13868. // call on exit
  13869. if (onExit)
  13870. onExit();
  13871. // make sure to reset currentNode after traversal to indicate this
  13872. // node has been removed.
  13873. context.currentNode = null;
  13874. }
  13875. else {
  13876. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  13877. }
  13878. break;
  13879. }
  13880. }
  13881. }
  13882. function createIfBranch(node, dir) {
  13883. const isTemplateIf = node.tagType === 3 /* ElementTypes.TEMPLATE */;
  13884. return {
  13885. type: 10 /* NodeTypes.IF_BRANCH */,
  13886. loc: node.loc,
  13887. condition: dir.name === 'else' ? undefined : dir.exp,
  13888. children: isTemplateIf && !findDir(node, 'for') ? node.children : [node],
  13889. userKey: findProp(node, `key`),
  13890. isTemplateIf
  13891. };
  13892. }
  13893. function createCodegenNodeForBranch(branch, keyIndex, context) {
  13894. if (branch.condition) {
  13895. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  13896. // make sure to pass in asBlock: true so that the comment node call
  13897. // closes the current block.
  13898. createCallExpression(context.helper(CREATE_COMMENT), [
  13899. '"v-if"' ,
  13900. 'true'
  13901. ]));
  13902. }
  13903. else {
  13904. return createChildrenCodegenNode(branch, keyIndex, context);
  13905. }
  13906. }
  13907. function createChildrenCodegenNode(branch, keyIndex, context) {
  13908. const { helper } = context;
  13909. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* ConstantTypes.CAN_HOIST */));
  13910. const { children } = branch;
  13911. const firstChild = children[0];
  13912. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* NodeTypes.ELEMENT */;
  13913. if (needFragmentWrapper) {
  13914. if (children.length === 1 && firstChild.type === 11 /* NodeTypes.FOR */) {
  13915. // optimize away nested fragments when child is a ForNode
  13916. const vnodeCall = firstChild.codegenNode;
  13917. injectProp(vnodeCall, keyProperty, context);
  13918. return vnodeCall;
  13919. }
  13920. else {
  13921. let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
  13922. let patchFlagText = PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
  13923. // check if the fragment actually contains a single valid child with
  13924. // the rest being comments
  13925. if (!branch.isTemplateIf &&
  13926. children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
  13927. patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
  13928. patchFlagText += `, ${PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
  13929. }
  13930. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
  13931. }
  13932. }
  13933. else {
  13934. const ret = firstChild.codegenNode;
  13935. const vnodeCall = getMemoedVNodeCall(ret);
  13936. // Change createVNode to createBlock.
  13937. if (vnodeCall.type === 13 /* NodeTypes.VNODE_CALL */) {
  13938. makeBlock(vnodeCall, context);
  13939. }
  13940. // inject branch key
  13941. injectProp(vnodeCall, keyProperty, context);
  13942. return ret;
  13943. }
  13944. }
  13945. function isSameKey(a, b) {
  13946. if (!a || a.type !== b.type) {
  13947. return false;
  13948. }
  13949. if (a.type === 6 /* NodeTypes.ATTRIBUTE */) {
  13950. if (a.value.content !== b.value.content) {
  13951. return false;
  13952. }
  13953. }
  13954. else {
  13955. // directive
  13956. const exp = a.exp;
  13957. const branchExp = b.exp;
  13958. if (exp.type !== branchExp.type) {
  13959. return false;
  13960. }
  13961. if (exp.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  13962. exp.isStatic !== branchExp.isStatic ||
  13963. exp.content !== branchExp.content) {
  13964. return false;
  13965. }
  13966. }
  13967. return true;
  13968. }
  13969. function getParentCondition(node) {
  13970. while (true) {
  13971. if (node.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  13972. if (node.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  13973. node = node.alternate;
  13974. }
  13975. else {
  13976. return node;
  13977. }
  13978. }
  13979. else if (node.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */) {
  13980. node = node.value;
  13981. }
  13982. }
  13983. }
  13984. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  13985. const { helper, removeHelper } = context;
  13986. return processFor(node, dir, context, forNode => {
  13987. // create the loop render function expression now, and add the
  13988. // iterator on exit after all children have been traversed
  13989. const renderExp = createCallExpression(helper(RENDER_LIST), [
  13990. forNode.source
  13991. ]);
  13992. const isTemplate = isTemplateNode(node);
  13993. const memo = findDir(node, 'memo');
  13994. const keyProp = findProp(node, `key`);
  13995. const keyExp = keyProp &&
  13996. (keyProp.type === 6 /* NodeTypes.ATTRIBUTE */
  13997. ? createSimpleExpression(keyProp.value.content, true)
  13998. : keyProp.exp);
  13999. const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
  14000. const isStableFragment = forNode.source.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  14001. forNode.source.constType > 0 /* ConstantTypes.NOT_CONSTANT */;
  14002. const fragmentFlag = isStableFragment
  14003. ? 64 /* PatchFlags.STABLE_FRAGMENT */
  14004. : keyProp
  14005. ? 128 /* PatchFlags.KEYED_FRAGMENT */
  14006. : 256 /* PatchFlags.UNKEYED_FRAGMENT */;
  14007. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
  14008. (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
  14009. return () => {
  14010. // finish the codegen now that all children have been traversed
  14011. let childBlock;
  14012. const { children } = forNode;
  14013. // check <template v-for> key placement
  14014. if (isTemplate) {
  14015. node.children.some(c => {
  14016. if (c.type === 1 /* NodeTypes.ELEMENT */) {
  14017. const key = findProp(c, 'key');
  14018. if (key) {
  14019. context.onError(createCompilerError(33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  14020. return true;
  14021. }
  14022. }
  14023. });
  14024. }
  14025. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* NodeTypes.ELEMENT */;
  14026. const slotOutlet = isSlotOutlet(node)
  14027. ? node
  14028. : isTemplate &&
  14029. node.children.length === 1 &&
  14030. isSlotOutlet(node.children[0])
  14031. ? node.children[0] // api-extractor somehow fails to infer this
  14032. : null;
  14033. if (slotOutlet) {
  14034. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  14035. childBlock = slotOutlet.codegenNode;
  14036. if (isTemplate && keyProperty) {
  14037. // <template v-for="..." :key="..."><slot/></template>
  14038. // we need to inject the key to the renderSlot() call.
  14039. // the props for renderSlot is passed as the 3rd argument.
  14040. injectProp(childBlock, keyProperty, context);
  14041. }
  14042. }
  14043. else if (needFragmentWrapper) {
  14044. // <template v-for="..."> with text or multi-elements
  14045. // should generate a fragment block for each loop
  14046. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* PatchFlags.STABLE_FRAGMENT */ +
  14047. (` /* ${PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */]} */`
  14048. ), undefined, undefined, true, undefined, false /* isComponent */);
  14049. }
  14050. else {
  14051. // Normal element v-for. Directly use the child's codegenNode
  14052. // but mark it as a block.
  14053. childBlock = children[0]
  14054. .codegenNode;
  14055. if (isTemplate && keyProperty) {
  14056. injectProp(childBlock, keyProperty, context);
  14057. }
  14058. if (childBlock.isBlock !== !isStableFragment) {
  14059. if (childBlock.isBlock) {
  14060. // switch from block to vnode
  14061. removeHelper(OPEN_BLOCK);
  14062. removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  14063. }
  14064. else {
  14065. // switch from vnode to block
  14066. removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  14067. }
  14068. }
  14069. childBlock.isBlock = !isStableFragment;
  14070. if (childBlock.isBlock) {
  14071. helper(OPEN_BLOCK);
  14072. helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  14073. }
  14074. else {
  14075. helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  14076. }
  14077. }
  14078. if (memo) {
  14079. const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
  14080. createSimpleExpression(`_cached`)
  14081. ]));
  14082. loop.body = createBlockStatement([
  14083. createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
  14084. createCompoundExpression([
  14085. `if (_cached`,
  14086. ...(keyExp ? [` && _cached.key === `, keyExp] : []),
  14087. ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
  14088. ]),
  14089. createCompoundExpression([`const _item = `, childBlock]),
  14090. createSimpleExpression(`_item.memo = _memo`),
  14091. createSimpleExpression(`return _item`)
  14092. ]);
  14093. renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
  14094. }
  14095. else {
  14096. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  14097. }
  14098. };
  14099. });
  14100. });
  14101. // target-agnostic transform used for both Client and SSR
  14102. function processFor(node, dir, context, processCodegen) {
  14103. if (!dir.exp) {
  14104. context.onError(createCompilerError(31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */, dir.loc));
  14105. return;
  14106. }
  14107. const parseResult = parseForExpression(
  14108. // can only be simple expression because vFor transform is applied
  14109. // before expression transform.
  14110. dir.exp, context);
  14111. if (!parseResult) {
  14112. context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  14113. return;
  14114. }
  14115. const { addIdentifiers, removeIdentifiers, scopes } = context;
  14116. const { source, value, key, index } = parseResult;
  14117. const forNode = {
  14118. type: 11 /* NodeTypes.FOR */,
  14119. loc: dir.loc,
  14120. source,
  14121. valueAlias: value,
  14122. keyAlias: key,
  14123. objectIndexAlias: index,
  14124. parseResult,
  14125. children: isTemplateNode(node) ? node.children : [node]
  14126. };
  14127. context.replaceNode(forNode);
  14128. // bookkeeping
  14129. scopes.vFor++;
  14130. const onExit = processCodegen && processCodegen(forNode);
  14131. return () => {
  14132. scopes.vFor--;
  14133. if (onExit)
  14134. onExit();
  14135. };
  14136. }
  14137. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  14138. // This regex doesn't cover the case if key or index aliases have destructuring,
  14139. // but those do not make sense in the first place, so this works in practice.
  14140. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  14141. const stripParensRE = /^\(|\)$/g;
  14142. function parseForExpression(input, context) {
  14143. const loc = input.loc;
  14144. const exp = input.content;
  14145. const inMatch = exp.match(forAliasRE);
  14146. if (!inMatch)
  14147. return;
  14148. const [, LHS, RHS] = inMatch;
  14149. const result = {
  14150. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  14151. value: undefined,
  14152. key: undefined,
  14153. index: undefined
  14154. };
  14155. {
  14156. validateBrowserExpression(result.source, context);
  14157. }
  14158. let valueContent = LHS.trim().replace(stripParensRE, '').trim();
  14159. const trimmedOffset = LHS.indexOf(valueContent);
  14160. const iteratorMatch = valueContent.match(forIteratorRE);
  14161. if (iteratorMatch) {
  14162. valueContent = valueContent.replace(forIteratorRE, '').trim();
  14163. const keyContent = iteratorMatch[1].trim();
  14164. let keyOffset;
  14165. if (keyContent) {
  14166. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  14167. result.key = createAliasExpression(loc, keyContent, keyOffset);
  14168. {
  14169. validateBrowserExpression(result.key, context, true);
  14170. }
  14171. }
  14172. if (iteratorMatch[2]) {
  14173. const indexContent = iteratorMatch[2].trim();
  14174. if (indexContent) {
  14175. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  14176. ? keyOffset + keyContent.length
  14177. : trimmedOffset + valueContent.length));
  14178. {
  14179. validateBrowserExpression(result.index, context, true);
  14180. }
  14181. }
  14182. }
  14183. }
  14184. if (valueContent) {
  14185. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  14186. {
  14187. validateBrowserExpression(result.value, context, true);
  14188. }
  14189. }
  14190. return result;
  14191. }
  14192. function createAliasExpression(range, content, offset) {
  14193. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  14194. }
  14195. function createForLoopParams({ value, key, index }, memoArgs = []) {
  14196. return createParamsList([value, key, index, ...memoArgs]);
  14197. }
  14198. function createParamsList(args) {
  14199. let i = args.length;
  14200. while (i--) {
  14201. if (args[i])
  14202. break;
  14203. }
  14204. return args
  14205. .slice(0, i + 1)
  14206. .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
  14207. }
  14208. const defaultFallback = createSimpleExpression(`undefined`, false);
  14209. // A NodeTransform that:
  14210. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  14211. // by transformExpression. This is only applied in non-browser builds with
  14212. // { prefixIdentifiers: true }.
  14213. // 2. Track v-slot depths so that we know a slot is inside another slot.
  14214. // Note the exit callback is executed before buildSlots() on the same node,
  14215. // so only nested slots see positive numbers.
  14216. const trackSlotScopes = (node, context) => {
  14217. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  14218. (node.tagType === 1 /* ElementTypes.COMPONENT */ ||
  14219. node.tagType === 3 /* ElementTypes.TEMPLATE */)) {
  14220. // We are only checking non-empty v-slot here
  14221. // since we only care about slots that introduce scope variables.
  14222. const vSlot = findDir(node, 'slot');
  14223. if (vSlot) {
  14224. vSlot.exp;
  14225. context.scopes.vSlot++;
  14226. return () => {
  14227. context.scopes.vSlot--;
  14228. };
  14229. }
  14230. }
  14231. };
  14232. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  14233. // Instead of being a DirectiveTransform, v-slot processing is called during
  14234. // transformElement to build the slots object for a component.
  14235. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  14236. context.helper(WITH_CTX);
  14237. const { children, loc } = node;
  14238. const slotsProperties = [];
  14239. const dynamicSlots = [];
  14240. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  14241. // since it likely uses a scope variable.
  14242. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  14243. // 1. Check for slot with slotProps on component itself.
  14244. // <Comp v-slot="{ prop }"/>
  14245. const onComponentSlot = findDir(node, 'slot', true);
  14246. if (onComponentSlot) {
  14247. const { arg, exp } = onComponentSlot;
  14248. if (arg && !isStaticExp(arg)) {
  14249. hasDynamicSlots = true;
  14250. }
  14251. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  14252. }
  14253. // 2. Iterate through children and check for template slots
  14254. // <template v-slot:foo="{ prop }">
  14255. let hasTemplateSlots = false;
  14256. let hasNamedDefaultSlot = false;
  14257. const implicitDefaultChildren = [];
  14258. const seenSlotNames = new Set();
  14259. let conditionalBranchIndex = 0;
  14260. for (let i = 0; i < children.length; i++) {
  14261. const slotElement = children[i];
  14262. let slotDir;
  14263. if (!isTemplateNode(slotElement) ||
  14264. !(slotDir = findDir(slotElement, 'slot', true))) {
  14265. // not a <template v-slot>, skip.
  14266. if (slotElement.type !== 3 /* NodeTypes.COMMENT */) {
  14267. implicitDefaultChildren.push(slotElement);
  14268. }
  14269. continue;
  14270. }
  14271. if (onComponentSlot) {
  14272. // already has on-component slot - this is incorrect usage.
  14273. context.onError(createCompilerError(37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  14274. break;
  14275. }
  14276. hasTemplateSlots = true;
  14277. const { children: slotChildren, loc: slotLoc } = slotElement;
  14278. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  14279. // check if name is dynamic.
  14280. let staticSlotName;
  14281. if (isStaticExp(slotName)) {
  14282. staticSlotName = slotName ? slotName.content : `default`;
  14283. }
  14284. else {
  14285. hasDynamicSlots = true;
  14286. }
  14287. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  14288. // check if this slot is conditional (v-if/v-for)
  14289. let vIf;
  14290. let vElse;
  14291. let vFor;
  14292. if ((vIf = findDir(slotElement, 'if'))) {
  14293. hasDynamicSlots = true;
  14294. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback));
  14295. }
  14296. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  14297. // find adjacent v-if
  14298. let j = i;
  14299. let prev;
  14300. while (j--) {
  14301. prev = children[j];
  14302. if (prev.type !== 3 /* NodeTypes.COMMENT */) {
  14303. break;
  14304. }
  14305. }
  14306. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  14307. // remove node
  14308. children.splice(i, 1);
  14309. i--;
  14310. // attach this slot to previous conditional
  14311. let conditional = dynamicSlots[dynamicSlots.length - 1];
  14312. while (conditional.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  14313. conditional = conditional.alternate;
  14314. }
  14315. conditional.alternate = vElse.exp
  14316. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback)
  14317. : buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++);
  14318. }
  14319. else {
  14320. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  14321. }
  14322. }
  14323. else if ((vFor = findDir(slotElement, 'for'))) {
  14324. hasDynamicSlots = true;
  14325. const parseResult = vFor.parseResult ||
  14326. parseForExpression(vFor.exp, context);
  14327. if (parseResult) {
  14328. // Render the dynamic slots as an array and add it to the createSlot()
  14329. // args. The runtime knows how to handle it appropriately.
  14330. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  14331. parseResult.source,
  14332. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  14333. ]));
  14334. }
  14335. else {
  14336. context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  14337. }
  14338. }
  14339. else {
  14340. // check duplicate static names
  14341. if (staticSlotName) {
  14342. if (seenSlotNames.has(staticSlotName)) {
  14343. context.onError(createCompilerError(38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  14344. continue;
  14345. }
  14346. seenSlotNames.add(staticSlotName);
  14347. if (staticSlotName === 'default') {
  14348. hasNamedDefaultSlot = true;
  14349. }
  14350. }
  14351. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  14352. }
  14353. }
  14354. if (!onComponentSlot) {
  14355. const buildDefaultSlotProperty = (props, children) => {
  14356. const fn = buildSlotFn(props, children, loc);
  14357. return createObjectProperty(`default`, fn);
  14358. };
  14359. if (!hasTemplateSlots) {
  14360. // implicit default slot (on component)
  14361. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  14362. }
  14363. else if (implicitDefaultChildren.length &&
  14364. // #3766
  14365. // with whitespace: 'preserve', whitespaces between slots will end up in
  14366. // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
  14367. implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
  14368. // implicit default slot (mixed with named slots)
  14369. if (hasNamedDefaultSlot) {
  14370. context.onError(createCompilerError(39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  14371. }
  14372. else {
  14373. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  14374. }
  14375. }
  14376. }
  14377. const slotFlag = hasDynamicSlots
  14378. ? 2 /* SlotFlags.DYNAMIC */
  14379. : hasForwardedSlots(node.children)
  14380. ? 3 /* SlotFlags.FORWARDED */
  14381. : 1 /* SlotFlags.STABLE */;
  14382. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  14383. // 2 = compiled but dynamic = can skip normalization, but must run diff
  14384. // 1 = compiled and static = can skip normalization AND diff as optimized
  14385. createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
  14386. if (dynamicSlots.length) {
  14387. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  14388. slots,
  14389. createArrayExpression(dynamicSlots)
  14390. ]);
  14391. }
  14392. return {
  14393. slots,
  14394. hasDynamicSlots
  14395. };
  14396. }
  14397. function buildDynamicSlot(name, fn, index) {
  14398. const props = [
  14399. createObjectProperty(`name`, name),
  14400. createObjectProperty(`fn`, fn)
  14401. ];
  14402. if (index != null) {
  14403. props.push(createObjectProperty(`key`, createSimpleExpression(String(index), true)));
  14404. }
  14405. return createObjectExpression(props);
  14406. }
  14407. function hasForwardedSlots(children) {
  14408. for (let i = 0; i < children.length; i++) {
  14409. const child = children[i];
  14410. switch (child.type) {
  14411. case 1 /* NodeTypes.ELEMENT */:
  14412. if (child.tagType === 2 /* ElementTypes.SLOT */ ||
  14413. hasForwardedSlots(child.children)) {
  14414. return true;
  14415. }
  14416. break;
  14417. case 9 /* NodeTypes.IF */:
  14418. if (hasForwardedSlots(child.branches))
  14419. return true;
  14420. break;
  14421. case 10 /* NodeTypes.IF_BRANCH */:
  14422. case 11 /* NodeTypes.FOR */:
  14423. if (hasForwardedSlots(child.children))
  14424. return true;
  14425. break;
  14426. }
  14427. }
  14428. return false;
  14429. }
  14430. function isNonWhitespaceContent(node) {
  14431. if (node.type !== 2 /* NodeTypes.TEXT */ && node.type !== 12 /* NodeTypes.TEXT_CALL */)
  14432. return true;
  14433. return node.type === 2 /* NodeTypes.TEXT */
  14434. ? !!node.content.trim()
  14435. : isNonWhitespaceContent(node.content);
  14436. }
  14437. // some directive transforms (e.g. v-model) may return a symbol for runtime
  14438. // import, which should be used instead of a resolveDirective call.
  14439. const directiveImportMap = new WeakMap();
  14440. // generate a JavaScript AST for this element's codegen
  14441. const transformElement = (node, context) => {
  14442. // perform the work on exit, after all child expressions have been
  14443. // processed and merged.
  14444. return function postTransformElement() {
  14445. node = context.currentNode;
  14446. if (!(node.type === 1 /* NodeTypes.ELEMENT */ &&
  14447. (node.tagType === 0 /* ElementTypes.ELEMENT */ ||
  14448. node.tagType === 1 /* ElementTypes.COMPONENT */))) {
  14449. return;
  14450. }
  14451. const { tag, props } = node;
  14452. const isComponent = node.tagType === 1 /* ElementTypes.COMPONENT */;
  14453. // The goal of the transform is to create a codegenNode implementing the
  14454. // VNodeCall interface.
  14455. let vnodeTag = isComponent
  14456. ? resolveComponentType(node, context)
  14457. : `"${tag}"`;
  14458. const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  14459. let vnodeProps;
  14460. let vnodeChildren;
  14461. let vnodePatchFlag;
  14462. let patchFlag = 0;
  14463. let vnodeDynamicProps;
  14464. let dynamicPropNames;
  14465. let vnodeDirectives;
  14466. let shouldUseBlock =
  14467. // dynamic component may resolve to plain elements
  14468. isDynamicComponent ||
  14469. vnodeTag === TELEPORT ||
  14470. vnodeTag === SUSPENSE ||
  14471. (!isComponent &&
  14472. // <svg> and <foreignObject> must be forced into blocks so that block
  14473. // updates inside get proper isSVG flag at runtime. (#639, #643)
  14474. // This is technically web-specific, but splitting the logic out of core
  14475. // leads to too much unnecessary complexity.
  14476. (tag === 'svg' || tag === 'foreignObject'));
  14477. // props
  14478. if (props.length > 0) {
  14479. const propsBuildResult = buildProps(node, context, undefined, isComponent, isDynamicComponent);
  14480. vnodeProps = propsBuildResult.props;
  14481. patchFlag = propsBuildResult.patchFlag;
  14482. dynamicPropNames = propsBuildResult.dynamicPropNames;
  14483. const directives = propsBuildResult.directives;
  14484. vnodeDirectives =
  14485. directives && directives.length
  14486. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  14487. : undefined;
  14488. if (propsBuildResult.shouldUseBlock) {
  14489. shouldUseBlock = true;
  14490. }
  14491. }
  14492. // children
  14493. if (node.children.length > 0) {
  14494. if (vnodeTag === KEEP_ALIVE) {
  14495. // Although a built-in component, we compile KeepAlive with raw children
  14496. // instead of slot functions so that it can be used inside Transition
  14497. // or other Transition-wrapping HOCs.
  14498. // To ensure correct updates with block optimizations, we need to:
  14499. // 1. Force keep-alive into a block. This avoids its children being
  14500. // collected by a parent block.
  14501. shouldUseBlock = true;
  14502. // 2. Force keep-alive to always be updated, since it uses raw children.
  14503. patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  14504. if (node.children.length > 1) {
  14505. context.onError(createCompilerError(46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */, {
  14506. start: node.children[0].loc.start,
  14507. end: node.children[node.children.length - 1].loc.end,
  14508. source: ''
  14509. }));
  14510. }
  14511. }
  14512. const shouldBuildAsSlots = isComponent &&
  14513. // Teleport is not a real component and has dedicated runtime handling
  14514. vnodeTag !== TELEPORT &&
  14515. // explained above.
  14516. vnodeTag !== KEEP_ALIVE;
  14517. if (shouldBuildAsSlots) {
  14518. const { slots, hasDynamicSlots } = buildSlots(node, context);
  14519. vnodeChildren = slots;
  14520. if (hasDynamicSlots) {
  14521. patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  14522. }
  14523. }
  14524. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  14525. const child = node.children[0];
  14526. const type = child.type;
  14527. // check for dynamic text children
  14528. const hasDynamicTextChild = type === 5 /* NodeTypes.INTERPOLATION */ ||
  14529. type === 8 /* NodeTypes.COMPOUND_EXPRESSION */;
  14530. if (hasDynamicTextChild &&
  14531. getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14532. patchFlag |= 1 /* PatchFlags.TEXT */;
  14533. }
  14534. // pass directly if the only child is a text node
  14535. // (plain / interpolation / expression)
  14536. if (hasDynamicTextChild || type === 2 /* NodeTypes.TEXT */) {
  14537. vnodeChildren = child;
  14538. }
  14539. else {
  14540. vnodeChildren = node.children;
  14541. }
  14542. }
  14543. else {
  14544. vnodeChildren = node.children;
  14545. }
  14546. }
  14547. // patchFlag & dynamicPropNames
  14548. if (patchFlag !== 0) {
  14549. {
  14550. if (patchFlag < 0) {
  14551. // special flags (negative and mutually exclusive)
  14552. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  14553. }
  14554. else {
  14555. // bitwise flags
  14556. const flagNames = Object.keys(PatchFlagNames)
  14557. .map(Number)
  14558. .filter(n => n > 0 && patchFlag & n)
  14559. .map(n => PatchFlagNames[n])
  14560. .join(`, `);
  14561. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  14562. }
  14563. }
  14564. if (dynamicPropNames && dynamicPropNames.length) {
  14565. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  14566. }
  14567. }
  14568. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
  14569. };
  14570. };
  14571. function resolveComponentType(node, context, ssr = false) {
  14572. let { tag } = node;
  14573. // 1. dynamic component
  14574. const isExplicitDynamic = isComponentTag(tag);
  14575. const isProp = findProp(node, 'is');
  14576. if (isProp) {
  14577. if (isExplicitDynamic ||
  14578. (false )) {
  14579. const exp = isProp.type === 6 /* NodeTypes.ATTRIBUTE */
  14580. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  14581. : isProp.exp;
  14582. if (exp) {
  14583. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  14584. exp
  14585. ]);
  14586. }
  14587. }
  14588. else if (isProp.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  14589. isProp.value.content.startsWith('vue:')) {
  14590. // <button is="vue:xxx">
  14591. // if not <component>, only is value that starts with "vue:" will be
  14592. // treated as component by the parse phase and reach here, unless it's
  14593. // compat mode where all is values are considered components
  14594. tag = isProp.value.content.slice(4);
  14595. }
  14596. }
  14597. // 1.5 v-is (TODO: Deprecate)
  14598. const isDir = !isExplicitDynamic && findDir(node, 'is');
  14599. if (isDir && isDir.exp) {
  14600. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  14601. isDir.exp
  14602. ]);
  14603. }
  14604. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  14605. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  14606. if (builtIn) {
  14607. // built-ins are simply fallthroughs / have special handling during ssr
  14608. // so we don't need to import their runtime equivalents
  14609. if (!ssr)
  14610. context.helper(builtIn);
  14611. return builtIn;
  14612. }
  14613. // 5. user component (resolve)
  14614. context.helper(RESOLVE_COMPONENT);
  14615. context.components.add(tag);
  14616. return toValidAssetId(tag, `component`);
  14617. }
  14618. function buildProps(node, context, props = node.props, isComponent, isDynamicComponent, ssr = false) {
  14619. const { tag, loc: elementLoc, children } = node;
  14620. let properties = [];
  14621. const mergeArgs = [];
  14622. const runtimeDirectives = [];
  14623. const hasChildren = children.length > 0;
  14624. let shouldUseBlock = false;
  14625. // patchFlag analysis
  14626. let patchFlag = 0;
  14627. let hasRef = false;
  14628. let hasClassBinding = false;
  14629. let hasStyleBinding = false;
  14630. let hasHydrationEventBinding = false;
  14631. let hasDynamicKeys = false;
  14632. let hasVnodeHook = false;
  14633. const dynamicPropNames = [];
  14634. const pushMergeArg = (arg) => {
  14635. if (properties.length) {
  14636. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  14637. properties = [];
  14638. }
  14639. if (arg)
  14640. mergeArgs.push(arg);
  14641. };
  14642. const analyzePatchFlag = ({ key, value }) => {
  14643. if (isStaticExp(key)) {
  14644. const name = key.content;
  14645. const isEventHandler = isOn(name);
  14646. if (isEventHandler &&
  14647. (!isComponent || isDynamicComponent) &&
  14648. // omit the flag for click handlers because hydration gives click
  14649. // dedicated fast path.
  14650. name.toLowerCase() !== 'onclick' &&
  14651. // omit v-model handlers
  14652. name !== 'onUpdate:modelValue' &&
  14653. // omit onVnodeXXX hooks
  14654. !isReservedProp(name)) {
  14655. hasHydrationEventBinding = true;
  14656. }
  14657. if (isEventHandler && isReservedProp(name)) {
  14658. hasVnodeHook = true;
  14659. }
  14660. if (value.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */ ||
  14661. ((value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  14662. value.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) &&
  14663. getConstantType(value, context) > 0)) {
  14664. // skip if the prop is a cached handler or has constant value
  14665. return;
  14666. }
  14667. if (name === 'ref') {
  14668. hasRef = true;
  14669. }
  14670. else if (name === 'class') {
  14671. hasClassBinding = true;
  14672. }
  14673. else if (name === 'style') {
  14674. hasStyleBinding = true;
  14675. }
  14676. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  14677. dynamicPropNames.push(name);
  14678. }
  14679. // treat the dynamic class and style binding of the component as dynamic props
  14680. if (isComponent &&
  14681. (name === 'class' || name === 'style') &&
  14682. !dynamicPropNames.includes(name)) {
  14683. dynamicPropNames.push(name);
  14684. }
  14685. }
  14686. else {
  14687. hasDynamicKeys = true;
  14688. }
  14689. };
  14690. for (let i = 0; i < props.length; i++) {
  14691. // static attribute
  14692. const prop = props[i];
  14693. if (prop.type === 6 /* NodeTypes.ATTRIBUTE */) {
  14694. const { loc, name, value } = prop;
  14695. let isStatic = true;
  14696. if (name === 'ref') {
  14697. hasRef = true;
  14698. if (context.scopes.vFor > 0) {
  14699. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  14700. }
  14701. }
  14702. // skip is on <component>, or is="vue:xxx"
  14703. if (name === 'is' &&
  14704. (isComponentTag(tag) ||
  14705. (value && value.content.startsWith('vue:')) ||
  14706. (false ))) {
  14707. continue;
  14708. }
  14709. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
  14710. }
  14711. else {
  14712. // directives
  14713. const { name, arg, exp, loc } = prop;
  14714. const isVBind = name === 'bind';
  14715. const isVOn = name === 'on';
  14716. // skip v-slot - it is handled by its dedicated transform.
  14717. if (name === 'slot') {
  14718. if (!isComponent) {
  14719. context.onError(createCompilerError(40 /* ErrorCodes.X_V_SLOT_MISPLACED */, loc));
  14720. }
  14721. continue;
  14722. }
  14723. // skip v-once/v-memo - they are handled by dedicated transforms.
  14724. if (name === 'once' || name === 'memo') {
  14725. continue;
  14726. }
  14727. // skip v-is and :is on <component>
  14728. if (name === 'is' ||
  14729. (isVBind &&
  14730. isStaticArgOf(arg, 'is') &&
  14731. (isComponentTag(tag) ||
  14732. (false )))) {
  14733. continue;
  14734. }
  14735. // skip v-on in SSR compilation
  14736. if (isVOn && ssr) {
  14737. continue;
  14738. }
  14739. if (
  14740. // #938: elements with dynamic keys should be forced into blocks
  14741. (isVBind && isStaticArgOf(arg, 'key')) ||
  14742. // inline before-update hooks need to force block so that it is invoked
  14743. // before children
  14744. (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
  14745. shouldUseBlock = true;
  14746. }
  14747. if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
  14748. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  14749. }
  14750. // special case for v-bind and v-on with no argument
  14751. if (!arg && (isVBind || isVOn)) {
  14752. hasDynamicKeys = true;
  14753. if (exp) {
  14754. if (isVBind) {
  14755. // have to merge early for compat build check
  14756. pushMergeArg();
  14757. mergeArgs.push(exp);
  14758. }
  14759. else {
  14760. // v-on="obj" -> toHandlers(obj)
  14761. pushMergeArg({
  14762. type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
  14763. loc,
  14764. callee: context.helper(TO_HANDLERS),
  14765. arguments: isComponent ? [exp] : [exp, `true`]
  14766. });
  14767. }
  14768. }
  14769. else {
  14770. context.onError(createCompilerError(isVBind
  14771. ? 34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */
  14772. : 35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
  14773. }
  14774. continue;
  14775. }
  14776. const directiveTransform = context.directiveTransforms[name];
  14777. if (directiveTransform) {
  14778. // has built-in directive transform.
  14779. const { props, needRuntime } = directiveTransform(prop, node, context);
  14780. !ssr && props.forEach(analyzePatchFlag);
  14781. if (isVOn && arg && !isStaticExp(arg)) {
  14782. pushMergeArg(createObjectExpression(props, elementLoc));
  14783. }
  14784. else {
  14785. properties.push(...props);
  14786. }
  14787. if (needRuntime) {
  14788. runtimeDirectives.push(prop);
  14789. if (isSymbol(needRuntime)) {
  14790. directiveImportMap.set(prop, needRuntime);
  14791. }
  14792. }
  14793. }
  14794. else if (!isBuiltInDirective(name)) {
  14795. // no built-in transform, this is a user custom directive.
  14796. runtimeDirectives.push(prop);
  14797. // custom dirs may use beforeUpdate so they need to force blocks
  14798. // to ensure before-update gets called before children update
  14799. if (hasChildren) {
  14800. shouldUseBlock = true;
  14801. }
  14802. }
  14803. }
  14804. }
  14805. let propsExpression = undefined;
  14806. // has v-bind="object" or v-on="object", wrap with mergeProps
  14807. if (mergeArgs.length) {
  14808. // close up any not-yet-merged props
  14809. pushMergeArg();
  14810. if (mergeArgs.length > 1) {
  14811. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  14812. }
  14813. else {
  14814. // single v-bind with nothing else - no need for a mergeProps call
  14815. propsExpression = mergeArgs[0];
  14816. }
  14817. }
  14818. else if (properties.length) {
  14819. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  14820. }
  14821. // patchFlag analysis
  14822. if (hasDynamicKeys) {
  14823. patchFlag |= 16 /* PatchFlags.FULL_PROPS */;
  14824. }
  14825. else {
  14826. if (hasClassBinding && !isComponent) {
  14827. patchFlag |= 2 /* PatchFlags.CLASS */;
  14828. }
  14829. if (hasStyleBinding && !isComponent) {
  14830. patchFlag |= 4 /* PatchFlags.STYLE */;
  14831. }
  14832. if (dynamicPropNames.length) {
  14833. patchFlag |= 8 /* PatchFlags.PROPS */;
  14834. }
  14835. if (hasHydrationEventBinding) {
  14836. patchFlag |= 32 /* PatchFlags.HYDRATE_EVENTS */;
  14837. }
  14838. }
  14839. if (!shouldUseBlock &&
  14840. (patchFlag === 0 || patchFlag === 32 /* PatchFlags.HYDRATE_EVENTS */) &&
  14841. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  14842. patchFlag |= 512 /* PatchFlags.NEED_PATCH */;
  14843. }
  14844. // pre-normalize props, SSR is skipped for now
  14845. if (!context.inSSR && propsExpression) {
  14846. switch (propsExpression.type) {
  14847. case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
  14848. // means that there is no v-bind,
  14849. // but still need to deal with dynamic key binding
  14850. let classKeyIndex = -1;
  14851. let styleKeyIndex = -1;
  14852. let hasDynamicKey = false;
  14853. for (let i = 0; i < propsExpression.properties.length; i++) {
  14854. const key = propsExpression.properties[i].key;
  14855. if (isStaticExp(key)) {
  14856. if (key.content === 'class') {
  14857. classKeyIndex = i;
  14858. }
  14859. else if (key.content === 'style') {
  14860. styleKeyIndex = i;
  14861. }
  14862. }
  14863. else if (!key.isHandlerKey) {
  14864. hasDynamicKey = true;
  14865. }
  14866. }
  14867. const classProp = propsExpression.properties[classKeyIndex];
  14868. const styleProp = propsExpression.properties[styleKeyIndex];
  14869. // no dynamic key
  14870. if (!hasDynamicKey) {
  14871. if (classProp && !isStaticExp(classProp.value)) {
  14872. classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
  14873. }
  14874. if (styleProp &&
  14875. // the static style is compiled into an object,
  14876. // so use `hasStyleBinding` to ensure that it is a dynamic style binding
  14877. (hasStyleBinding ||
  14878. (styleProp.value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  14879. styleProp.value.content.trim()[0] === `[`) ||
  14880. // v-bind:style and style both exist,
  14881. // v-bind:style with static literal object
  14882. styleProp.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */)) {
  14883. styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
  14884. }
  14885. }
  14886. else {
  14887. // dynamic key binding, wrap with `normalizeProps`
  14888. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
  14889. }
  14890. break;
  14891. case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
  14892. // mergeProps call, do nothing
  14893. break;
  14894. default:
  14895. // single v-bind
  14896. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
  14897. createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
  14898. propsExpression
  14899. ])
  14900. ]);
  14901. break;
  14902. }
  14903. }
  14904. return {
  14905. props: propsExpression,
  14906. directives: runtimeDirectives,
  14907. patchFlag,
  14908. dynamicPropNames,
  14909. shouldUseBlock
  14910. };
  14911. }
  14912. // Dedupe props in an object literal.
  14913. // Literal duplicated attributes would have been warned during the parse phase,
  14914. // however, it's possible to encounter duplicated `onXXX` handlers with different
  14915. // modifiers. We also need to merge static and dynamic class / style attributes.
  14916. // - onXXX handlers / style: merge into array
  14917. // - class: merge into single expression with concatenation
  14918. function dedupeProperties(properties) {
  14919. const knownProps = new Map();
  14920. const deduped = [];
  14921. for (let i = 0; i < properties.length; i++) {
  14922. const prop = properties[i];
  14923. // dynamic keys are always allowed
  14924. if (prop.key.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  14925. deduped.push(prop);
  14926. continue;
  14927. }
  14928. const name = prop.key.content;
  14929. const existing = knownProps.get(name);
  14930. if (existing) {
  14931. if (name === 'style' || name === 'class' || isOn(name)) {
  14932. mergeAsArray$1(existing, prop);
  14933. }
  14934. // unexpected duplicate, should have emitted error during parse
  14935. }
  14936. else {
  14937. knownProps.set(name, prop);
  14938. deduped.push(prop);
  14939. }
  14940. }
  14941. return deduped;
  14942. }
  14943. function mergeAsArray$1(existing, incoming) {
  14944. if (existing.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */) {
  14945. existing.value.elements.push(incoming.value);
  14946. }
  14947. else {
  14948. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  14949. }
  14950. }
  14951. function buildDirectiveArgs(dir, context) {
  14952. const dirArgs = [];
  14953. const runtime = directiveImportMap.get(dir);
  14954. if (runtime) {
  14955. // built-in directive with runtime
  14956. dirArgs.push(context.helperString(runtime));
  14957. }
  14958. else {
  14959. {
  14960. // inject statement for resolving directive
  14961. context.helper(RESOLVE_DIRECTIVE);
  14962. context.directives.add(dir.name);
  14963. dirArgs.push(toValidAssetId(dir.name, `directive`));
  14964. }
  14965. }
  14966. const { loc } = dir;
  14967. if (dir.exp)
  14968. dirArgs.push(dir.exp);
  14969. if (dir.arg) {
  14970. if (!dir.exp) {
  14971. dirArgs.push(`void 0`);
  14972. }
  14973. dirArgs.push(dir.arg);
  14974. }
  14975. if (Object.keys(dir.modifiers).length) {
  14976. if (!dir.arg) {
  14977. if (!dir.exp) {
  14978. dirArgs.push(`void 0`);
  14979. }
  14980. dirArgs.push(`void 0`);
  14981. }
  14982. const trueExpression = createSimpleExpression(`true`, false, loc);
  14983. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  14984. }
  14985. return createArrayExpression(dirArgs, dir.loc);
  14986. }
  14987. function stringifyDynamicPropNames(props) {
  14988. let propsNamesString = `[`;
  14989. for (let i = 0, l = props.length; i < l; i++) {
  14990. propsNamesString += JSON.stringify(props[i]);
  14991. if (i < l - 1)
  14992. propsNamesString += ', ';
  14993. }
  14994. return propsNamesString + `]`;
  14995. }
  14996. function isComponentTag(tag) {
  14997. return tag === 'component' || tag === 'Component';
  14998. }
  14999. const transformSlotOutlet = (node, context) => {
  15000. if (isSlotOutlet(node)) {
  15001. const { children, loc } = node;
  15002. const { slotName, slotProps } = processSlotOutlet(node, context);
  15003. const slotArgs = [
  15004. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  15005. slotName,
  15006. '{}',
  15007. 'undefined',
  15008. 'true'
  15009. ];
  15010. let expectedLen = 2;
  15011. if (slotProps) {
  15012. slotArgs[2] = slotProps;
  15013. expectedLen = 3;
  15014. }
  15015. if (children.length) {
  15016. slotArgs[3] = createFunctionExpression([], children, false, false, loc);
  15017. expectedLen = 4;
  15018. }
  15019. if (context.scopeId && !context.slotted) {
  15020. expectedLen = 5;
  15021. }
  15022. slotArgs.splice(expectedLen); // remove unused arguments
  15023. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  15024. }
  15025. };
  15026. function processSlotOutlet(node, context) {
  15027. let slotName = `"default"`;
  15028. let slotProps = undefined;
  15029. const nonNameProps = [];
  15030. for (let i = 0; i < node.props.length; i++) {
  15031. const p = node.props[i];
  15032. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  15033. if (p.value) {
  15034. if (p.name === 'name') {
  15035. slotName = JSON.stringify(p.value.content);
  15036. }
  15037. else {
  15038. p.name = camelize(p.name);
  15039. nonNameProps.push(p);
  15040. }
  15041. }
  15042. }
  15043. else {
  15044. if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
  15045. if (p.exp)
  15046. slotName = p.exp;
  15047. }
  15048. else {
  15049. if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
  15050. p.arg.content = camelize(p.arg.content);
  15051. }
  15052. nonNameProps.push(p);
  15053. }
  15054. }
  15055. }
  15056. if (nonNameProps.length > 0) {
  15057. const { props, directives } = buildProps(node, context, nonNameProps, false, false);
  15058. slotProps = props;
  15059. if (directives.length) {
  15060. context.onError(createCompilerError(36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  15061. }
  15062. }
  15063. return {
  15064. slotName,
  15065. slotProps
  15066. };
  15067. }
  15068. const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*(:[^=]+)?=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
  15069. const transformOn = (dir, node, context, augmentor) => {
  15070. const { loc, modifiers, arg } = dir;
  15071. if (!dir.exp && !modifiers.length) {
  15072. context.onError(createCompilerError(35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
  15073. }
  15074. let eventName;
  15075. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  15076. if (arg.isStatic) {
  15077. let rawName = arg.content;
  15078. // TODO deprecate @vnodeXXX usage
  15079. if (rawName.startsWith('vue:')) {
  15080. rawName = `vnode-${rawName.slice(4)}`;
  15081. }
  15082. const eventString = node.tagType !== 0 /* ElementTypes.ELEMENT */ ||
  15083. rawName.startsWith('vnode') ||
  15084. !/[A-Z]/.test(rawName)
  15085. ? // for non-element and vnode lifecycle event listeners, auto convert
  15086. // it to camelCase. See issue #2249
  15087. toHandlerKey(camelize(rawName))
  15088. : // preserve case for plain element listeners that have uppercase
  15089. // letters, as these may be custom elements' custom events
  15090. `on:${rawName}`;
  15091. eventName = createSimpleExpression(eventString, true, arg.loc);
  15092. }
  15093. else {
  15094. // #2388
  15095. eventName = createCompoundExpression([
  15096. `${context.helperString(TO_HANDLER_KEY)}(`,
  15097. arg,
  15098. `)`
  15099. ]);
  15100. }
  15101. }
  15102. else {
  15103. // already a compound expression.
  15104. eventName = arg;
  15105. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  15106. eventName.children.push(`)`);
  15107. }
  15108. // handler processing
  15109. let exp = dir.exp;
  15110. if (exp && !exp.content.trim()) {
  15111. exp = undefined;
  15112. }
  15113. let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
  15114. if (exp) {
  15115. const isMemberExp = isMemberExpression(exp.content);
  15116. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  15117. const hasMultipleStatements = exp.content.includes(`;`);
  15118. {
  15119. validateBrowserExpression(exp, context, false, hasMultipleStatements);
  15120. }
  15121. if (isInlineStatement || (shouldCache && isMemberExp)) {
  15122. // wrap inline statement in a function expression
  15123. exp = createCompoundExpression([
  15124. `${isInlineStatement
  15125. ? `$event`
  15126. : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  15127. exp,
  15128. hasMultipleStatements ? `}` : `)`
  15129. ]);
  15130. }
  15131. }
  15132. let ret = {
  15133. props: [
  15134. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  15135. ]
  15136. };
  15137. // apply extended compiler augmentor
  15138. if (augmentor) {
  15139. ret = augmentor(ret);
  15140. }
  15141. if (shouldCache) {
  15142. // cache handlers so that it's always the same handler being passed down.
  15143. // this avoids unnecessary re-renders when users use inline handlers on
  15144. // components.
  15145. ret.props[0].value = context.cache(ret.props[0].value);
  15146. }
  15147. // mark the key as handler for props normalization check
  15148. ret.props.forEach(p => (p.key.isHandlerKey = true));
  15149. return ret;
  15150. };
  15151. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  15152. // codegen for the entire props object. This transform here is only for v-bind
  15153. // *with* args.
  15154. const transformBind = (dir, _node, context) => {
  15155. const { exp, modifiers, loc } = dir;
  15156. const arg = dir.arg;
  15157. if (arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  15158. arg.children.unshift(`(`);
  15159. arg.children.push(`) || ""`);
  15160. }
  15161. else if (!arg.isStatic) {
  15162. arg.content = `${arg.content} || ""`;
  15163. }
  15164. // .sync is replaced by v-model:arg
  15165. if (modifiers.includes('camel')) {
  15166. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  15167. if (arg.isStatic) {
  15168. arg.content = camelize(arg.content);
  15169. }
  15170. else {
  15171. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  15172. }
  15173. }
  15174. else {
  15175. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  15176. arg.children.push(`)`);
  15177. }
  15178. }
  15179. if (!context.inSSR) {
  15180. if (modifiers.includes('prop')) {
  15181. injectPrefix(arg, '.');
  15182. }
  15183. if (modifiers.includes('attr')) {
  15184. injectPrefix(arg, '^');
  15185. }
  15186. }
  15187. if (!exp ||
  15188. (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  15189. context.onError(createCompilerError(34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */, loc));
  15190. return {
  15191. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  15192. };
  15193. }
  15194. return {
  15195. props: [createObjectProperty(arg, exp)]
  15196. };
  15197. };
  15198. const injectPrefix = (arg, prefix) => {
  15199. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  15200. if (arg.isStatic) {
  15201. arg.content = prefix + arg.content;
  15202. }
  15203. else {
  15204. arg.content = `\`${prefix}\${${arg.content}}\``;
  15205. }
  15206. }
  15207. else {
  15208. arg.children.unshift(`'${prefix}' + (`);
  15209. arg.children.push(`)`);
  15210. }
  15211. };
  15212. // Merge adjacent text nodes and expressions into a single expression
  15213. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  15214. const transformText = (node, context) => {
  15215. if (node.type === 0 /* NodeTypes.ROOT */ ||
  15216. node.type === 1 /* NodeTypes.ELEMENT */ ||
  15217. node.type === 11 /* NodeTypes.FOR */ ||
  15218. node.type === 10 /* NodeTypes.IF_BRANCH */) {
  15219. // perform the transform on node exit so that all expressions have already
  15220. // been processed.
  15221. return () => {
  15222. const children = node.children;
  15223. let currentContainer = undefined;
  15224. let hasText = false;
  15225. for (let i = 0; i < children.length; i++) {
  15226. const child = children[i];
  15227. if (isText(child)) {
  15228. hasText = true;
  15229. for (let j = i + 1; j < children.length; j++) {
  15230. const next = children[j];
  15231. if (isText(next)) {
  15232. if (!currentContainer) {
  15233. currentContainer = children[i] = createCompoundExpression([child], child.loc);
  15234. }
  15235. // merge adjacent text node into current
  15236. currentContainer.children.push(` + `, next);
  15237. children.splice(j, 1);
  15238. j--;
  15239. }
  15240. else {
  15241. currentContainer = undefined;
  15242. break;
  15243. }
  15244. }
  15245. }
  15246. }
  15247. if (!hasText ||
  15248. // if this is a plain element with a single text child, leave it
  15249. // as-is since the runtime has dedicated fast path for this by directly
  15250. // setting textContent of the element.
  15251. // for component root it's always normalized anyway.
  15252. (children.length === 1 &&
  15253. (node.type === 0 /* NodeTypes.ROOT */ ||
  15254. (node.type === 1 /* NodeTypes.ELEMENT */ &&
  15255. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  15256. // #3756
  15257. // custom directives can potentially add DOM elements arbitrarily,
  15258. // we need to avoid setting textContent of the element at runtime
  15259. // to avoid accidentally overwriting the DOM elements added
  15260. // by the user through custom directives.
  15261. !node.props.find(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  15262. !context.directiveTransforms[p.name]) &&
  15263. // in compat mode, <template> tags with no special directives
  15264. // will be rendered as a fragment so its children must be
  15265. // converted into vnodes.
  15266. !(false ))))) {
  15267. return;
  15268. }
  15269. // pre-convert text nodes into createTextVNode(text) calls to avoid
  15270. // runtime normalization.
  15271. for (let i = 0; i < children.length; i++) {
  15272. const child = children[i];
  15273. if (isText(child) || child.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  15274. const callArgs = [];
  15275. // createTextVNode defaults to single whitespace, so if it is a
  15276. // single space the code could be an empty call to save bytes.
  15277. if (child.type !== 2 /* NodeTypes.TEXT */ || child.content !== ' ') {
  15278. callArgs.push(child);
  15279. }
  15280. // mark dynamic text with flag so it gets patched inside a block
  15281. if (!context.ssr &&
  15282. getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
  15283. callArgs.push(1 /* PatchFlags.TEXT */ +
  15284. (` /* ${PatchFlagNames[1 /* PatchFlags.TEXT */]} */` ));
  15285. }
  15286. children[i] = {
  15287. type: 12 /* NodeTypes.TEXT_CALL */,
  15288. content: child,
  15289. loc: child.loc,
  15290. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  15291. };
  15292. }
  15293. }
  15294. };
  15295. }
  15296. };
  15297. const seen = new WeakSet();
  15298. const transformOnce = (node, context) => {
  15299. if (node.type === 1 /* NodeTypes.ELEMENT */ && findDir(node, 'once', true)) {
  15300. if (seen.has(node) || context.inVOnce) {
  15301. return;
  15302. }
  15303. seen.add(node);
  15304. context.inVOnce = true;
  15305. context.helper(SET_BLOCK_TRACKING);
  15306. return () => {
  15307. context.inVOnce = false;
  15308. const cur = context.currentNode;
  15309. if (cur.codegenNode) {
  15310. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  15311. }
  15312. };
  15313. }
  15314. };
  15315. const transformModel = (dir, node, context) => {
  15316. const { exp, arg } = dir;
  15317. if (!exp) {
  15318. context.onError(createCompilerError(41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */, dir.loc));
  15319. return createTransformProps();
  15320. }
  15321. const rawExp = exp.loc.source;
  15322. const expString = exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ? exp.content : rawExp;
  15323. // im SFC <script setup> inline mode, the exp may have been transformed into
  15324. // _unref(exp)
  15325. const bindingType = context.bindingMetadata[rawExp];
  15326. // check props
  15327. if (bindingType === "props" /* BindingTypes.PROPS */ ||
  15328. bindingType === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
  15329. context.onError(createCompilerError(44 /* ErrorCodes.X_V_MODEL_ON_PROPS */, exp.loc));
  15330. return createTransformProps();
  15331. }
  15332. const maybeRef = !true ;
  15333. if (!expString.trim() ||
  15334. (!isMemberExpression(expString) && !maybeRef)) {
  15335. context.onError(createCompilerError(42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  15336. return createTransformProps();
  15337. }
  15338. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  15339. const eventName = arg
  15340. ? isStaticExp(arg)
  15341. ? `onUpdate:${arg.content}`
  15342. : createCompoundExpression(['"onUpdate:" + ', arg])
  15343. : `onUpdate:modelValue`;
  15344. let assignmentExp;
  15345. const eventArg = context.isTS ? `($event: any)` : `$event`;
  15346. {
  15347. assignmentExp = createCompoundExpression([
  15348. `${eventArg} => ((`,
  15349. exp,
  15350. `) = $event)`
  15351. ]);
  15352. }
  15353. const props = [
  15354. // modelValue: foo
  15355. createObjectProperty(propName, dir.exp),
  15356. // "onUpdate:modelValue": $event => (foo = $event)
  15357. createObjectProperty(eventName, assignmentExp)
  15358. ];
  15359. // modelModifiers: { foo: true, "bar-baz": true }
  15360. if (dir.modifiers.length && node.tagType === 1 /* ElementTypes.COMPONENT */) {
  15361. const modifiers = dir.modifiers
  15362. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  15363. .join(`, `);
  15364. const modifiersKey = arg
  15365. ? isStaticExp(arg)
  15366. ? `${arg.content}Modifiers`
  15367. : createCompoundExpression([arg, ' + "Modifiers"'])
  15368. : `modelModifiers`;
  15369. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* ConstantTypes.CAN_HOIST */)));
  15370. }
  15371. return createTransformProps(props);
  15372. };
  15373. function createTransformProps(props = []) {
  15374. return { props };
  15375. }
  15376. const seen$1 = new WeakSet();
  15377. const transformMemo = (node, context) => {
  15378. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  15379. const dir = findDir(node, 'memo');
  15380. if (!dir || seen$1.has(node)) {
  15381. return;
  15382. }
  15383. seen$1.add(node);
  15384. return () => {
  15385. const codegenNode = node.codegenNode ||
  15386. context.currentNode.codegenNode;
  15387. if (codegenNode && codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  15388. // non-component sub tree should be turned into a block
  15389. if (node.tagType !== 1 /* ElementTypes.COMPONENT */) {
  15390. makeBlock(codegenNode, context);
  15391. }
  15392. node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
  15393. dir.exp,
  15394. createFunctionExpression(undefined, codegenNode),
  15395. `_cache`,
  15396. String(context.cached++)
  15397. ]);
  15398. }
  15399. };
  15400. }
  15401. };
  15402. function getBaseTransformPreset(prefixIdentifiers) {
  15403. return [
  15404. [
  15405. transformOnce,
  15406. transformIf,
  15407. transformMemo,
  15408. transformFor,
  15409. ...([]),
  15410. ...([transformExpression]
  15411. ),
  15412. transformSlotOutlet,
  15413. transformElement,
  15414. trackSlotScopes,
  15415. transformText
  15416. ],
  15417. {
  15418. on: transformOn,
  15419. bind: transformBind,
  15420. model: transformModel
  15421. }
  15422. ];
  15423. }
  15424. // we name it `baseCompile` so that higher order compilers like
  15425. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  15426. function baseCompile(template, options = {}) {
  15427. const onError = options.onError || defaultOnError;
  15428. const isModuleMode = options.mode === 'module';
  15429. /* istanbul ignore if */
  15430. {
  15431. if (options.prefixIdentifiers === true) {
  15432. onError(createCompilerError(47 /* ErrorCodes.X_PREFIX_ID_NOT_SUPPORTED */));
  15433. }
  15434. else if (isModuleMode) {
  15435. onError(createCompilerError(48 /* ErrorCodes.X_MODULE_MODE_NOT_SUPPORTED */));
  15436. }
  15437. }
  15438. const prefixIdentifiers = !true ;
  15439. if (options.cacheHandlers) {
  15440. onError(createCompilerError(49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */));
  15441. }
  15442. if (options.scopeId && !isModuleMode) {
  15443. onError(createCompilerError(50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */));
  15444. }
  15445. const ast = isString(template) ? baseParse(template, options) : template;
  15446. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
  15447. transform(ast, extend({}, options, {
  15448. prefixIdentifiers,
  15449. nodeTransforms: [
  15450. ...nodeTransforms,
  15451. ...(options.nodeTransforms || []) // user transforms
  15452. ],
  15453. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  15454. )
  15455. }));
  15456. return generate(ast, extend({}, options, {
  15457. prefixIdentifiers
  15458. }));
  15459. }
  15460. const noopDirectiveTransform = () => ({ props: [] });
  15461. const V_MODEL_RADIO = Symbol(`vModelRadio` );
  15462. const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
  15463. const V_MODEL_TEXT = Symbol(`vModelText` );
  15464. const V_MODEL_SELECT = Symbol(`vModelSelect` );
  15465. const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
  15466. const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
  15467. const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
  15468. const V_SHOW = Symbol(`vShow` );
  15469. const TRANSITION$1 = Symbol(`Transition` );
  15470. const TRANSITION_GROUP = Symbol(`TransitionGroup` );
  15471. registerRuntimeHelpers({
  15472. [V_MODEL_RADIO]: `vModelRadio`,
  15473. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  15474. [V_MODEL_TEXT]: `vModelText`,
  15475. [V_MODEL_SELECT]: `vModelSelect`,
  15476. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  15477. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  15478. [V_ON_WITH_KEYS]: `withKeys`,
  15479. [V_SHOW]: `vShow`,
  15480. [TRANSITION$1]: `Transition`,
  15481. [TRANSITION_GROUP]: `TransitionGroup`
  15482. });
  15483. /* eslint-disable no-restricted-globals */
  15484. let decoder;
  15485. function decodeHtmlBrowser(raw, asAttr = false) {
  15486. if (!decoder) {
  15487. decoder = document.createElement('div');
  15488. }
  15489. if (asAttr) {
  15490. decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
  15491. return decoder.children[0].getAttribute('foo');
  15492. }
  15493. else {
  15494. decoder.innerHTML = raw;
  15495. return decoder.textContent;
  15496. }
  15497. }
  15498. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  15499. const parserOptions = {
  15500. isVoidTag,
  15501. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  15502. isPreTag: tag => tag === 'pre',
  15503. decodeEntities: decodeHtmlBrowser ,
  15504. isBuiltInComponent: (tag) => {
  15505. if (isBuiltInType(tag, `Transition`)) {
  15506. return TRANSITION$1;
  15507. }
  15508. else if (isBuiltInType(tag, `TransitionGroup`)) {
  15509. return TRANSITION_GROUP;
  15510. }
  15511. },
  15512. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  15513. getNamespace(tag, parent) {
  15514. let ns = parent ? parent.ns : 0 /* DOMNamespaces.HTML */;
  15515. if (parent && ns === 2 /* DOMNamespaces.MATH_ML */) {
  15516. if (parent.tag === 'annotation-xml') {
  15517. if (tag === 'svg') {
  15518. return 1 /* DOMNamespaces.SVG */;
  15519. }
  15520. if (parent.props.some(a => a.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  15521. a.name === 'encoding' &&
  15522. a.value != null &&
  15523. (a.value.content === 'text/html' ||
  15524. a.value.content === 'application/xhtml+xml'))) {
  15525. ns = 0 /* DOMNamespaces.HTML */;
  15526. }
  15527. }
  15528. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  15529. tag !== 'mglyph' &&
  15530. tag !== 'malignmark') {
  15531. ns = 0 /* DOMNamespaces.HTML */;
  15532. }
  15533. }
  15534. else if (parent && ns === 1 /* DOMNamespaces.SVG */) {
  15535. if (parent.tag === 'foreignObject' ||
  15536. parent.tag === 'desc' ||
  15537. parent.tag === 'title') {
  15538. ns = 0 /* DOMNamespaces.HTML */;
  15539. }
  15540. }
  15541. if (ns === 0 /* DOMNamespaces.HTML */) {
  15542. if (tag === 'svg') {
  15543. return 1 /* DOMNamespaces.SVG */;
  15544. }
  15545. if (tag === 'math') {
  15546. return 2 /* DOMNamespaces.MATH_ML */;
  15547. }
  15548. }
  15549. return ns;
  15550. },
  15551. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  15552. getTextMode({ tag, ns }) {
  15553. if (ns === 0 /* DOMNamespaces.HTML */) {
  15554. if (tag === 'textarea' || tag === 'title') {
  15555. return 1 /* TextModes.RCDATA */;
  15556. }
  15557. if (isRawTextContainer(tag)) {
  15558. return 2 /* TextModes.RAWTEXT */;
  15559. }
  15560. }
  15561. return 0 /* TextModes.DATA */;
  15562. }
  15563. };
  15564. // Parse inline CSS strings for static style attributes into an object.
  15565. // This is a NodeTransform since it works on the static `style` attribute and
  15566. // converts it into a dynamic equivalent:
  15567. // style="color: red" -> :style='{ "color": "red" }'
  15568. // It is then processed by `transformElement` and included in the generated
  15569. // props.
  15570. const transformStyle = node => {
  15571. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  15572. node.props.forEach((p, i) => {
  15573. if (p.type === 6 /* NodeTypes.ATTRIBUTE */ && p.name === 'style' && p.value) {
  15574. // replace p with an expression node
  15575. node.props[i] = {
  15576. type: 7 /* NodeTypes.DIRECTIVE */,
  15577. name: `bind`,
  15578. arg: createSimpleExpression(`style`, true, p.loc),
  15579. exp: parseInlineCSS(p.value.content, p.loc),
  15580. modifiers: [],
  15581. loc: p.loc
  15582. };
  15583. }
  15584. });
  15585. }
  15586. };
  15587. const parseInlineCSS = (cssText, loc) => {
  15588. const normalized = parseStringStyle(cssText);
  15589. return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  15590. };
  15591. function createDOMCompilerError(code, loc) {
  15592. return createCompilerError(code, loc, DOMErrorMessages );
  15593. }
  15594. const DOMErrorMessages = {
  15595. [51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  15596. [52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  15597. [53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  15598. [54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  15599. [55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  15600. [56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  15601. [57 /* DOMErrorCodes.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.`,
  15602. [58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  15603. [59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  15604. [60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  15605. [61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  15606. };
  15607. const transformVHtml = (dir, node, context) => {
  15608. const { exp, loc } = dir;
  15609. if (!exp) {
  15610. context.onError(createDOMCompilerError(51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */, loc));
  15611. }
  15612. if (node.children.length) {
  15613. context.onError(createDOMCompilerError(52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */, loc));
  15614. node.children.length = 0;
  15615. }
  15616. return {
  15617. props: [
  15618. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  15619. ]
  15620. };
  15621. };
  15622. const transformVText = (dir, node, context) => {
  15623. const { exp, loc } = dir;
  15624. if (!exp) {
  15625. context.onError(createDOMCompilerError(53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */, loc));
  15626. }
  15627. if (node.children.length) {
  15628. context.onError(createDOMCompilerError(54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */, loc));
  15629. node.children.length = 0;
  15630. }
  15631. return {
  15632. props: [
  15633. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  15634. ? getConstantType(exp, context) > 0
  15635. ? exp
  15636. : createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  15637. : createSimpleExpression('', true))
  15638. ]
  15639. };
  15640. };
  15641. const transformModel$1 = (dir, node, context) => {
  15642. const baseResult = transformModel(dir, node, context);
  15643. // base transform has errors OR component v-model (only need props)
  15644. if (!baseResult.props.length || node.tagType === 1 /* ElementTypes.COMPONENT */) {
  15645. return baseResult;
  15646. }
  15647. if (dir.arg) {
  15648. context.onError(createDOMCompilerError(56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  15649. }
  15650. function checkDuplicatedValue() {
  15651. const value = findProp(node, 'value');
  15652. if (value) {
  15653. context.onError(createDOMCompilerError(58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  15654. }
  15655. }
  15656. const { tag } = node;
  15657. const isCustomElement = context.isCustomElement(tag);
  15658. if (tag === 'input' ||
  15659. tag === 'textarea' ||
  15660. tag === 'select' ||
  15661. isCustomElement) {
  15662. let directiveToUse = V_MODEL_TEXT;
  15663. let isInvalidType = false;
  15664. if (tag === 'input' || isCustomElement) {
  15665. const type = findProp(node, `type`);
  15666. if (type) {
  15667. if (type.type === 7 /* NodeTypes.DIRECTIVE */) {
  15668. // :type="foo"
  15669. directiveToUse = V_MODEL_DYNAMIC;
  15670. }
  15671. else if (type.value) {
  15672. switch (type.value.content) {
  15673. case 'radio':
  15674. directiveToUse = V_MODEL_RADIO;
  15675. break;
  15676. case 'checkbox':
  15677. directiveToUse = V_MODEL_CHECKBOX;
  15678. break;
  15679. case 'file':
  15680. isInvalidType = true;
  15681. context.onError(createDOMCompilerError(57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  15682. break;
  15683. default:
  15684. // text type
  15685. checkDuplicatedValue();
  15686. break;
  15687. }
  15688. }
  15689. }
  15690. else if (hasDynamicKeyVBind(node)) {
  15691. // element has bindings with dynamic keys, which can possibly contain
  15692. // "type".
  15693. directiveToUse = V_MODEL_DYNAMIC;
  15694. }
  15695. else {
  15696. // text type
  15697. checkDuplicatedValue();
  15698. }
  15699. }
  15700. else if (tag === 'select') {
  15701. directiveToUse = V_MODEL_SELECT;
  15702. }
  15703. else {
  15704. // textarea
  15705. checkDuplicatedValue();
  15706. }
  15707. // inject runtime directive
  15708. // by returning the helper symbol via needRuntime
  15709. // the import will replaced a resolveDirective call.
  15710. if (!isInvalidType) {
  15711. baseResult.needRuntime = context.helper(directiveToUse);
  15712. }
  15713. }
  15714. else {
  15715. context.onError(createDOMCompilerError(55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  15716. }
  15717. // native vmodel doesn't need the `modelValue` props since they are also
  15718. // passed to the runtime as `binding.value`. removing it reduces code size.
  15719. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  15720. p.key.content === 'modelValue'));
  15721. return baseResult;
  15722. };
  15723. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  15724. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  15725. // event propagation management
  15726. `stop,prevent,self,` +
  15727. // system modifiers + exact
  15728. `ctrl,shift,alt,meta,exact,` +
  15729. // mouse
  15730. `middle`);
  15731. // left & right could be mouse or key modifiers based on event type
  15732. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  15733. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  15734. const resolveModifiers = (key, modifiers, context, loc) => {
  15735. const keyModifiers = [];
  15736. const nonKeyModifiers = [];
  15737. const eventOptionModifiers = [];
  15738. for (let i = 0; i < modifiers.length; i++) {
  15739. const modifier = modifiers[i];
  15740. if (isEventOptionModifier(modifier)) {
  15741. // eventOptionModifiers: modifiers for addEventListener() options,
  15742. // e.g. .passive & .capture
  15743. eventOptionModifiers.push(modifier);
  15744. }
  15745. else {
  15746. // runtimeModifiers: modifiers that needs runtime guards
  15747. if (maybeKeyModifier(modifier)) {
  15748. if (isStaticExp(key)) {
  15749. if (isKeyboardEvent(key.content)) {
  15750. keyModifiers.push(modifier);
  15751. }
  15752. else {
  15753. nonKeyModifiers.push(modifier);
  15754. }
  15755. }
  15756. else {
  15757. keyModifiers.push(modifier);
  15758. nonKeyModifiers.push(modifier);
  15759. }
  15760. }
  15761. else {
  15762. if (isNonKeyModifier(modifier)) {
  15763. nonKeyModifiers.push(modifier);
  15764. }
  15765. else {
  15766. keyModifiers.push(modifier);
  15767. }
  15768. }
  15769. }
  15770. }
  15771. return {
  15772. keyModifiers,
  15773. nonKeyModifiers,
  15774. eventOptionModifiers
  15775. };
  15776. };
  15777. const transformClick = (key, event) => {
  15778. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  15779. return isStaticClick
  15780. ? createSimpleExpression(event, true)
  15781. : key.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */
  15782. ? createCompoundExpression([
  15783. `(`,
  15784. key,
  15785. `) === "onClick" ? "${event}" : (`,
  15786. key,
  15787. `)`
  15788. ])
  15789. : key;
  15790. };
  15791. const transformOn$1 = (dir, node, context) => {
  15792. return transformOn(dir, node, context, baseResult => {
  15793. const { modifiers } = dir;
  15794. if (!modifiers.length)
  15795. return baseResult;
  15796. let { key, value: handlerExp } = baseResult.props[0];
  15797. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
  15798. // normalize click.right and click.middle since they don't actually fire
  15799. if (nonKeyModifiers.includes('right')) {
  15800. key = transformClick(key, `onContextmenu`);
  15801. }
  15802. if (nonKeyModifiers.includes('middle')) {
  15803. key = transformClick(key, `onMouseup`);
  15804. }
  15805. if (nonKeyModifiers.length) {
  15806. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  15807. handlerExp,
  15808. JSON.stringify(nonKeyModifiers)
  15809. ]);
  15810. }
  15811. if (keyModifiers.length &&
  15812. // if event name is dynamic, always wrap with keys guard
  15813. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  15814. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  15815. handlerExp,
  15816. JSON.stringify(keyModifiers)
  15817. ]);
  15818. }
  15819. if (eventOptionModifiers.length) {
  15820. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  15821. key = isStaticExp(key)
  15822. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  15823. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  15824. }
  15825. return {
  15826. props: [createObjectProperty(key, handlerExp)]
  15827. };
  15828. });
  15829. };
  15830. const transformShow = (dir, node, context) => {
  15831. const { exp, loc } = dir;
  15832. if (!exp) {
  15833. context.onError(createDOMCompilerError(59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */, loc));
  15834. }
  15835. return {
  15836. props: [],
  15837. needRuntime: context.helper(V_SHOW)
  15838. };
  15839. };
  15840. const transformTransition = (node, context) => {
  15841. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  15842. node.tagType === 1 /* ElementTypes.COMPONENT */) {
  15843. const component = context.isBuiltInComponent(node.tag);
  15844. if (component === TRANSITION$1) {
  15845. return () => {
  15846. if (!node.children.length) {
  15847. return;
  15848. }
  15849. // warn multiple transition children
  15850. if (hasMultipleChildren(node)) {
  15851. context.onError(createDOMCompilerError(60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */, {
  15852. start: node.children[0].loc.start,
  15853. end: node.children[node.children.length - 1].loc.end,
  15854. source: ''
  15855. }));
  15856. }
  15857. // check if it's s single child w/ v-show
  15858. // if yes, inject "persisted: true" to the transition props
  15859. const child = node.children[0];
  15860. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  15861. for (const p of child.props) {
  15862. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'show') {
  15863. node.props.push({
  15864. type: 6 /* NodeTypes.ATTRIBUTE */,
  15865. name: 'persisted',
  15866. value: undefined,
  15867. loc: node.loc
  15868. });
  15869. }
  15870. }
  15871. }
  15872. };
  15873. }
  15874. }
  15875. };
  15876. function hasMultipleChildren(node) {
  15877. // #1352 filter out potential comment nodes.
  15878. const children = (node.children = node.children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */ &&
  15879. !(c.type === 2 /* NodeTypes.TEXT */ && !c.content.trim())));
  15880. const child = children[0];
  15881. return (children.length !== 1 ||
  15882. child.type === 11 /* NodeTypes.FOR */ ||
  15883. (child.type === 9 /* NodeTypes.IF */ && child.branches.some(hasMultipleChildren)));
  15884. }
  15885. const ignoreSideEffectTags = (node, context) => {
  15886. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  15887. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  15888. (node.tag === 'script' || node.tag === 'style')) {
  15889. context.onError(createDOMCompilerError(61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  15890. context.removeNode();
  15891. }
  15892. };
  15893. const DOMNodeTransforms = [
  15894. transformStyle,
  15895. ...([transformTransition] )
  15896. ];
  15897. const DOMDirectiveTransforms = {
  15898. cloak: noopDirectiveTransform,
  15899. html: transformVHtml,
  15900. text: transformVText,
  15901. model: transformModel$1,
  15902. on: transformOn$1,
  15903. show: transformShow
  15904. };
  15905. function compile$1(template, options = {}) {
  15906. return baseCompile(template, extend({}, parserOptions, options, {
  15907. nodeTransforms: [
  15908. // ignore <script> and <tag>
  15909. // this is not put inside DOMNodeTransforms because that list is used
  15910. // by compiler-ssr to generate vnode fallback branches
  15911. ignoreSideEffectTags,
  15912. ...DOMNodeTransforms,
  15913. ...(options.nodeTransforms || [])
  15914. ],
  15915. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  15916. transformHoist: null
  15917. }));
  15918. }
  15919. // This entry is the "full-build" that includes both the runtime
  15920. {
  15921. initDev();
  15922. }
  15923. const compileCache = Object.create(null);
  15924. function compileToFunction(template, options) {
  15925. if (!isString(template)) {
  15926. if (template.nodeType) {
  15927. template = template.innerHTML;
  15928. }
  15929. else {
  15930. warn$1(`invalid template option: `, template);
  15931. return NOOP;
  15932. }
  15933. }
  15934. const key = template;
  15935. const cached = compileCache[key];
  15936. if (cached) {
  15937. return cached;
  15938. }
  15939. if (template[0] === '#') {
  15940. const el = document.querySelector(template);
  15941. if (!el) {
  15942. warn$1(`Template element not found or is empty: ${template}`);
  15943. }
  15944. // __UNSAFE__
  15945. // Reason: potential execution of JS expressions in in-DOM template.
  15946. // The user must make sure the in-DOM template is trusted. If it's rendered
  15947. // by the server, the template should not contain any user data.
  15948. template = el ? el.innerHTML : ``;
  15949. }
  15950. const opts = extend({
  15951. hoistStatic: true,
  15952. onError: onError ,
  15953. onWarn: e => onError(e, true)
  15954. }, options);
  15955. if (!opts.isCustomElement && typeof customElements !== 'undefined') {
  15956. opts.isCustomElement = tag => !!customElements.get(tag);
  15957. }
  15958. const { code } = compile$1(template, opts);
  15959. function onError(err, asWarning = false) {
  15960. const message = asWarning
  15961. ? err.message
  15962. : `Template compilation error: ${err.message}`;
  15963. const codeFrame = err.loc &&
  15964. generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
  15965. warn$1(codeFrame ? `${message}\n${codeFrame}` : message);
  15966. }
  15967. // The wildcard import results in a huge object with every export
  15968. // with keys that cannot be mangled, and can be quite heavy size-wise.
  15969. // In the global build we know `Vue` is available globally so we can avoid
  15970. // the wildcard object.
  15971. const render = (new Function('Vue', code)(runtimeDom));
  15972. render._rc = true;
  15973. return (compileCache[key] = render);
  15974. }
  15975. registerRuntimeCompiler(compileToFunction);
  15976. export { BaseTransition, Comment, EffectScope, Fragment, KeepAlive, ReactiveEffect, Static, Suspense, Teleport, Text, Transition, TransitionGroup, VueElement, callWithAsyncErrorHandling, callWithErrorHandling, camelize, capitalize, cloneVNode, compatUtils, compileToFunction as compile, computed$1 as computed, createApp, createBlock, createCommentVNode, createElementBlock, createBaseVNode as createElementVNode, createHydrationRenderer, createPropsRestProxy, createRenderer, createSSRApp, createSlots, createStaticVNode, createTextVNode, createVNode, customRef, defineAsyncComponent, defineComponent, defineCustomElement, defineEmits, defineExpose, defineProps, defineSSRCustomElement, devtools, effect, effectScope, getCurrentInstance, getCurrentScope, getTransitionRawChildren, guardReactiveProps, h, handleError, hydrate, initCustomFormatter, initDirectivesForSSR, inject, isMemoSame, isProxy, isReactive, isReadonly, isRef, isRuntimeOnly, isShallow, isVNode, markRaw, mergeDefaults, mergeProps, nextTick, normalizeClass, normalizeProps, normalizeStyle, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onScopeDispose, onServerPrefetch, onUnmounted, onUpdated, openBlock, popScopeId, provide, proxyRefs, pushScopeId, queuePostFlushCb, reactive, readonly, ref, registerRuntimeCompiler, render, renderList, renderSlot, resolveComponent, resolveDirective, resolveDynamicComponent, resolveFilter, resolveTransitionHooks, setBlockTracking, setDevtoolsHook, setTransitionHooks, shallowReactive, shallowReadonly, shallowRef, ssrContextKey, ssrUtils, stop, toDisplayString, toHandlerKey, toHandlers, toRaw, toRef, toRefs, transformVNodeArgs, triggerRef, unref, useAttrs, useCssModule, useCssVars, useSSRContext, useSlots, useTransitionState, vModelCheckbox, vModelDynamic, vModelRadio, vModelSelect, vModelText, vShow, version, warn$1 as warn, watch, watchEffect, watchPostEffect, watchSyncEffect, withAsyncContext, withCtx, withDefaults, withDirectives, withKeys, withMemo, withModifiers, withScopeId };