compiler-sfc.esm-browser.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827
  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$3(value)) {
  92. const res = {};
  93. for (let i = 0; i < value.length; i++) {
  94. const item = value[i];
  95. const normalized = isString$2(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$2(value)) {
  107. return value;
  108. }
  109. else if (isObject$2(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 stringifyStyle(styles) {
  130. let ret = '';
  131. if (!styles || isString$2(styles)) {
  132. return ret;
  133. }
  134. for (const key in styles) {
  135. const value = styles[key];
  136. const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key);
  137. if (isString$2(value) || typeof value === 'number') {
  138. // only render valid values
  139. ret += `${normalizedKey}:${value};`;
  140. }
  141. }
  142. return ret;
  143. }
  144. function normalizeClass(value) {
  145. let res = '';
  146. if (isString$2(value)) {
  147. res = value;
  148. }
  149. else if (isArray$3(value)) {
  150. for (let i = 0; i < value.length; i++) {
  151. const normalized = normalizeClass(value[i]);
  152. if (normalized) {
  153. res += normalized + ' ';
  154. }
  155. }
  156. }
  157. else if (isObject$2(value)) {
  158. for (const name in value) {
  159. if (value[name]) {
  160. res += name + ' ';
  161. }
  162. }
  163. }
  164. return res.trim();
  165. }
  166. // These tag configs are shared between compiler-dom and runtime-dom, so they
  167. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  168. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  169. 'header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,' +
  170. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  171. 'data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,' +
  172. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  173. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  174. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  175. 'option,output,progress,select,textarea,details,dialog,menu,' +
  176. 'summary,template,blockquote,iframe,tfoot';
  177. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  178. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  179. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  180. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  181. 'feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  182. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  183. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  184. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  185. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  186. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  187. 'text,textPath,title,tspan,unknown,use,view';
  188. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  189. /**
  190. * Compiler only.
  191. * Do NOT use in runtime code paths unless behind `true` flag.
  192. */
  193. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  194. /**
  195. * Compiler only.
  196. * Do NOT use in runtime code paths unless behind `true` flag.
  197. */
  198. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  199. /**
  200. * Compiler only.
  201. * Do NOT use in runtime code paths unless behind `true` flag.
  202. */
  203. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  204. /**
  205. * On the client we only need to offer special cases for boolean attributes that
  206. * have different names from their corresponding dom properties:
  207. * - itemscope -> N/A
  208. * - allowfullscreen -> allowFullscreen
  209. * - formnovalidate -> formNoValidate
  210. * - ismap -> isMap
  211. * - nomodule -> noModule
  212. * - novalidate -> noValidate
  213. * - readonly -> readOnly
  214. */
  215. const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
  216. /**
  217. * The full list is needed during SSR to produce the correct initial markup.
  218. */
  219. const isBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs +
  220. `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,` +
  221. `loop,open,required,reversed,scoped,seamless,` +
  222. `checked,muted,multiple,selected`);
  223. const unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/;
  224. const attrValidationCache = {};
  225. function isSSRSafeAttrName(name) {
  226. if (attrValidationCache.hasOwnProperty(name)) {
  227. return attrValidationCache[name];
  228. }
  229. const isUnsafe = unsafeAttrCharRE.test(name);
  230. if (isUnsafe) {
  231. console.error(`unsafe attribute name: ${name}`);
  232. }
  233. return (attrValidationCache[name] = !isUnsafe);
  234. }
  235. const propsToAttrMap = {
  236. acceptCharset: 'accept-charset',
  237. className: 'class',
  238. htmlFor: 'for',
  239. httpEquiv: 'http-equiv'
  240. };
  241. /**
  242. * Known attributes, this is used for stringification of runtime static nodes
  243. * so that we don't stringify bindings that cannot be set from HTML.
  244. * Don't also forget to allow `data-*` and `aria-*`!
  245. * Generated from https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
  246. */
  247. const isKnownHtmlAttr = /*#__PURE__*/ makeMap(`accept,accept-charset,accesskey,action,align,allow,alt,async,` +
  248. `autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,` +
  249. `border,buffered,capture,challenge,charset,checked,cite,class,code,` +
  250. `codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,` +
  251. `coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,` +
  252. `disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,` +
  253. `formaction,formenctype,formmethod,formnovalidate,formtarget,headers,` +
  254. `height,hidden,high,href,hreflang,http-equiv,icon,id,importance,integrity,` +
  255. `ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,` +
  256. `manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,` +
  257. `open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,` +
  258. `referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,` +
  259. `selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,` +
  260. `start,step,style,summary,tabindex,target,title,translate,type,usemap,` +
  261. `value,width,wrap`);
  262. /**
  263. * Generated from https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute
  264. */
  265. const isKnownSvgAttr = /*#__PURE__*/ makeMap(`xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,` +
  266. `arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,` +
  267. `baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,` +
  268. `clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,` +
  269. `color-interpolation-filters,color-profile,color-rendering,` +
  270. `contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,` +
  271. `descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,` +
  272. `dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,` +
  273. `fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,` +
  274. `font-family,font-size,font-size-adjust,font-stretch,font-style,` +
  275. `font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,` +
  276. `glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,` +
  277. `gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,` +
  278. `horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,` +
  279. `k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,` +
  280. `lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,` +
  281. `marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,` +
  282. `mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,` +
  283. `name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,` +
  284. `overflow,overline-position,overline-thickness,panose-1,paint-order,path,` +
  285. `pathLength,patternContentUnits,patternTransform,patternUnits,ping,` +
  286. `pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,` +
  287. `preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,` +
  288. `rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,` +
  289. `restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,` +
  290. `specularConstant,specularExponent,speed,spreadMethod,startOffset,` +
  291. `stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,` +
  292. `strikethrough-position,strikethrough-thickness,string,stroke,` +
  293. `stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,` +
  294. `stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,` +
  295. `systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,` +
  296. `text-decoration,text-rendering,textLength,to,transform,transform-origin,` +
  297. `type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,` +
  298. `unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,` +
  299. `v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,` +
  300. `vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,` +
  301. `writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,` +
  302. `xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xml:base,xml:lang,` +
  303. `xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan`);
  304. const escapeRE = /["'&<>]/;
  305. function escapeHtml(string) {
  306. const str = '' + string;
  307. const match = escapeRE.exec(str);
  308. if (!match) {
  309. return str;
  310. }
  311. let html = '';
  312. let escaped;
  313. let index;
  314. let lastIndex = 0;
  315. for (index = match.index; index < str.length; index++) {
  316. switch (str.charCodeAt(index)) {
  317. case 34: // "
  318. escaped = '&quot;';
  319. break;
  320. case 38: // &
  321. escaped = '&amp;';
  322. break;
  323. case 39: // '
  324. escaped = '&#39;';
  325. break;
  326. case 60: // <
  327. escaped = '&lt;';
  328. break;
  329. case 62: // >
  330. escaped = '&gt;';
  331. break;
  332. default:
  333. continue;
  334. }
  335. if (lastIndex !== index) {
  336. html += str.slice(lastIndex, index);
  337. }
  338. lastIndex = index + 1;
  339. html += escaped;
  340. }
  341. return lastIndex !== index ? html + str.slice(lastIndex, index) : html;
  342. }
  343. /**
  344. * For converting {{ interpolation }} values to displayed strings.
  345. * @private
  346. */
  347. const toDisplayString = (val) => {
  348. return isString$2(val)
  349. ? val
  350. : val == null
  351. ? ''
  352. : isArray$3(val) ||
  353. (isObject$2(val) &&
  354. (val.toString === objectToString$1 || !isFunction$1(val.toString)))
  355. ? JSON.stringify(val, replacer, 2)
  356. : String(val);
  357. };
  358. const replacer = (_key, val) => {
  359. // can't use isRef here since @vue/shared has no deps
  360. if (val && val.__v_isRef) {
  361. return replacer(_key, val.value);
  362. }
  363. else if (isMap(val)) {
  364. return {
  365. [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
  366. entries[`${key} =>`] = val;
  367. return entries;
  368. }, {})
  369. };
  370. }
  371. else if (isSet(val)) {
  372. return {
  373. [`Set(${val.size})`]: [...val.values()]
  374. };
  375. }
  376. else if (isObject$2(val) && !isArray$3(val) && !isPlainObject(val)) {
  377. return String(val);
  378. }
  379. return val;
  380. };
  381. const EMPTY_OBJ = Object.freeze({})
  382. ;
  383. const NOOP = () => { };
  384. /**
  385. * Always return false.
  386. */
  387. const NO = () => false;
  388. const onRE = /^on[^a-z]/;
  389. const isOn = (key) => onRE.test(key);
  390. const extend = Object.assign;
  391. const hasOwnProperty$3 = Object.prototype.hasOwnProperty;
  392. const hasOwn = (val, key) => hasOwnProperty$3.call(val, key);
  393. const isArray$3 = Array.isArray;
  394. const isMap = (val) => toTypeString(val) === '[object Map]';
  395. const isSet = (val) => toTypeString(val) === '[object Set]';
  396. const isFunction$1 = (val) => typeof val === 'function';
  397. const isString$2 = (val) => typeof val === 'string';
  398. const isSymbol$1 = (val) => typeof val === 'symbol';
  399. const isObject$2 = (val) => val !== null && typeof val === 'object';
  400. const objectToString$1 = Object.prototype.toString;
  401. const toTypeString = (value) => objectToString$1.call(value);
  402. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  403. const isReservedProp = /*#__PURE__*/ makeMap(
  404. // the leading comma is intentional so empty string "" is also included
  405. ',key,ref,ref_for,ref_key,' +
  406. 'onVnodeBeforeMount,onVnodeMounted,' +
  407. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  408. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  409. const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo');
  410. const cacheStringFunction = (fn) => {
  411. const cache = Object.create(null);
  412. return ((str) => {
  413. const hit = cache[str];
  414. return hit || (cache[str] = fn(str));
  415. });
  416. };
  417. const camelizeRE = /-(\w)/g;
  418. /**
  419. * @private
  420. */
  421. const camelize = cacheStringFunction((str) => {
  422. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  423. });
  424. const hyphenateRE = /\B([A-Z])/g;
  425. /**
  426. * @private
  427. */
  428. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  429. /**
  430. * @private
  431. */
  432. const capitalize$1 = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  433. /**
  434. * @private
  435. */
  436. const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize$1(str)}` : ``);
  437. const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/;
  438. function genPropsAccessExp(name) {
  439. return identRE.test(name)
  440. ? `__props.${name}`
  441. : `__props[${JSON.stringify(name)}]`;
  442. }
  443. function defaultOnError(error) {
  444. throw error;
  445. }
  446. function defaultOnWarn(msg) {
  447. console.warn(`[Vue warn] ${msg.message}`);
  448. }
  449. function createCompilerError(code, loc, messages, additionalMessage) {
  450. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  451. ;
  452. const error = new SyntaxError(String(msg));
  453. error.code = code;
  454. error.loc = loc;
  455. return error;
  456. }
  457. const errorMessages = {
  458. // parse errors
  459. [0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  460. [1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  461. [2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  462. [3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  463. [4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  464. [5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  465. [6 /* ErrorCodes.EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  466. [7 /* ErrorCodes.EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  467. [8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  468. [9 /* ErrorCodes.EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  469. [10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  470. [11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  471. [12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  472. [13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  473. [14 /* ErrorCodes.MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  474. [15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  475. [16 /* ErrorCodes.NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  476. [17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  477. [18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  478. [19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  479. [21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  480. [20 /* ErrorCodes.UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
  481. [22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  482. // Vue-specific parse errors
  483. [23 /* ErrorCodes.X_INVALID_END_TAG */]: 'Invalid end tag.',
  484. [24 /* ErrorCodes.X_MISSING_END_TAG */]: 'Element is missing end tag.',
  485. [25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  486. [27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  487. 'Note that dynamic directive argument cannot contain spaces.',
  488. [26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
  489. // transform errors
  490. [28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  491. [29 /* ErrorCodes.X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  492. [30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
  493. [31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  494. [32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  495. [33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  496. [34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  497. [35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  498. [36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  499. [37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>. ` +
  500. `When there are multiple named slots, all slots should use <template> ` +
  501. `syntax to avoid scope ambiguity.`,
  502. [38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  503. [39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  504. `default slot. These children will be ignored.`,
  505. [40 /* ErrorCodes.X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  506. [41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  507. [42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  508. [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.`,
  509. [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.`,
  510. [45 /* ErrorCodes.X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  511. [46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  512. // generic errors
  513. [47 /* ErrorCodes.X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  514. [48 /* ErrorCodes.X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  515. [49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  516. [50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
  517. // just to fulfill types
  518. [51 /* ErrorCodes.__EXTEND_POINT__ */]: ``
  519. };
  520. const FRAGMENT = Symbol(`Fragment` );
  521. const TELEPORT = Symbol(`Teleport` );
  522. const SUSPENSE = Symbol(`Suspense` );
  523. const KEEP_ALIVE = Symbol(`KeepAlive` );
  524. const BASE_TRANSITION = Symbol(`BaseTransition` );
  525. const OPEN_BLOCK = Symbol(`openBlock` );
  526. const CREATE_BLOCK = Symbol(`createBlock` );
  527. const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
  528. const CREATE_VNODE = Symbol(`createVNode` );
  529. const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
  530. const CREATE_COMMENT = Symbol(`createCommentVNode` );
  531. const CREATE_TEXT = Symbol(`createTextVNode` );
  532. const CREATE_STATIC = Symbol(`createStaticVNode` );
  533. const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
  534. const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
  535. const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
  536. const RESOLVE_FILTER = Symbol(`resolveFilter` );
  537. const WITH_DIRECTIVES = Symbol(`withDirectives` );
  538. const RENDER_LIST = Symbol(`renderList` );
  539. const RENDER_SLOT = Symbol(`renderSlot` );
  540. const CREATE_SLOTS = Symbol(`createSlots` );
  541. const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
  542. const MERGE_PROPS = Symbol(`mergeProps` );
  543. const NORMALIZE_CLASS = Symbol(`normalizeClass` );
  544. const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
  545. const NORMALIZE_PROPS = Symbol(`normalizeProps` );
  546. const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
  547. const TO_HANDLERS = Symbol(`toHandlers` );
  548. const CAMELIZE = Symbol(`camelize` );
  549. const CAPITALIZE = Symbol(`capitalize` );
  550. const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
  551. const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
  552. const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
  553. const POP_SCOPE_ID = Symbol(`popScopeId` );
  554. const WITH_CTX = Symbol(`withCtx` );
  555. const UNREF = Symbol(`unref` );
  556. const IS_REF = Symbol(`isRef` );
  557. const WITH_MEMO = Symbol(`withMemo` );
  558. const IS_MEMO_SAME = Symbol(`isMemoSame` );
  559. // Name mapping for runtime helpers that need to be imported from 'vue' in
  560. // generated code. Make sure these are correctly exported in the runtime!
  561. const helperNameMap = {
  562. [FRAGMENT]: `Fragment`,
  563. [TELEPORT]: `Teleport`,
  564. [SUSPENSE]: `Suspense`,
  565. [KEEP_ALIVE]: `KeepAlive`,
  566. [BASE_TRANSITION]: `BaseTransition`,
  567. [OPEN_BLOCK]: `openBlock`,
  568. [CREATE_BLOCK]: `createBlock`,
  569. [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
  570. [CREATE_VNODE]: `createVNode`,
  571. [CREATE_ELEMENT_VNODE]: `createElementVNode`,
  572. [CREATE_COMMENT]: `createCommentVNode`,
  573. [CREATE_TEXT]: `createTextVNode`,
  574. [CREATE_STATIC]: `createStaticVNode`,
  575. [RESOLVE_COMPONENT]: `resolveComponent`,
  576. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  577. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  578. [RESOLVE_FILTER]: `resolveFilter`,
  579. [WITH_DIRECTIVES]: `withDirectives`,
  580. [RENDER_LIST]: `renderList`,
  581. [RENDER_SLOT]: `renderSlot`,
  582. [CREATE_SLOTS]: `createSlots`,
  583. [TO_DISPLAY_STRING]: `toDisplayString`,
  584. [MERGE_PROPS]: `mergeProps`,
  585. [NORMALIZE_CLASS]: `normalizeClass`,
  586. [NORMALIZE_STYLE]: `normalizeStyle`,
  587. [NORMALIZE_PROPS]: `normalizeProps`,
  588. [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
  589. [TO_HANDLERS]: `toHandlers`,
  590. [CAMELIZE]: `camelize`,
  591. [CAPITALIZE]: `capitalize`,
  592. [TO_HANDLER_KEY]: `toHandlerKey`,
  593. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  594. [PUSH_SCOPE_ID]: `pushScopeId`,
  595. [POP_SCOPE_ID]: `popScopeId`,
  596. [WITH_CTX]: `withCtx`,
  597. [UNREF]: `unref`,
  598. [IS_REF]: `isRef`,
  599. [WITH_MEMO]: `withMemo`,
  600. [IS_MEMO_SAME]: `isMemoSame`
  601. };
  602. function registerRuntimeHelpers(helpers) {
  603. Object.getOwnPropertySymbols(helpers).forEach(s => {
  604. helperNameMap[s] = helpers[s];
  605. });
  606. }
  607. // AST Utilities ---------------------------------------------------------------
  608. // Some expressions, e.g. sequence and conditional expressions, are never
  609. // associated with template nodes, so their source locations are just a stub.
  610. // Container types like CompoundExpression also don't need a real location.
  611. const locStub = {
  612. source: '',
  613. start: { line: 1, column: 1, offset: 0 },
  614. end: { line: 1, column: 1, offset: 0 }
  615. };
  616. function createRoot(children, loc = locStub) {
  617. return {
  618. type: 0 /* NodeTypes.ROOT */,
  619. children,
  620. helpers: new Set(),
  621. components: [],
  622. directives: [],
  623. hoists: [],
  624. imports: [],
  625. cached: 0,
  626. temps: 0,
  627. codegenNode: undefined,
  628. loc
  629. };
  630. }
  631. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
  632. if (context) {
  633. if (isBlock) {
  634. context.helper(OPEN_BLOCK);
  635. context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
  636. }
  637. else {
  638. context.helper(getVNodeHelper(context.inSSR, isComponent));
  639. }
  640. if (directives) {
  641. context.helper(WITH_DIRECTIVES);
  642. }
  643. }
  644. return {
  645. type: 13 /* NodeTypes.VNODE_CALL */,
  646. tag,
  647. props,
  648. children,
  649. patchFlag,
  650. dynamicProps,
  651. directives,
  652. isBlock,
  653. disableTracking,
  654. isComponent,
  655. loc
  656. };
  657. }
  658. function createArrayExpression(elements, loc = locStub) {
  659. return {
  660. type: 17 /* NodeTypes.JS_ARRAY_EXPRESSION */,
  661. loc,
  662. elements
  663. };
  664. }
  665. function createObjectExpression(properties, loc = locStub) {
  666. return {
  667. type: 15 /* NodeTypes.JS_OBJECT_EXPRESSION */,
  668. loc,
  669. properties
  670. };
  671. }
  672. function createObjectProperty(key, value) {
  673. return {
  674. type: 16 /* NodeTypes.JS_PROPERTY */,
  675. loc: locStub,
  676. key: isString$2(key) ? createSimpleExpression(key, true) : key,
  677. value
  678. };
  679. }
  680. function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* ConstantTypes.NOT_CONSTANT */) {
  681. return {
  682. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  683. loc,
  684. content,
  685. isStatic,
  686. constType: isStatic ? 3 /* ConstantTypes.CAN_STRINGIFY */ : constType
  687. };
  688. }
  689. function createInterpolation(content, loc) {
  690. return {
  691. type: 5 /* NodeTypes.INTERPOLATION */,
  692. loc,
  693. content: isString$2(content)
  694. ? createSimpleExpression(content, false, loc)
  695. : content
  696. };
  697. }
  698. function createCompoundExpression(children, loc = locStub) {
  699. return {
  700. type: 8 /* NodeTypes.COMPOUND_EXPRESSION */,
  701. loc,
  702. children
  703. };
  704. }
  705. function createCallExpression(callee, args = [], loc = locStub) {
  706. return {
  707. type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
  708. loc,
  709. callee,
  710. arguments: args
  711. };
  712. }
  713. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  714. return {
  715. type: 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */,
  716. params,
  717. returns,
  718. newline,
  719. isSlot,
  720. loc
  721. };
  722. }
  723. function createConditionalExpression(test, consequent, alternate, newline = true) {
  724. return {
  725. type: 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */,
  726. test,
  727. consequent,
  728. alternate,
  729. newline,
  730. loc: locStub
  731. };
  732. }
  733. function createCacheExpression(index, value, isVNode = false) {
  734. return {
  735. type: 20 /* NodeTypes.JS_CACHE_EXPRESSION */,
  736. index,
  737. value,
  738. isVNode,
  739. loc: locStub
  740. };
  741. }
  742. function createBlockStatement(body) {
  743. return {
  744. type: 21 /* NodeTypes.JS_BLOCK_STATEMENT */,
  745. body,
  746. loc: locStub
  747. };
  748. }
  749. function createTemplateLiteral(elements) {
  750. return {
  751. type: 22 /* NodeTypes.JS_TEMPLATE_LITERAL */,
  752. elements,
  753. loc: locStub
  754. };
  755. }
  756. function createIfStatement(test, consequent, alternate) {
  757. return {
  758. type: 23 /* NodeTypes.JS_IF_STATEMENT */,
  759. test,
  760. consequent,
  761. alternate,
  762. loc: locStub
  763. };
  764. }
  765. function createAssignmentExpression(left, right) {
  766. return {
  767. type: 24 /* NodeTypes.JS_ASSIGNMENT_EXPRESSION */,
  768. left,
  769. right,
  770. loc: locStub
  771. };
  772. }
  773. function createSequenceExpression(expressions) {
  774. return {
  775. type: 25 /* NodeTypes.JS_SEQUENCE_EXPRESSION */,
  776. expressions,
  777. loc: locStub
  778. };
  779. }
  780. function createReturnStatement(returns) {
  781. return {
  782. type: 26 /* NodeTypes.JS_RETURN_STATEMENT */,
  783. returns,
  784. loc: locStub
  785. };
  786. }
  787. function getDefaultExportFromCjs (x) {
  788. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  789. }
  790. function getAugmentedNamespace(n) {
  791. var f = n.default;
  792. if (typeof f == "function") {
  793. var a = function () {
  794. return f.apply(this, arguments);
  795. };
  796. a.prototype = f.prototype;
  797. } else a = {};
  798. Object.defineProperty(a, '__esModule', {value: true});
  799. Object.keys(n).forEach(function (k) {
  800. var d = Object.getOwnPropertyDescriptor(n, k);
  801. Object.defineProperty(a, k, d.get ? d : {
  802. enumerable: true,
  803. get: function () {
  804. return n[k];
  805. }
  806. });
  807. });
  808. return a;
  809. }
  810. var lib = {};
  811. Object.defineProperty(lib, '__esModule', { value: true });
  812. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  813. const lineBreakG = new RegExp(lineBreak.source, "g");
  814. function isNewLine(code) {
  815. switch (code) {
  816. case 10:
  817. case 13:
  818. case 8232:
  819. case 8233:
  820. return true;
  821. default:
  822. return false;
  823. }
  824. }
  825. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  826. const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/y;
  827. const skipWhiteSpaceToLineBreak = new RegExp("(?=(" + skipWhiteSpaceInLine.source + "))\\1" + /(?=[\n\r\u2028\u2029]|\/\*(?!.*?\*\/)|$)/.source, "y");
  828. function isWhitespace(code) {
  829. switch (code) {
  830. case 0x0009:
  831. case 0x000b:
  832. case 0x000c:
  833. case 32:
  834. case 160:
  835. case 5760:
  836. case 0x2000:
  837. case 0x2001:
  838. case 0x2002:
  839. case 0x2003:
  840. case 0x2004:
  841. case 0x2005:
  842. case 0x2006:
  843. case 0x2007:
  844. case 0x2008:
  845. case 0x2009:
  846. case 0x200a:
  847. case 0x202f:
  848. case 0x205f:
  849. case 0x3000:
  850. case 0xfeff:
  851. return true;
  852. default:
  853. return false;
  854. }
  855. }
  856. class Position {
  857. constructor(line, col) {
  858. this.line = void 0;
  859. this.column = void 0;
  860. this.line = line;
  861. this.column = col;
  862. }
  863. }
  864. class SourceLocation {
  865. constructor(start, end) {
  866. this.start = void 0;
  867. this.end = void 0;
  868. this.filename = void 0;
  869. this.identifierName = void 0;
  870. this.start = start;
  871. this.end = end;
  872. }
  873. }
  874. function getLineInfo(input, offset) {
  875. let line = 1;
  876. let lineStart = 0;
  877. let match;
  878. lineBreakG.lastIndex = 0;
  879. while ((match = lineBreakG.exec(input)) && match.index < offset) {
  880. line++;
  881. lineStart = lineBreakG.lastIndex;
  882. }
  883. return new Position(line, offset - lineStart);
  884. }
  885. class BaseParser {
  886. constructor() {
  887. this.sawUnambiguousESM = false;
  888. this.ambiguousScriptDifferentAst = false;
  889. }
  890. hasPlugin(name) {
  891. return this.plugins.has(name);
  892. }
  893. getPluginOption(plugin, name) {
  894. if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
  895. }
  896. }
  897. function setTrailingComments(node, comments) {
  898. if (node.trailingComments === undefined) {
  899. node.trailingComments = comments;
  900. } else {
  901. node.trailingComments.unshift(...comments);
  902. }
  903. }
  904. function setLeadingComments(node, comments) {
  905. if (node.leadingComments === undefined) {
  906. node.leadingComments = comments;
  907. } else {
  908. node.leadingComments.unshift(...comments);
  909. }
  910. }
  911. function setInnerComments(node, comments) {
  912. if (node.innerComments === undefined) {
  913. node.innerComments = comments;
  914. } else {
  915. node.innerComments.unshift(...comments);
  916. }
  917. }
  918. function adjustInnerComments(node, elements, commentWS) {
  919. let lastElement = null;
  920. let i = elements.length;
  921. while (lastElement === null && i > 0) {
  922. lastElement = elements[--i];
  923. }
  924. if (lastElement === null || lastElement.start > commentWS.start) {
  925. setInnerComments(node, commentWS.comments);
  926. } else {
  927. setTrailingComments(lastElement, commentWS.comments);
  928. }
  929. }
  930. class CommentsParser extends BaseParser {
  931. addComment(comment) {
  932. if (this.filename) comment.loc.filename = this.filename;
  933. this.state.comments.push(comment);
  934. }
  935. processComment(node) {
  936. const {
  937. commentStack
  938. } = this.state;
  939. const commentStackLength = commentStack.length;
  940. if (commentStackLength === 0) return;
  941. let i = commentStackLength - 1;
  942. const lastCommentWS = commentStack[i];
  943. if (lastCommentWS.start === node.end) {
  944. lastCommentWS.leadingNode = node;
  945. i--;
  946. }
  947. const {
  948. start: nodeStart
  949. } = node;
  950. for (; i >= 0; i--) {
  951. const commentWS = commentStack[i];
  952. const commentEnd = commentWS.end;
  953. if (commentEnd > nodeStart) {
  954. commentWS.containingNode = node;
  955. this.finalizeComment(commentWS);
  956. commentStack.splice(i, 1);
  957. } else {
  958. if (commentEnd === nodeStart) {
  959. commentWS.trailingNode = node;
  960. }
  961. break;
  962. }
  963. }
  964. }
  965. finalizeComment(commentWS) {
  966. const {
  967. comments
  968. } = commentWS;
  969. if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {
  970. if (commentWS.leadingNode !== null) {
  971. setTrailingComments(commentWS.leadingNode, comments);
  972. }
  973. if (commentWS.trailingNode !== null) {
  974. setLeadingComments(commentWS.trailingNode, comments);
  975. }
  976. } else {
  977. const {
  978. containingNode: node,
  979. start: commentStart
  980. } = commentWS;
  981. if (this.input.charCodeAt(commentStart - 1) === 44) {
  982. switch (node.type) {
  983. case "ObjectExpression":
  984. case "ObjectPattern":
  985. case "RecordExpression":
  986. adjustInnerComments(node, node.properties, commentWS);
  987. break;
  988. case "CallExpression":
  989. case "OptionalCallExpression":
  990. adjustInnerComments(node, node.arguments, commentWS);
  991. break;
  992. case "FunctionDeclaration":
  993. case "FunctionExpression":
  994. case "ArrowFunctionExpression":
  995. case "ObjectMethod":
  996. case "ClassMethod":
  997. case "ClassPrivateMethod":
  998. adjustInnerComments(node, node.params, commentWS);
  999. break;
  1000. case "ArrayExpression":
  1001. case "ArrayPattern":
  1002. case "TupleExpression":
  1003. adjustInnerComments(node, node.elements, commentWS);
  1004. break;
  1005. case "ExportNamedDeclaration":
  1006. case "ImportDeclaration":
  1007. adjustInnerComments(node, node.specifiers, commentWS);
  1008. break;
  1009. default:
  1010. {
  1011. setInnerComments(node, comments);
  1012. }
  1013. }
  1014. } else {
  1015. setInnerComments(node, comments);
  1016. }
  1017. }
  1018. }
  1019. finalizeRemainingComments() {
  1020. const {
  1021. commentStack
  1022. } = this.state;
  1023. for (let i = commentStack.length - 1; i >= 0; i--) {
  1024. this.finalizeComment(commentStack[i]);
  1025. }
  1026. this.state.commentStack = [];
  1027. }
  1028. resetPreviousNodeTrailingComments(node) {
  1029. const {
  1030. commentStack
  1031. } = this.state;
  1032. const {
  1033. length
  1034. } = commentStack;
  1035. if (length === 0) return;
  1036. const commentWS = commentStack[length - 1];
  1037. if (commentWS.leadingNode === node) {
  1038. commentWS.leadingNode = null;
  1039. }
  1040. }
  1041. takeSurroundingComments(node, start, end) {
  1042. const {
  1043. commentStack
  1044. } = this.state;
  1045. const commentStackLength = commentStack.length;
  1046. if (commentStackLength === 0) return;
  1047. let i = commentStackLength - 1;
  1048. for (; i >= 0; i--) {
  1049. const commentWS = commentStack[i];
  1050. const commentEnd = commentWS.end;
  1051. const commentStart = commentWS.start;
  1052. if (commentStart === end) {
  1053. commentWS.leadingNode = node;
  1054. } else if (commentEnd === start) {
  1055. commentWS.trailingNode = node;
  1056. } else if (commentEnd < start) {
  1057. break;
  1058. }
  1059. }
  1060. }
  1061. }
  1062. const ErrorCodes = Object.freeze({
  1063. SyntaxError: "BABEL_PARSER_SYNTAX_ERROR",
  1064. SourceTypeModuleError: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  1065. });
  1066. const ErrorMessages = makeErrorTemplates({
  1067. AccessorIsGenerator: "A %0ter cannot be a generator.",
  1068. ArgumentsInClass: "'arguments' is only allowed in functions and class methods.",
  1069. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.",
  1070. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.",
  1071. AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.",
  1072. AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.",
  1073. AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.",
  1074. AwaitNotInAsyncFunction: "'await' is only allowed within async functions.",
  1075. BadGetterArity: "A 'get' accesor must not have any formal parameters.",
  1076. BadSetterArity: "A 'set' accesor must have exactly one formal parameter.",
  1077. BadSetterRestParameter: "A 'set' accesor function argument must not be a rest parameter.",
  1078. ConstructorClassField: "Classes may not have a field named 'constructor'.",
  1079. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.",
  1080. ConstructorIsAccessor: "Class constructor may not be an accessor.",
  1081. ConstructorIsAsync: "Constructor can't be an async function.",
  1082. ConstructorIsGenerator: "Constructor can't be a generator.",
  1083. DeclarationMissingInitializer: "'%0' require an initialization value.",
  1084. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax.",
  1085. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  1086. DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",
  1087. DecoratorSemicolon: "Decorators must not be followed by a semicolon.",
  1088. DecoratorStaticBlock: "Decorators can't be used with a static block.",
  1089. DeletePrivateField: "Deleting a private field is not allowed.",
  1090. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  1091. DuplicateConstructor: "Duplicate constructor in the same class.",
  1092. DuplicateDefaultExport: "Only one default export allowed per module.",
  1093. DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.",
  1094. DuplicateProto: "Redefinition of __proto__ property.",
  1095. DuplicateRegExpFlags: "Duplicate regular expression flag.",
  1096. ElementAfterRest: "Rest element must be last element.",
  1097. EscapedCharNotAnIdentifier: "Invalid Unicode escape.",
  1098. ExportBindingIsString: "A string literal cannot be used as an exported binding without `from`.\n- Did you mean `export { '%0' as '%1' } from 'some-module'`?",
  1099. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.",
  1100. ForInOfLoopInitializer: "'%0' loop variable declaration may not have an initializer.",
  1101. ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.",
  1102. ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.",
  1103. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.",
  1104. IllegalBreakContinue: "Unsyntactic %0.",
  1105. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.",
  1106. IllegalReturn: "'return' outside of function.",
  1107. ImportBindingIsString: 'A string literal cannot be used as an imported binding.\n- Did you mean `import { "%0" as foo }`?',
  1108. ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments.",
  1109. ImportCallArity: "`import()` requires exactly %0.",
  1110. ImportCallNotNewExpression: "Cannot use new with import(...).",
  1111. ImportCallSpreadArgument: "`...` is not allowed in `import()`.",
  1112. InvalidBigIntLiteral: "Invalid BigIntLiteral.",
  1113. InvalidCodePoint: "Code point out of bounds.",
  1114. InvalidDecimal: "Invalid decimal.",
  1115. InvalidDigit: "Expected number in radix %0.",
  1116. InvalidEscapeSequence: "Bad character escape sequence.",
  1117. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.",
  1118. InvalidEscapedReservedWord: "Escape sequence in keyword %0.",
  1119. InvalidIdentifier: "Invalid identifier %0.",
  1120. InvalidLhs: "Invalid left-hand side in %0.",
  1121. InvalidLhsBinding: "Binding invalid left-hand side in %0.",
  1122. InvalidNumber: "Invalid number.",
  1123. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.",
  1124. InvalidOrUnexpectedToken: "Unexpected character '%0'.",
  1125. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.",
  1126. InvalidPrivateFieldResolution: "Private name #%0 is not defined.",
  1127. InvalidPropertyBindingPattern: "Binding member expression.",
  1128. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.",
  1129. InvalidRestAssignmentPattern: "Invalid rest operator's argument.",
  1130. LabelRedeclaration: "Label '%0' is already declared.",
  1131. LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.",
  1132. LineTerminatorBeforeArrow: "No line break is allowed before '=>'.",
  1133. MalformedRegExpFlags: "Invalid regular expression flag.",
  1134. MissingClassName: "A class name is required.",
  1135. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  1136. MissingSemicolon: "Missing semicolon.",
  1137. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.",
  1138. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.",
  1139. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.",
  1140. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.",
  1141. ModuleAttributesWithDuplicateKeys: 'Duplicate key "%0" is not allowed in module attributes.',
  1142. ModuleExportNameHasLoneSurrogate: "An export name cannot include a lone surrogate, found '\\u%0'.",
  1143. ModuleExportUndefined: "Export '%0' is not defined.",
  1144. MultipleDefaultsInSwitch: "Multiple default clauses.",
  1145. NewlineAfterThrow: "Illegal newline after throw.",
  1146. NoCatchOrFinally: "Missing catch or finally clause.",
  1147. NumberIdentifier: "Identifier directly after number.",
  1148. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",
  1149. ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.",
  1150. OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.",
  1151. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.",
  1152. OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.",
  1153. ParamDupe: "Argument name clash.",
  1154. PatternHasAccessor: "Object pattern can't contain getter or setter.",
  1155. PatternHasMethod: "Object pattern can't contain methods.",
  1156. PipeBodyIsTighter: "Unexpected %0 after pipeline body; any %0 expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",
  1157. PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',
  1158. PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.",
  1159. PipeTopicUnconfiguredToken: 'Invalid topic token %0. In order to use %0 as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "%0" }.',
  1160. PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",
  1161. PipeUnparenthesizedBody: "Hack-style pipe body cannot be an unparenthesized %0 expression; please wrap it in parentheses.",
  1162. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.',
  1163. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.",
  1164. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.",
  1165. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.",
  1166. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.",
  1167. PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',
  1168. PrivateInExpectedIn: "Private names are only allowed in property accesses (`obj.#%0`) or in `in` expressions (`#%0 in obj`).",
  1169. PrivateNameRedeclaration: "Duplicate private name #%0.",
  1170. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  1171. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  1172. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  1173. RecordNoProto: "'__proto__' is not allowed in Record expressions.",
  1174. RestTrailingComma: "Unexpected trailing comma after rest element.",
  1175. SloppyFunction: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.",
  1176. StaticPrototype: "Classes may not have static property named prototype.",
  1177. StrictDelete: "Deleting local variable in strict mode.",
  1178. StrictEvalArguments: "Assigning to '%0' in strict mode.",
  1179. StrictEvalArgumentsBinding: "Binding '%0' in strict mode.",
  1180. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.",
  1181. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.",
  1182. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.",
  1183. StrictWith: "'with' in strict mode.",
  1184. SuperNotAllowed: "`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",
  1185. SuperPrivateField: "Private fields can't be accessed on super.",
  1186. TrailingDecorator: "Decorators must be attached to a class element.",
  1187. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  1188. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  1189. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  1190. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.",
  1191. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',
  1192. UnexpectedDigitAfterHash: "Unexpected digit after hash token.",
  1193. UnexpectedImportExport: "'import' and 'export' may only appear at the top level.",
  1194. UnexpectedKeyword: "Unexpected keyword '%0'.",
  1195. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.",
  1196. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.",
  1197. UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.",
  1198. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.",
  1199. UnexpectedPrivateField: "Private names can only be used as the name of a class element (i.e. class C { #p = 42; #m() {} } )\n or a property of member expression (i.e. this.#p).",
  1200. UnexpectedReservedWord: "Unexpected reserved word '%0'.",
  1201. UnexpectedSuper: "'super' is only allowed in object methods and classes.",
  1202. UnexpectedToken: "Unexpected token '%0'.",
  1203. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  1204. UnsupportedBind: "Binding should be performed on object property.",
  1205. UnsupportedDecoratorExport: "A decorated export must export a class declaration.",
  1206. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  1207. UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.",
  1208. UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1.",
  1209. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.",
  1210. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.",
  1211. UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",
  1212. UnterminatedComment: "Unterminated comment.",
  1213. UnterminatedRegExp: "Unterminated regular expression.",
  1214. UnterminatedString: "Unterminated string constant.",
  1215. UnterminatedTemplate: "Unterminated template.",
  1216. VarRedeclaration: "Identifier '%0' has already been declared.",
  1217. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.",
  1218. YieldInParameter: "Yield expression is not allowed in formal parameters.",
  1219. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0."
  1220. }, ErrorCodes.SyntaxError);
  1221. const SourceTypeModuleErrorMessages = makeErrorTemplates({
  1222. ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`,
  1223. ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'`
  1224. }, ErrorCodes.SourceTypeModuleError);
  1225. function keepReasonCodeCompat(reasonCode, syntaxPlugin) {
  1226. {
  1227. if (syntaxPlugin === "flow" && reasonCode === "PatternIsOptional") {
  1228. return "OptionalBindingPattern";
  1229. }
  1230. }
  1231. return reasonCode;
  1232. }
  1233. function makeErrorTemplates(messages, code, syntaxPlugin) {
  1234. const templates = {};
  1235. Object.keys(messages).forEach(reasonCode => {
  1236. templates[reasonCode] = Object.freeze({
  1237. code,
  1238. reasonCode: keepReasonCodeCompat(reasonCode, syntaxPlugin),
  1239. template: messages[reasonCode]
  1240. });
  1241. });
  1242. return Object.freeze(templates);
  1243. }
  1244. class ParserError extends CommentsParser {
  1245. getLocationForPosition(pos) {
  1246. let loc;
  1247. if (pos === this.state.start) loc = this.state.startLoc;else if (pos === this.state.lastTokStart) loc = this.state.lastTokStartLoc;else if (pos === this.state.end) loc = this.state.endLoc;else if (pos === this.state.lastTokEnd) loc = this.state.lastTokEndLoc;else loc = getLineInfo(this.input, pos);
  1248. return loc;
  1249. }
  1250. raise(pos, {
  1251. code,
  1252. reasonCode,
  1253. template
  1254. }, ...params) {
  1255. return this.raiseWithData(pos, {
  1256. code,
  1257. reasonCode
  1258. }, template, ...params);
  1259. }
  1260. raiseOverwrite(pos, {
  1261. code,
  1262. template
  1263. }, ...params) {
  1264. const loc = this.getLocationForPosition(pos);
  1265. const message = template.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  1266. if (this.options.errorRecovery) {
  1267. const errors = this.state.errors;
  1268. for (let i = errors.length - 1; i >= 0; i--) {
  1269. const error = errors[i];
  1270. if (error.pos === pos) {
  1271. return Object.assign(error, {
  1272. message
  1273. });
  1274. } else if (error.pos < pos) {
  1275. break;
  1276. }
  1277. }
  1278. }
  1279. return this._raise({
  1280. code,
  1281. loc,
  1282. pos
  1283. }, message);
  1284. }
  1285. raiseWithData(pos, data, errorTemplate, ...params) {
  1286. const loc = this.getLocationForPosition(pos);
  1287. const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  1288. return this._raise(Object.assign({
  1289. loc,
  1290. pos
  1291. }, data), message);
  1292. }
  1293. _raise(errorContext, message) {
  1294. const err = new SyntaxError(message);
  1295. Object.assign(err, errorContext);
  1296. if (this.options.errorRecovery) {
  1297. if (!this.isLookahead) this.state.errors.push(err);
  1298. return err;
  1299. } else {
  1300. throw err;
  1301. }
  1302. }
  1303. }
  1304. var estree = (superClass => class extends superClass {
  1305. parseRegExpLiteral({
  1306. pattern,
  1307. flags
  1308. }) {
  1309. let regex = null;
  1310. try {
  1311. regex = new RegExp(pattern, flags);
  1312. } catch (e) {}
  1313. const node = this.estreeParseLiteral(regex);
  1314. node.regex = {
  1315. pattern,
  1316. flags
  1317. };
  1318. return node;
  1319. }
  1320. parseBigIntLiteral(value) {
  1321. let bigInt;
  1322. try {
  1323. bigInt = BigInt(value);
  1324. } catch (_unused) {
  1325. bigInt = null;
  1326. }
  1327. const node = this.estreeParseLiteral(bigInt);
  1328. node.bigint = String(node.value || value);
  1329. return node;
  1330. }
  1331. parseDecimalLiteral(value) {
  1332. const decimal = null;
  1333. const node = this.estreeParseLiteral(decimal);
  1334. node.decimal = String(node.value || value);
  1335. return node;
  1336. }
  1337. estreeParseLiteral(value) {
  1338. return this.parseLiteral(value, "Literal");
  1339. }
  1340. parseStringLiteral(value) {
  1341. return this.estreeParseLiteral(value);
  1342. }
  1343. parseNumericLiteral(value) {
  1344. return this.estreeParseLiteral(value);
  1345. }
  1346. parseNullLiteral() {
  1347. return this.estreeParseLiteral(null);
  1348. }
  1349. parseBooleanLiteral(value) {
  1350. return this.estreeParseLiteral(value);
  1351. }
  1352. directiveToStmt(directive) {
  1353. const directiveLiteral = directive.value;
  1354. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  1355. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  1356. expression.value = directiveLiteral.extra.expressionValue;
  1357. expression.raw = directiveLiteral.extra.raw;
  1358. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  1359. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  1360. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  1361. }
  1362. initFunction(node, isAsync) {
  1363. super.initFunction(node, isAsync);
  1364. node.expression = false;
  1365. }
  1366. checkDeclaration(node) {
  1367. if (node != null && this.isObjectProperty(node)) {
  1368. this.checkDeclaration(node.value);
  1369. } else {
  1370. super.checkDeclaration(node);
  1371. }
  1372. }
  1373. getObjectOrClassMethodParams(method) {
  1374. return method.value.params;
  1375. }
  1376. isValidDirective(stmt) {
  1377. var _stmt$expression$extr;
  1378. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized);
  1379. }
  1380. parseBlockBody(node, ...args) {
  1381. super.parseBlockBody(node, ...args);
  1382. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  1383. node.body = directiveStatements.concat(node.body);
  1384. delete node.directives;
  1385. }
  1386. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  1387. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  1388. if (method.typeParameters) {
  1389. method.value.typeParameters = method.typeParameters;
  1390. delete method.typeParameters;
  1391. }
  1392. classBody.body.push(method);
  1393. }
  1394. parsePrivateName() {
  1395. const node = super.parsePrivateName();
  1396. {
  1397. if (!this.getPluginOption("estree", "classFeatures")) {
  1398. return node;
  1399. }
  1400. }
  1401. return this.convertPrivateNameToPrivateIdentifier(node);
  1402. }
  1403. convertPrivateNameToPrivateIdentifier(node) {
  1404. const name = super.getPrivateNameSV(node);
  1405. node = node;
  1406. delete node.id;
  1407. node.name = name;
  1408. node.type = "PrivateIdentifier";
  1409. return node;
  1410. }
  1411. isPrivateName(node) {
  1412. {
  1413. if (!this.getPluginOption("estree", "classFeatures")) {
  1414. return super.isPrivateName(node);
  1415. }
  1416. }
  1417. return node.type === "PrivateIdentifier";
  1418. }
  1419. getPrivateNameSV(node) {
  1420. {
  1421. if (!this.getPluginOption("estree", "classFeatures")) {
  1422. return super.getPrivateNameSV(node);
  1423. }
  1424. }
  1425. return node.name;
  1426. }
  1427. parseLiteral(value, type) {
  1428. const node = super.parseLiteral(value, type);
  1429. node.raw = node.extra.raw;
  1430. delete node.extra;
  1431. return node;
  1432. }
  1433. parseFunctionBody(node, allowExpression, isMethod = false) {
  1434. super.parseFunctionBody(node, allowExpression, isMethod);
  1435. node.expression = node.body.type !== "BlockStatement";
  1436. }
  1437. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  1438. let funcNode = this.startNode();
  1439. funcNode.kind = node.kind;
  1440. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  1441. funcNode.type = "FunctionExpression";
  1442. delete funcNode.kind;
  1443. node.value = funcNode;
  1444. if (type === "ClassPrivateMethod") {
  1445. node.computed = false;
  1446. }
  1447. type = "MethodDefinition";
  1448. return this.finishNode(node, type);
  1449. }
  1450. parseClassProperty(...args) {
  1451. const propertyNode = super.parseClassProperty(...args);
  1452. {
  1453. if (!this.getPluginOption("estree", "classFeatures")) {
  1454. return propertyNode;
  1455. }
  1456. }
  1457. propertyNode.type = "PropertyDefinition";
  1458. return propertyNode;
  1459. }
  1460. parseClassPrivateProperty(...args) {
  1461. const propertyNode = super.parseClassPrivateProperty(...args);
  1462. {
  1463. if (!this.getPluginOption("estree", "classFeatures")) {
  1464. return propertyNode;
  1465. }
  1466. }
  1467. propertyNode.type = "PropertyDefinition";
  1468. propertyNode.computed = false;
  1469. return propertyNode;
  1470. }
  1471. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  1472. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
  1473. if (node) {
  1474. node.type = "Property";
  1475. if (node.kind === "method") node.kind = "init";
  1476. node.shorthand = false;
  1477. }
  1478. return node;
  1479. }
  1480. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  1481. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  1482. if (node) {
  1483. node.kind = "init";
  1484. node.type = "Property";
  1485. }
  1486. return node;
  1487. }
  1488. isAssignable(node, isBinding) {
  1489. if (node != null && this.isObjectProperty(node)) {
  1490. return this.isAssignable(node.value, isBinding);
  1491. }
  1492. return super.isAssignable(node, isBinding);
  1493. }
  1494. toAssignable(node, isLHS = false) {
  1495. if (node != null && this.isObjectProperty(node)) {
  1496. this.toAssignable(node.value, isLHS);
  1497. return node;
  1498. }
  1499. return super.toAssignable(node, isLHS);
  1500. }
  1501. toAssignableObjectExpressionProp(prop, ...args) {
  1502. if (prop.kind === "get" || prop.kind === "set") {
  1503. this.raise(prop.key.start, ErrorMessages.PatternHasAccessor);
  1504. } else if (prop.method) {
  1505. this.raise(prop.key.start, ErrorMessages.PatternHasMethod);
  1506. } else {
  1507. super.toAssignableObjectExpressionProp(prop, ...args);
  1508. }
  1509. }
  1510. finishCallExpression(node, optional) {
  1511. super.finishCallExpression(node, optional);
  1512. if (node.callee.type === "Import") {
  1513. node.type = "ImportExpression";
  1514. node.source = node.arguments[0];
  1515. if (this.hasPlugin("importAssertions")) {
  1516. var _node$arguments$;
  1517. node.attributes = (_node$arguments$ = node.arguments[1]) != null ? _node$arguments$ : null;
  1518. }
  1519. delete node.arguments;
  1520. delete node.callee;
  1521. }
  1522. return node;
  1523. }
  1524. toReferencedArguments(node) {
  1525. if (node.type === "ImportExpression") {
  1526. return;
  1527. }
  1528. super.toReferencedArguments(node);
  1529. }
  1530. parseExport(node) {
  1531. super.parseExport(node);
  1532. switch (node.type) {
  1533. case "ExportAllDeclaration":
  1534. node.exported = null;
  1535. break;
  1536. case "ExportNamedDeclaration":
  1537. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  1538. node.type = "ExportAllDeclaration";
  1539. node.exported = node.specifiers[0].exported;
  1540. delete node.specifiers;
  1541. }
  1542. break;
  1543. }
  1544. return node;
  1545. }
  1546. parseSubscript(base, startPos, startLoc, noCalls, state) {
  1547. const node = super.parseSubscript(base, startPos, startLoc, noCalls, state);
  1548. if (state.optionalChainMember) {
  1549. if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") {
  1550. node.type = node.type.substring(8);
  1551. }
  1552. if (state.stop) {
  1553. const chain = this.startNodeAtNode(node);
  1554. chain.expression = node;
  1555. return this.finishNode(chain, "ChainExpression");
  1556. }
  1557. } else if (node.type === "MemberExpression" || node.type === "CallExpression") {
  1558. node.optional = false;
  1559. }
  1560. return node;
  1561. }
  1562. hasPropertyAsPrivateName(node) {
  1563. if (node.type === "ChainExpression") {
  1564. node = node.expression;
  1565. }
  1566. return super.hasPropertyAsPrivateName(node);
  1567. }
  1568. isOptionalChain(node) {
  1569. return node.type === "ChainExpression";
  1570. }
  1571. isObjectProperty(node) {
  1572. return node.type === "Property" && node.kind === "init" && !node.method;
  1573. }
  1574. isObjectMethod(node) {
  1575. return node.method || node.kind === "get" || node.kind === "set";
  1576. }
  1577. });
  1578. class TokContext {
  1579. constructor(token, preserveSpace) {
  1580. this.token = void 0;
  1581. this.preserveSpace = void 0;
  1582. this.token = token;
  1583. this.preserveSpace = !!preserveSpace;
  1584. }
  1585. }
  1586. const types$1 = {
  1587. brace: new TokContext("{"),
  1588. template: new TokContext("`", true)
  1589. };
  1590. const beforeExpr = true;
  1591. const startsExpr = true;
  1592. const isLoop = true;
  1593. const isAssign = true;
  1594. const prefix = true;
  1595. const postfix = true;
  1596. class ExportedTokenType {
  1597. constructor(label, conf = {}) {
  1598. this.label = void 0;
  1599. this.keyword = void 0;
  1600. this.beforeExpr = void 0;
  1601. this.startsExpr = void 0;
  1602. this.rightAssociative = void 0;
  1603. this.isLoop = void 0;
  1604. this.isAssign = void 0;
  1605. this.prefix = void 0;
  1606. this.postfix = void 0;
  1607. this.binop = void 0;
  1608. this.label = label;
  1609. this.keyword = conf.keyword;
  1610. this.beforeExpr = !!conf.beforeExpr;
  1611. this.startsExpr = !!conf.startsExpr;
  1612. this.rightAssociative = !!conf.rightAssociative;
  1613. this.isLoop = !!conf.isLoop;
  1614. this.isAssign = !!conf.isAssign;
  1615. this.prefix = !!conf.prefix;
  1616. this.postfix = !!conf.postfix;
  1617. this.binop = conf.binop != null ? conf.binop : null;
  1618. {
  1619. this.updateContext = null;
  1620. }
  1621. }
  1622. }
  1623. const keywords$1 = new Map();
  1624. function createKeyword(name, options = {}) {
  1625. options.keyword = name;
  1626. const token = createToken(name, options);
  1627. keywords$1.set(name, token);
  1628. return token;
  1629. }
  1630. function createBinop(name, binop) {
  1631. return createToken(name, {
  1632. beforeExpr,
  1633. binop
  1634. });
  1635. }
  1636. let tokenTypeCounter = -1;
  1637. const tokenTypes$1 = [];
  1638. const tokenLabels = [];
  1639. const tokenBinops = [];
  1640. const tokenBeforeExprs = [];
  1641. const tokenStartsExprs = [];
  1642. const tokenPrefixes = [];
  1643. function createToken(name, options = {}) {
  1644. var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix;
  1645. ++tokenTypeCounter;
  1646. tokenLabels.push(name);
  1647. tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1);
  1648. tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false);
  1649. tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false);
  1650. tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false);
  1651. tokenTypes$1.push(new ExportedTokenType(name, options));
  1652. return tokenTypeCounter;
  1653. }
  1654. function createKeywordLike(name, options = {}) {
  1655. var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2;
  1656. ++tokenTypeCounter;
  1657. keywords$1.set(name, tokenTypeCounter);
  1658. tokenLabels.push(name);
  1659. tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1);
  1660. tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false);
  1661. tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false);
  1662. tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false);
  1663. tokenTypes$1.push(new ExportedTokenType("name", options));
  1664. return tokenTypeCounter;
  1665. }
  1666. const tt = {
  1667. bracketL: createToken("[", {
  1668. beforeExpr,
  1669. startsExpr
  1670. }),
  1671. bracketHashL: createToken("#[", {
  1672. beforeExpr,
  1673. startsExpr
  1674. }),
  1675. bracketBarL: createToken("[|", {
  1676. beforeExpr,
  1677. startsExpr
  1678. }),
  1679. bracketR: createToken("]"),
  1680. bracketBarR: createToken("|]"),
  1681. braceL: createToken("{", {
  1682. beforeExpr,
  1683. startsExpr
  1684. }),
  1685. braceBarL: createToken("{|", {
  1686. beforeExpr,
  1687. startsExpr
  1688. }),
  1689. braceHashL: createToken("#{", {
  1690. beforeExpr,
  1691. startsExpr
  1692. }),
  1693. braceR: createToken("}", {
  1694. beforeExpr
  1695. }),
  1696. braceBarR: createToken("|}"),
  1697. parenL: createToken("(", {
  1698. beforeExpr,
  1699. startsExpr
  1700. }),
  1701. parenR: createToken(")"),
  1702. comma: createToken(",", {
  1703. beforeExpr
  1704. }),
  1705. semi: createToken(";", {
  1706. beforeExpr
  1707. }),
  1708. colon: createToken(":", {
  1709. beforeExpr
  1710. }),
  1711. doubleColon: createToken("::", {
  1712. beforeExpr
  1713. }),
  1714. dot: createToken("."),
  1715. question: createToken("?", {
  1716. beforeExpr
  1717. }),
  1718. questionDot: createToken("?."),
  1719. arrow: createToken("=>", {
  1720. beforeExpr
  1721. }),
  1722. template: createToken("template"),
  1723. ellipsis: createToken("...", {
  1724. beforeExpr
  1725. }),
  1726. backQuote: createToken("`", {
  1727. startsExpr
  1728. }),
  1729. dollarBraceL: createToken("${", {
  1730. beforeExpr,
  1731. startsExpr
  1732. }),
  1733. at: createToken("@"),
  1734. hash: createToken("#", {
  1735. startsExpr
  1736. }),
  1737. interpreterDirective: createToken("#!..."),
  1738. eq: createToken("=", {
  1739. beforeExpr,
  1740. isAssign
  1741. }),
  1742. assign: createToken("_=", {
  1743. beforeExpr,
  1744. isAssign
  1745. }),
  1746. slashAssign: createToken("_=", {
  1747. beforeExpr,
  1748. isAssign
  1749. }),
  1750. xorAssign: createToken("_=", {
  1751. beforeExpr,
  1752. isAssign
  1753. }),
  1754. moduloAssign: createToken("_=", {
  1755. beforeExpr,
  1756. isAssign
  1757. }),
  1758. incDec: createToken("++/--", {
  1759. prefix,
  1760. postfix,
  1761. startsExpr
  1762. }),
  1763. bang: createToken("!", {
  1764. beforeExpr,
  1765. prefix,
  1766. startsExpr
  1767. }),
  1768. tilde: createToken("~", {
  1769. beforeExpr,
  1770. prefix,
  1771. startsExpr
  1772. }),
  1773. pipeline: createBinop("|>", 0),
  1774. nullishCoalescing: createBinop("??", 1),
  1775. logicalOR: createBinop("||", 1),
  1776. logicalAND: createBinop("&&", 2),
  1777. bitwiseOR: createBinop("|", 3),
  1778. bitwiseXOR: createBinop("^", 4),
  1779. bitwiseAND: createBinop("&", 5),
  1780. equality: createBinop("==/!=/===/!==", 6),
  1781. lt: createBinop("</>/<=/>=", 7),
  1782. gt: createBinop("</>/<=/>=", 7),
  1783. relational: createBinop("</>/<=/>=", 7),
  1784. bitShift: createBinop("<</>>/>>>", 8),
  1785. plusMin: createToken("+/-", {
  1786. beforeExpr,
  1787. binop: 9,
  1788. prefix,
  1789. startsExpr
  1790. }),
  1791. modulo: createToken("%", {
  1792. binop: 10,
  1793. startsExpr
  1794. }),
  1795. star: createToken("*", {
  1796. binop: 10
  1797. }),
  1798. slash: createBinop("/", 10),
  1799. exponent: createToken("**", {
  1800. beforeExpr,
  1801. binop: 11,
  1802. rightAssociative: true
  1803. }),
  1804. _in: createKeyword("in", {
  1805. beforeExpr,
  1806. binop: 7
  1807. }),
  1808. _instanceof: createKeyword("instanceof", {
  1809. beforeExpr,
  1810. binop: 7
  1811. }),
  1812. _break: createKeyword("break"),
  1813. _case: createKeyword("case", {
  1814. beforeExpr
  1815. }),
  1816. _catch: createKeyword("catch"),
  1817. _continue: createKeyword("continue"),
  1818. _debugger: createKeyword("debugger"),
  1819. _default: createKeyword("default", {
  1820. beforeExpr
  1821. }),
  1822. _else: createKeyword("else", {
  1823. beforeExpr
  1824. }),
  1825. _finally: createKeyword("finally"),
  1826. _function: createKeyword("function", {
  1827. startsExpr
  1828. }),
  1829. _if: createKeyword("if"),
  1830. _return: createKeyword("return", {
  1831. beforeExpr
  1832. }),
  1833. _switch: createKeyword("switch"),
  1834. _throw: createKeyword("throw", {
  1835. beforeExpr,
  1836. prefix,
  1837. startsExpr
  1838. }),
  1839. _try: createKeyword("try"),
  1840. _var: createKeyword("var"),
  1841. _const: createKeyword("const"),
  1842. _with: createKeyword("with"),
  1843. _new: createKeyword("new", {
  1844. beforeExpr,
  1845. startsExpr
  1846. }),
  1847. _this: createKeyword("this", {
  1848. startsExpr
  1849. }),
  1850. _super: createKeyword("super", {
  1851. startsExpr
  1852. }),
  1853. _class: createKeyword("class", {
  1854. startsExpr
  1855. }),
  1856. _extends: createKeyword("extends", {
  1857. beforeExpr
  1858. }),
  1859. _export: createKeyword("export"),
  1860. _import: createKeyword("import", {
  1861. startsExpr
  1862. }),
  1863. _null: createKeyword("null", {
  1864. startsExpr
  1865. }),
  1866. _true: createKeyword("true", {
  1867. startsExpr
  1868. }),
  1869. _false: createKeyword("false", {
  1870. startsExpr
  1871. }),
  1872. _typeof: createKeyword("typeof", {
  1873. beforeExpr,
  1874. prefix,
  1875. startsExpr
  1876. }),
  1877. _void: createKeyword("void", {
  1878. beforeExpr,
  1879. prefix,
  1880. startsExpr
  1881. }),
  1882. _delete: createKeyword("delete", {
  1883. beforeExpr,
  1884. prefix,
  1885. startsExpr
  1886. }),
  1887. _do: createKeyword("do", {
  1888. isLoop,
  1889. beforeExpr
  1890. }),
  1891. _for: createKeyword("for", {
  1892. isLoop
  1893. }),
  1894. _while: createKeyword("while", {
  1895. isLoop
  1896. }),
  1897. _as: createKeywordLike("as", {
  1898. startsExpr
  1899. }),
  1900. _assert: createKeywordLike("assert", {
  1901. startsExpr
  1902. }),
  1903. _async: createKeywordLike("async", {
  1904. startsExpr
  1905. }),
  1906. _await: createKeywordLike("await", {
  1907. startsExpr
  1908. }),
  1909. _from: createKeywordLike("from", {
  1910. startsExpr
  1911. }),
  1912. _get: createKeywordLike("get", {
  1913. startsExpr
  1914. }),
  1915. _let: createKeywordLike("let", {
  1916. startsExpr
  1917. }),
  1918. _meta: createKeywordLike("meta", {
  1919. startsExpr
  1920. }),
  1921. _of: createKeywordLike("of", {
  1922. startsExpr
  1923. }),
  1924. _sent: createKeywordLike("sent", {
  1925. startsExpr
  1926. }),
  1927. _set: createKeywordLike("set", {
  1928. startsExpr
  1929. }),
  1930. _static: createKeywordLike("static", {
  1931. startsExpr
  1932. }),
  1933. _yield: createKeywordLike("yield", {
  1934. startsExpr
  1935. }),
  1936. _asserts: createKeywordLike("asserts", {
  1937. startsExpr
  1938. }),
  1939. _checks: createKeywordLike("checks", {
  1940. startsExpr
  1941. }),
  1942. _exports: createKeywordLike("exports", {
  1943. startsExpr
  1944. }),
  1945. _global: createKeywordLike("global", {
  1946. startsExpr
  1947. }),
  1948. _implements: createKeywordLike("implements", {
  1949. startsExpr
  1950. }),
  1951. _intrinsic: createKeywordLike("intrinsic", {
  1952. startsExpr
  1953. }),
  1954. _infer: createKeywordLike("infer", {
  1955. startsExpr
  1956. }),
  1957. _is: createKeywordLike("is", {
  1958. startsExpr
  1959. }),
  1960. _mixins: createKeywordLike("mixins", {
  1961. startsExpr
  1962. }),
  1963. _proto: createKeywordLike("proto", {
  1964. startsExpr
  1965. }),
  1966. _require: createKeywordLike("require", {
  1967. startsExpr
  1968. }),
  1969. _keyof: createKeywordLike("keyof", {
  1970. startsExpr
  1971. }),
  1972. _readonly: createKeywordLike("readonly", {
  1973. startsExpr
  1974. }),
  1975. _unique: createKeywordLike("unique", {
  1976. startsExpr
  1977. }),
  1978. _abstract: createKeywordLike("abstract", {
  1979. startsExpr
  1980. }),
  1981. _declare: createKeywordLike("declare", {
  1982. startsExpr
  1983. }),
  1984. _enum: createKeywordLike("enum", {
  1985. startsExpr
  1986. }),
  1987. _module: createKeywordLike("module", {
  1988. startsExpr
  1989. }),
  1990. _namespace: createKeywordLike("namespace", {
  1991. startsExpr
  1992. }),
  1993. _interface: createKeywordLike("interface", {
  1994. startsExpr
  1995. }),
  1996. _type: createKeywordLike("type", {
  1997. startsExpr
  1998. }),
  1999. _opaque: createKeywordLike("opaque", {
  2000. startsExpr
  2001. }),
  2002. name: createToken("name", {
  2003. startsExpr
  2004. }),
  2005. string: createToken("string", {
  2006. startsExpr
  2007. }),
  2008. num: createToken("num", {
  2009. startsExpr
  2010. }),
  2011. bigint: createToken("bigint", {
  2012. startsExpr
  2013. }),
  2014. decimal: createToken("decimal", {
  2015. startsExpr
  2016. }),
  2017. regexp: createToken("regexp", {
  2018. startsExpr
  2019. }),
  2020. privateName: createToken("#name", {
  2021. startsExpr
  2022. }),
  2023. eof: createToken("eof"),
  2024. jsxName: createToken("jsxName"),
  2025. jsxText: createToken("jsxText", {
  2026. beforeExpr: true
  2027. }),
  2028. jsxTagStart: createToken("jsxTagStart", {
  2029. startsExpr: true
  2030. }),
  2031. jsxTagEnd: createToken("jsxTagEnd"),
  2032. placeholder: createToken("%%", {
  2033. startsExpr: true
  2034. })
  2035. };
  2036. function tokenIsIdentifier(token) {
  2037. return token >= 87 && token <= 122;
  2038. }
  2039. function tokenKeywordOrIdentifierIsKeyword(token) {
  2040. return token <= 86;
  2041. }
  2042. function tokenIsKeywordOrIdentifier(token) {
  2043. return token >= 52 && token <= 122;
  2044. }
  2045. function tokenIsLiteralPropertyName(token) {
  2046. return token >= 52 && token <= 126;
  2047. }
  2048. function tokenComesBeforeExpression(token) {
  2049. return tokenBeforeExprs[token];
  2050. }
  2051. function tokenCanStartExpression(token) {
  2052. return tokenStartsExprs[token];
  2053. }
  2054. function tokenIsAssignment(token) {
  2055. return token >= 27 && token <= 31;
  2056. }
  2057. function tokenIsFlowInterfaceOrTypeOrOpaque(token) {
  2058. return token >= 119 && token <= 121;
  2059. }
  2060. function tokenIsLoop(token) {
  2061. return token >= 84 && token <= 86;
  2062. }
  2063. function tokenIsKeyword(token) {
  2064. return token >= 52 && token <= 86;
  2065. }
  2066. function tokenIsOperator(token) {
  2067. return token >= 35 && token <= 53;
  2068. }
  2069. function tokenIsPostfix(token) {
  2070. return token === 32;
  2071. }
  2072. function tokenIsPrefix(token) {
  2073. return tokenPrefixes[token];
  2074. }
  2075. function tokenIsTSTypeOperator(token) {
  2076. return token >= 111 && token <= 113;
  2077. }
  2078. function tokenIsTSDeclarationStart(token) {
  2079. return token >= 114 && token <= 120;
  2080. }
  2081. function tokenLabelName(token) {
  2082. return tokenLabels[token];
  2083. }
  2084. function tokenOperatorPrecedence(token) {
  2085. return tokenBinops[token];
  2086. }
  2087. function tokenIsRightAssociative(token) {
  2088. return token === 51;
  2089. }
  2090. function getExportedToken(token) {
  2091. return tokenTypes$1[token];
  2092. }
  2093. function isTokenType(obj) {
  2094. return typeof obj === "number";
  2095. }
  2096. {
  2097. tokenTypes$1[8].updateContext = context => {
  2098. context.pop();
  2099. };
  2100. tokenTypes$1[5].updateContext = tokenTypes$1[7].updateContext = tokenTypes$1[23].updateContext = context => {
  2101. context.push(types$1.brace);
  2102. };
  2103. tokenTypes$1[22].updateContext = context => {
  2104. if (context[context.length - 1] === types$1.template) {
  2105. context.pop();
  2106. } else {
  2107. context.push(types$1.template);
  2108. }
  2109. };
  2110. tokenTypes$1[132].updateContext = context => {
  2111. context.push(types$1.j_expr, types$1.j_oTag);
  2112. };
  2113. }
  2114. let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  2115. let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  2116. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  2117. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  2118. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  2119. const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1070, 4050, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 46, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 482, 44, 11, 6, 17, 0, 322, 29, 19, 43, 1269, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4152, 8, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
  2120. const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 357, 0, 62, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  2121. function isInAstralSet(code, set) {
  2122. let pos = 0x10000;
  2123. for (let i = 0, length = set.length; i < length; i += 2) {
  2124. pos += set[i];
  2125. if (pos > code) return false;
  2126. pos += set[i + 1];
  2127. if (pos >= code) return true;
  2128. }
  2129. return false;
  2130. }
  2131. function isIdentifierStart(code) {
  2132. if (code < 65) return code === 36;
  2133. if (code <= 90) return true;
  2134. if (code < 97) return code === 95;
  2135. if (code <= 122) return true;
  2136. if (code <= 0xffff) {
  2137. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  2138. }
  2139. return isInAstralSet(code, astralIdentifierStartCodes);
  2140. }
  2141. function isIdentifierChar(code) {
  2142. if (code < 48) return code === 36;
  2143. if (code < 58) return true;
  2144. if (code < 65) return false;
  2145. if (code <= 90) return true;
  2146. if (code < 97) return code === 95;
  2147. if (code <= 122) return true;
  2148. if (code <= 0xffff) {
  2149. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  2150. }
  2151. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  2152. }
  2153. const reservedWords = {
  2154. keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
  2155. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  2156. strictBind: ["eval", "arguments"]
  2157. };
  2158. const keywords = new Set(reservedWords.keyword);
  2159. const reservedWordsStrictSet = new Set(reservedWords.strict);
  2160. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  2161. function isReservedWord(word, inModule) {
  2162. return inModule && word === "await" || word === "enum";
  2163. }
  2164. function isStrictReservedWord(word, inModule) {
  2165. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  2166. }
  2167. function isStrictBindOnlyReservedWord(word) {
  2168. return reservedWordsStrictBindSet.has(word);
  2169. }
  2170. function isStrictBindReservedWord(word, inModule) {
  2171. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  2172. }
  2173. function isKeyword(word) {
  2174. return keywords.has(word);
  2175. }
  2176. function isIteratorStart(current, next) {
  2177. return current === 64 && next === 64;
  2178. }
  2179. const reservedWordLikeSet = new Set(["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", "eval", "arguments", "enum", "await"]);
  2180. function canBeReservedWord(word) {
  2181. return reservedWordLikeSet.has(word);
  2182. }
  2183. const SCOPE_OTHER = 0b000000000,
  2184. SCOPE_PROGRAM = 0b000000001,
  2185. SCOPE_FUNCTION = 0b000000010,
  2186. SCOPE_ARROW = 0b000000100,
  2187. SCOPE_SIMPLE_CATCH = 0b000001000,
  2188. SCOPE_SUPER = 0b000010000,
  2189. SCOPE_DIRECT_SUPER = 0b000100000,
  2190. SCOPE_CLASS = 0b001000000,
  2191. SCOPE_STATIC_BLOCK = 0b010000000,
  2192. SCOPE_TS_MODULE = 0b100000000,
  2193. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
  2194. const BIND_KIND_VALUE = 0b000000000001,
  2195. BIND_KIND_TYPE = 0b000000000010,
  2196. BIND_SCOPE_VAR = 0b000000000100,
  2197. BIND_SCOPE_LEXICAL = 0b000000001000,
  2198. BIND_SCOPE_FUNCTION = 0b000000010000,
  2199. BIND_FLAGS_NONE = 0b000001000000,
  2200. BIND_FLAGS_CLASS = 0b000010000000,
  2201. BIND_FLAGS_TS_ENUM = 0b000100000000,
  2202. BIND_FLAGS_TS_CONST_ENUM = 0b001000000000,
  2203. BIND_FLAGS_TS_EXPORT_ONLY = 0b010000000000,
  2204. BIND_FLAGS_FLOW_DECLARE_FN = 0b100000000000;
  2205. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  2206. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  2207. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  2208. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  2209. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  2210. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  2211. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  2212. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  2213. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  2214. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  2215. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  2216. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  2217. BIND_FLOW_DECLARE_FN = BIND_FLAGS_FLOW_DECLARE_FN;
  2218. const CLASS_ELEMENT_FLAG_STATIC = 0b100,
  2219. CLASS_ELEMENT_KIND_GETTER = 0b010,
  2220. CLASS_ELEMENT_KIND_SETTER = 0b001,
  2221. CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
  2222. const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
  2223. CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
  2224. CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
  2225. CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
  2226. CLASS_ELEMENT_OTHER = 0;
  2227. class Scope {
  2228. constructor(flags) {
  2229. this.var = new Set();
  2230. this.lexical = new Set();
  2231. this.functions = new Set();
  2232. this.flags = flags;
  2233. }
  2234. }
  2235. class ScopeHandler {
  2236. constructor(raise, inModule) {
  2237. this.scopeStack = [];
  2238. this.undefinedExports = new Map();
  2239. this.undefinedPrivateNames = new Map();
  2240. this.raise = raise;
  2241. this.inModule = inModule;
  2242. }
  2243. get inFunction() {
  2244. return (this.currentVarScopeFlags() & SCOPE_FUNCTION) > 0;
  2245. }
  2246. get allowSuper() {
  2247. return (this.currentThisScopeFlags() & SCOPE_SUPER) > 0;
  2248. }
  2249. get allowDirectSuper() {
  2250. return (this.currentThisScopeFlags() & SCOPE_DIRECT_SUPER) > 0;
  2251. }
  2252. get inClass() {
  2253. return (this.currentThisScopeFlags() & SCOPE_CLASS) > 0;
  2254. }
  2255. get inClassAndNotInNonArrowFunction() {
  2256. const flags = this.currentThisScopeFlags();
  2257. return (flags & SCOPE_CLASS) > 0 && (flags & SCOPE_FUNCTION) === 0;
  2258. }
  2259. get inStaticBlock() {
  2260. for (let i = this.scopeStack.length - 1;; i--) {
  2261. const {
  2262. flags
  2263. } = this.scopeStack[i];
  2264. if (flags & SCOPE_STATIC_BLOCK) {
  2265. return true;
  2266. }
  2267. if (flags & (SCOPE_VAR | SCOPE_CLASS)) {
  2268. return false;
  2269. }
  2270. }
  2271. }
  2272. get inNonArrowFunction() {
  2273. return (this.currentThisScopeFlags() & SCOPE_FUNCTION) > 0;
  2274. }
  2275. get treatFunctionsAsVar() {
  2276. return this.treatFunctionsAsVarInScope(this.currentScope());
  2277. }
  2278. createScope(flags) {
  2279. return new Scope(flags);
  2280. }
  2281. enter(flags) {
  2282. this.scopeStack.push(this.createScope(flags));
  2283. }
  2284. exit() {
  2285. this.scopeStack.pop();
  2286. }
  2287. treatFunctionsAsVarInScope(scope) {
  2288. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  2289. }
  2290. declareName(name, bindingType, pos) {
  2291. let scope = this.currentScope();
  2292. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  2293. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  2294. if (bindingType & BIND_SCOPE_FUNCTION) {
  2295. scope.functions.add(name);
  2296. } else {
  2297. scope.lexical.add(name);
  2298. }
  2299. if (bindingType & BIND_SCOPE_LEXICAL) {
  2300. this.maybeExportDefined(scope, name);
  2301. }
  2302. } else if (bindingType & BIND_SCOPE_VAR) {
  2303. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  2304. scope = this.scopeStack[i];
  2305. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  2306. scope.var.add(name);
  2307. this.maybeExportDefined(scope, name);
  2308. if (scope.flags & SCOPE_VAR) break;
  2309. }
  2310. }
  2311. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  2312. this.undefinedExports.delete(name);
  2313. }
  2314. }
  2315. maybeExportDefined(scope, name) {
  2316. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  2317. this.undefinedExports.delete(name);
  2318. }
  2319. }
  2320. checkRedeclarationInScope(scope, name, bindingType, pos) {
  2321. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  2322. this.raise(pos, ErrorMessages.VarRedeclaration, name);
  2323. }
  2324. }
  2325. isRedeclaredInScope(scope, name, bindingType) {
  2326. if (!(bindingType & BIND_KIND_VALUE)) return false;
  2327. if (bindingType & BIND_SCOPE_LEXICAL) {
  2328. return scope.lexical.has(name) || scope.functions.has(name) || scope.var.has(name);
  2329. }
  2330. if (bindingType & BIND_SCOPE_FUNCTION) {
  2331. return scope.lexical.has(name) || !this.treatFunctionsAsVarInScope(scope) && scope.var.has(name);
  2332. }
  2333. return scope.lexical.has(name) && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical.values().next().value === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.has(name);
  2334. }
  2335. checkLocalExport(id) {
  2336. const {
  2337. name
  2338. } = id;
  2339. const topLevelScope = this.scopeStack[0];
  2340. if (!topLevelScope.lexical.has(name) && !topLevelScope.var.has(name) && !topLevelScope.functions.has(name)) {
  2341. this.undefinedExports.set(name, id.start);
  2342. }
  2343. }
  2344. currentScope() {
  2345. return this.scopeStack[this.scopeStack.length - 1];
  2346. }
  2347. currentVarScopeFlags() {
  2348. for (let i = this.scopeStack.length - 1;; i--) {
  2349. const {
  2350. flags
  2351. } = this.scopeStack[i];
  2352. if (flags & SCOPE_VAR) {
  2353. return flags;
  2354. }
  2355. }
  2356. }
  2357. currentThisScopeFlags() {
  2358. for (let i = this.scopeStack.length - 1;; i--) {
  2359. const {
  2360. flags
  2361. } = this.scopeStack[i];
  2362. if (flags & (SCOPE_VAR | SCOPE_CLASS) && !(flags & SCOPE_ARROW)) {
  2363. return flags;
  2364. }
  2365. }
  2366. }
  2367. }
  2368. class FlowScope extends Scope {
  2369. constructor(...args) {
  2370. super(...args);
  2371. this.declareFunctions = new Set();
  2372. }
  2373. }
  2374. class FlowScopeHandler extends ScopeHandler {
  2375. createScope(flags) {
  2376. return new FlowScope(flags);
  2377. }
  2378. declareName(name, bindingType, pos) {
  2379. const scope = this.currentScope();
  2380. if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
  2381. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  2382. this.maybeExportDefined(scope, name);
  2383. scope.declareFunctions.add(name);
  2384. return;
  2385. }
  2386. super.declareName(...arguments);
  2387. }
  2388. isRedeclaredInScope(scope, name, bindingType) {
  2389. if (super.isRedeclaredInScope(...arguments)) return true;
  2390. if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
  2391. return !scope.declareFunctions.has(name) && (scope.lexical.has(name) || scope.functions.has(name));
  2392. }
  2393. return false;
  2394. }
  2395. checkLocalExport(id) {
  2396. if (!this.scopeStack[0].declareFunctions.has(id.name)) {
  2397. super.checkLocalExport(id);
  2398. }
  2399. }
  2400. }
  2401. class State {
  2402. constructor() {
  2403. this.strict = void 0;
  2404. this.curLine = void 0;
  2405. this.lineStart = void 0;
  2406. this.startLoc = void 0;
  2407. this.endLoc = void 0;
  2408. this.errors = [];
  2409. this.potentialArrowAt = -1;
  2410. this.noArrowAt = [];
  2411. this.noArrowParamsConversionAt = [];
  2412. this.maybeInArrowParameters = false;
  2413. this.inType = false;
  2414. this.noAnonFunctionType = false;
  2415. this.hasFlowComment = false;
  2416. this.isAmbientContext = false;
  2417. this.inAbstractClass = false;
  2418. this.topicContext = {
  2419. maxNumOfResolvableTopics: 0,
  2420. maxTopicIndex: null
  2421. };
  2422. this.soloAwait = false;
  2423. this.inFSharpPipelineDirectBody = false;
  2424. this.labels = [];
  2425. this.decoratorStack = [[]];
  2426. this.comments = [];
  2427. this.commentStack = [];
  2428. this.pos = 0;
  2429. this.type = 129;
  2430. this.value = null;
  2431. this.start = 0;
  2432. this.end = 0;
  2433. this.lastTokEndLoc = null;
  2434. this.lastTokStartLoc = null;
  2435. this.lastTokStart = 0;
  2436. this.lastTokEnd = 0;
  2437. this.context = [types$1.brace];
  2438. this.canStartJSXElement = true;
  2439. this.containsEsc = false;
  2440. this.strictErrors = new Map();
  2441. this.tokensLength = 0;
  2442. }
  2443. init({
  2444. strictMode,
  2445. sourceType,
  2446. startLine,
  2447. startColumn
  2448. }) {
  2449. this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module";
  2450. this.curLine = startLine;
  2451. this.lineStart = -startColumn;
  2452. this.startLoc = this.endLoc = new Position(startLine, startColumn);
  2453. }
  2454. curPosition() {
  2455. return new Position(this.curLine, this.pos - this.lineStart);
  2456. }
  2457. clone(skipArrays) {
  2458. const state = new State();
  2459. const keys = Object.keys(this);
  2460. for (let i = 0, length = keys.length; i < length; i++) {
  2461. const key = keys[i];
  2462. let val = this[key];
  2463. if (!skipArrays && Array.isArray(val)) {
  2464. val = val.slice();
  2465. }
  2466. state[key] = val;
  2467. }
  2468. return state;
  2469. }
  2470. }
  2471. var _isDigit = function isDigit(code) {
  2472. return code >= 48 && code <= 57;
  2473. };
  2474. const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100]);
  2475. const forbiddenNumericSeparatorSiblings = {
  2476. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  2477. hex: [46, 88, 95, 120]
  2478. };
  2479. const allowedNumericSeparatorSiblings = {};
  2480. allowedNumericSeparatorSiblings.bin = [48, 49];
  2481. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  2482. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  2483. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  2484. class Token {
  2485. constructor(state) {
  2486. this.type = state.type;
  2487. this.value = state.value;
  2488. this.start = state.start;
  2489. this.end = state.end;
  2490. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  2491. }
  2492. }
  2493. class Tokenizer extends ParserError {
  2494. constructor(options, input) {
  2495. super();
  2496. this.isLookahead = void 0;
  2497. this.tokens = [];
  2498. this.state = new State();
  2499. this.state.init(options);
  2500. this.input = input;
  2501. this.length = input.length;
  2502. this.isLookahead = false;
  2503. }
  2504. pushToken(token) {
  2505. this.tokens.length = this.state.tokensLength;
  2506. this.tokens.push(token);
  2507. ++this.state.tokensLength;
  2508. }
  2509. next() {
  2510. this.checkKeywordEscapes();
  2511. if (this.options.tokens) {
  2512. this.pushToken(new Token(this.state));
  2513. }
  2514. this.state.lastTokEnd = this.state.end;
  2515. this.state.lastTokStart = this.state.start;
  2516. this.state.lastTokEndLoc = this.state.endLoc;
  2517. this.state.lastTokStartLoc = this.state.startLoc;
  2518. this.nextToken();
  2519. }
  2520. eat(type) {
  2521. if (this.match(type)) {
  2522. this.next();
  2523. return true;
  2524. } else {
  2525. return false;
  2526. }
  2527. }
  2528. match(type) {
  2529. return this.state.type === type;
  2530. }
  2531. createLookaheadState(state) {
  2532. return {
  2533. pos: state.pos,
  2534. value: null,
  2535. type: state.type,
  2536. start: state.start,
  2537. end: state.end,
  2538. lastTokEnd: state.end,
  2539. context: [this.curContext()],
  2540. inType: state.inType
  2541. };
  2542. }
  2543. lookahead() {
  2544. const old = this.state;
  2545. this.state = this.createLookaheadState(old);
  2546. this.isLookahead = true;
  2547. this.nextToken();
  2548. this.isLookahead = false;
  2549. const curr = this.state;
  2550. this.state = old;
  2551. return curr;
  2552. }
  2553. nextTokenStart() {
  2554. return this.nextTokenStartSince(this.state.pos);
  2555. }
  2556. nextTokenStartSince(pos) {
  2557. skipWhiteSpace.lastIndex = pos;
  2558. return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;
  2559. }
  2560. lookaheadCharCode() {
  2561. return this.input.charCodeAt(this.nextTokenStart());
  2562. }
  2563. codePointAtPos(pos) {
  2564. let cp = this.input.charCodeAt(pos);
  2565. if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {
  2566. const trail = this.input.charCodeAt(pos);
  2567. if ((trail & 0xfc00) === 0xdc00) {
  2568. cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
  2569. }
  2570. }
  2571. return cp;
  2572. }
  2573. setStrict(strict) {
  2574. this.state.strict = strict;
  2575. if (strict) {
  2576. this.state.strictErrors.forEach((message, pos) => this.raise(pos, message));
  2577. this.state.strictErrors.clear();
  2578. }
  2579. }
  2580. curContext() {
  2581. return this.state.context[this.state.context.length - 1];
  2582. }
  2583. nextToken() {
  2584. const curContext = this.curContext();
  2585. if (!curContext.preserveSpace) this.skipSpace();
  2586. this.state.start = this.state.pos;
  2587. if (!this.isLookahead) this.state.startLoc = this.state.curPosition();
  2588. if (this.state.pos >= this.length) {
  2589. this.finishToken(129);
  2590. return;
  2591. }
  2592. if (curContext === types$1.template) {
  2593. this.readTmplToken();
  2594. } else {
  2595. this.getTokenFromCode(this.codePointAtPos(this.state.pos));
  2596. }
  2597. }
  2598. skipBlockComment() {
  2599. let startLoc;
  2600. if (!this.isLookahead) startLoc = this.state.curPosition();
  2601. const start = this.state.pos;
  2602. const end = this.input.indexOf("*/", start + 2);
  2603. if (end === -1) throw this.raise(start, ErrorMessages.UnterminatedComment);
  2604. this.state.pos = end + 2;
  2605. lineBreakG.lastIndex = start + 2;
  2606. while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {
  2607. ++this.state.curLine;
  2608. this.state.lineStart = lineBreakG.lastIndex;
  2609. }
  2610. if (this.isLookahead) return;
  2611. const comment = {
  2612. type: "CommentBlock",
  2613. value: this.input.slice(start + 2, end),
  2614. start,
  2615. end: end + 2,
  2616. loc: new SourceLocation(startLoc, this.state.curPosition())
  2617. };
  2618. if (this.options.tokens) this.pushToken(comment);
  2619. return comment;
  2620. }
  2621. skipLineComment(startSkip) {
  2622. const start = this.state.pos;
  2623. let startLoc;
  2624. if (!this.isLookahead) startLoc = this.state.curPosition();
  2625. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  2626. if (this.state.pos < this.length) {
  2627. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  2628. ch = this.input.charCodeAt(this.state.pos);
  2629. }
  2630. }
  2631. if (this.isLookahead) return;
  2632. const end = this.state.pos;
  2633. const value = this.input.slice(start + startSkip, end);
  2634. const comment = {
  2635. type: "CommentLine",
  2636. value,
  2637. start,
  2638. end,
  2639. loc: new SourceLocation(startLoc, this.state.curPosition())
  2640. };
  2641. if (this.options.tokens) this.pushToken(comment);
  2642. return comment;
  2643. }
  2644. skipSpace() {
  2645. const spaceStart = this.state.pos;
  2646. const comments = [];
  2647. loop: while (this.state.pos < this.length) {
  2648. const ch = this.input.charCodeAt(this.state.pos);
  2649. switch (ch) {
  2650. case 32:
  2651. case 160:
  2652. case 9:
  2653. ++this.state.pos;
  2654. break;
  2655. case 13:
  2656. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  2657. ++this.state.pos;
  2658. }
  2659. case 10:
  2660. case 8232:
  2661. case 8233:
  2662. ++this.state.pos;
  2663. ++this.state.curLine;
  2664. this.state.lineStart = this.state.pos;
  2665. break;
  2666. case 47:
  2667. switch (this.input.charCodeAt(this.state.pos + 1)) {
  2668. case 42:
  2669. {
  2670. const comment = this.skipBlockComment();
  2671. if (comment !== undefined) {
  2672. this.addComment(comment);
  2673. if (this.options.attachComment) comments.push(comment);
  2674. }
  2675. break;
  2676. }
  2677. case 47:
  2678. {
  2679. const comment = this.skipLineComment(2);
  2680. if (comment !== undefined) {
  2681. this.addComment(comment);
  2682. if (this.options.attachComment) comments.push(comment);
  2683. }
  2684. break;
  2685. }
  2686. default:
  2687. break loop;
  2688. }
  2689. break;
  2690. default:
  2691. if (isWhitespace(ch)) {
  2692. ++this.state.pos;
  2693. } else if (ch === 45 && !this.inModule) {
  2694. const pos = this.state.pos;
  2695. if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) {
  2696. const comment = this.skipLineComment(3);
  2697. if (comment !== undefined) {
  2698. this.addComment(comment);
  2699. if (this.options.attachComment) comments.push(comment);
  2700. }
  2701. } else {
  2702. break loop;
  2703. }
  2704. } else if (ch === 60 && !this.inModule) {
  2705. const pos = this.state.pos;
  2706. if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) {
  2707. const comment = this.skipLineComment(4);
  2708. if (comment !== undefined) {
  2709. this.addComment(comment);
  2710. if (this.options.attachComment) comments.push(comment);
  2711. }
  2712. } else {
  2713. break loop;
  2714. }
  2715. } else {
  2716. break loop;
  2717. }
  2718. }
  2719. }
  2720. if (comments.length > 0) {
  2721. const end = this.state.pos;
  2722. const CommentWhitespace = {
  2723. start: spaceStart,
  2724. end,
  2725. comments,
  2726. leadingNode: null,
  2727. trailingNode: null,
  2728. containingNode: null
  2729. };
  2730. this.state.commentStack.push(CommentWhitespace);
  2731. }
  2732. }
  2733. finishToken(type, val) {
  2734. this.state.end = this.state.pos;
  2735. const prevType = this.state.type;
  2736. this.state.type = type;
  2737. this.state.value = val;
  2738. if (!this.isLookahead) {
  2739. this.state.endLoc = this.state.curPosition();
  2740. this.updateContext(prevType);
  2741. }
  2742. }
  2743. replaceToken(type) {
  2744. this.state.type = type;
  2745. this.updateContext();
  2746. }
  2747. readToken_numberSign() {
  2748. if (this.state.pos === 0 && this.readToken_interpreter()) {
  2749. return;
  2750. }
  2751. const nextPos = this.state.pos + 1;
  2752. const next = this.codePointAtPos(nextPos);
  2753. if (next >= 48 && next <= 57) {
  2754. throw this.raise(this.state.pos, ErrorMessages.UnexpectedDigitAfterHash);
  2755. }
  2756. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  2757. this.expectPlugin("recordAndTuple");
  2758. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") {
  2759. throw this.raise(this.state.pos, next === 123 ? ErrorMessages.RecordExpressionHashIncorrectStartSyntaxType : ErrorMessages.TupleExpressionHashIncorrectStartSyntaxType);
  2760. }
  2761. this.state.pos += 2;
  2762. if (next === 123) {
  2763. this.finishToken(7);
  2764. } else {
  2765. this.finishToken(1);
  2766. }
  2767. } else if (isIdentifierStart(next)) {
  2768. ++this.state.pos;
  2769. this.finishToken(128, this.readWord1(next));
  2770. } else if (next === 92) {
  2771. ++this.state.pos;
  2772. this.finishToken(128, this.readWord1());
  2773. } else {
  2774. this.finishOp(25, 1);
  2775. }
  2776. }
  2777. readToken_dot() {
  2778. const next = this.input.charCodeAt(this.state.pos + 1);
  2779. if (next >= 48 && next <= 57) {
  2780. this.readNumber(true);
  2781. return;
  2782. }
  2783. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  2784. this.state.pos += 3;
  2785. this.finishToken(21);
  2786. } else {
  2787. ++this.state.pos;
  2788. this.finishToken(16);
  2789. }
  2790. }
  2791. readToken_slash() {
  2792. const next = this.input.charCodeAt(this.state.pos + 1);
  2793. if (next === 61) {
  2794. this.finishOp(29, 2);
  2795. } else {
  2796. this.finishOp(50, 1);
  2797. }
  2798. }
  2799. readToken_interpreter() {
  2800. if (this.state.pos !== 0 || this.length < 2) return false;
  2801. let ch = this.input.charCodeAt(this.state.pos + 1);
  2802. if (ch !== 33) return false;
  2803. const start = this.state.pos;
  2804. this.state.pos += 1;
  2805. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  2806. ch = this.input.charCodeAt(this.state.pos);
  2807. }
  2808. const value = this.input.slice(start + 2, this.state.pos);
  2809. this.finishToken(26, value);
  2810. return true;
  2811. }
  2812. readToken_mult_modulo(code) {
  2813. let type = code === 42 ? 49 : 48;
  2814. let width = 1;
  2815. let next = this.input.charCodeAt(this.state.pos + 1);
  2816. if (code === 42 && next === 42) {
  2817. width++;
  2818. next = this.input.charCodeAt(this.state.pos + 2);
  2819. type = 51;
  2820. }
  2821. if (next === 61 && !this.state.inType) {
  2822. width++;
  2823. type = code === 37 ? 31 : 28;
  2824. }
  2825. this.finishOp(type, width);
  2826. }
  2827. readToken_pipe_amp(code) {
  2828. const next = this.input.charCodeAt(this.state.pos + 1);
  2829. if (next === code) {
  2830. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  2831. this.finishOp(28, 3);
  2832. } else {
  2833. this.finishOp(code === 124 ? 37 : 38, 2);
  2834. }
  2835. return;
  2836. }
  2837. if (code === 124) {
  2838. if (next === 62) {
  2839. this.finishOp(35, 2);
  2840. return;
  2841. }
  2842. if (this.hasPlugin("recordAndTuple") && next === 125) {
  2843. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2844. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType);
  2845. }
  2846. this.state.pos += 2;
  2847. this.finishToken(9);
  2848. return;
  2849. }
  2850. if (this.hasPlugin("recordAndTuple") && next === 93) {
  2851. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2852. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType);
  2853. }
  2854. this.state.pos += 2;
  2855. this.finishToken(4);
  2856. return;
  2857. }
  2858. }
  2859. if (next === 61) {
  2860. this.finishOp(28, 2);
  2861. return;
  2862. }
  2863. this.finishOp(code === 124 ? 39 : 41, 1);
  2864. }
  2865. readToken_caret() {
  2866. const next = this.input.charCodeAt(this.state.pos + 1);
  2867. if (next === 61 && !this.state.inType) {
  2868. this.finishOp(30, 2);
  2869. } else {
  2870. this.finishOp(40, 1);
  2871. }
  2872. }
  2873. readToken_plus_min(code) {
  2874. const next = this.input.charCodeAt(this.state.pos + 1);
  2875. if (next === code) {
  2876. this.finishOp(32, 2);
  2877. return;
  2878. }
  2879. if (next === 61) {
  2880. this.finishOp(28, 2);
  2881. } else {
  2882. this.finishOp(47, 1);
  2883. }
  2884. }
  2885. readToken_lt() {
  2886. const {
  2887. pos
  2888. } = this.state;
  2889. const next = this.input.charCodeAt(pos + 1);
  2890. if (next === 60) {
  2891. if (this.input.charCodeAt(pos + 2) === 61) {
  2892. this.finishOp(28, 3);
  2893. return;
  2894. }
  2895. this.finishOp(46, 2);
  2896. return;
  2897. }
  2898. if (next === 61) {
  2899. this.finishOp(45, 2);
  2900. return;
  2901. }
  2902. this.finishOp(43, 1);
  2903. }
  2904. readToken_gt() {
  2905. const {
  2906. pos
  2907. } = this.state;
  2908. const next = this.input.charCodeAt(pos + 1);
  2909. if (next === 62) {
  2910. const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2;
  2911. if (this.input.charCodeAt(pos + size) === 61) {
  2912. this.finishOp(28, size + 1);
  2913. return;
  2914. }
  2915. this.finishOp(46, size);
  2916. return;
  2917. }
  2918. if (next === 61) {
  2919. this.finishOp(45, 2);
  2920. return;
  2921. }
  2922. this.finishOp(44, 1);
  2923. }
  2924. readToken_eq_excl(code) {
  2925. const next = this.input.charCodeAt(this.state.pos + 1);
  2926. if (next === 61) {
  2927. this.finishOp(42, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  2928. return;
  2929. }
  2930. if (code === 61 && next === 62) {
  2931. this.state.pos += 2;
  2932. this.finishToken(19);
  2933. return;
  2934. }
  2935. this.finishOp(code === 61 ? 27 : 33, 1);
  2936. }
  2937. readToken_question() {
  2938. const next = this.input.charCodeAt(this.state.pos + 1);
  2939. const next2 = this.input.charCodeAt(this.state.pos + 2);
  2940. if (next === 63) {
  2941. if (next2 === 61) {
  2942. this.finishOp(28, 3);
  2943. } else {
  2944. this.finishOp(36, 2);
  2945. }
  2946. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  2947. this.state.pos += 2;
  2948. this.finishToken(18);
  2949. } else {
  2950. ++this.state.pos;
  2951. this.finishToken(17);
  2952. }
  2953. }
  2954. getTokenFromCode(code) {
  2955. switch (code) {
  2956. case 46:
  2957. this.readToken_dot();
  2958. return;
  2959. case 40:
  2960. ++this.state.pos;
  2961. this.finishToken(10);
  2962. return;
  2963. case 41:
  2964. ++this.state.pos;
  2965. this.finishToken(11);
  2966. return;
  2967. case 59:
  2968. ++this.state.pos;
  2969. this.finishToken(13);
  2970. return;
  2971. case 44:
  2972. ++this.state.pos;
  2973. this.finishToken(12);
  2974. return;
  2975. case 91:
  2976. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  2977. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2978. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectStartSyntaxType);
  2979. }
  2980. this.state.pos += 2;
  2981. this.finishToken(2);
  2982. } else {
  2983. ++this.state.pos;
  2984. this.finishToken(0);
  2985. }
  2986. return;
  2987. case 93:
  2988. ++this.state.pos;
  2989. this.finishToken(3);
  2990. return;
  2991. case 123:
  2992. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  2993. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2994. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectStartSyntaxType);
  2995. }
  2996. this.state.pos += 2;
  2997. this.finishToken(6);
  2998. } else {
  2999. ++this.state.pos;
  3000. this.finishToken(5);
  3001. }
  3002. return;
  3003. case 125:
  3004. ++this.state.pos;
  3005. this.finishToken(8);
  3006. return;
  3007. case 58:
  3008. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  3009. this.finishOp(15, 2);
  3010. } else {
  3011. ++this.state.pos;
  3012. this.finishToken(14);
  3013. }
  3014. return;
  3015. case 63:
  3016. this.readToken_question();
  3017. return;
  3018. case 96:
  3019. ++this.state.pos;
  3020. this.finishToken(22);
  3021. return;
  3022. case 48:
  3023. {
  3024. const next = this.input.charCodeAt(this.state.pos + 1);
  3025. if (next === 120 || next === 88) {
  3026. this.readRadixNumber(16);
  3027. return;
  3028. }
  3029. if (next === 111 || next === 79) {
  3030. this.readRadixNumber(8);
  3031. return;
  3032. }
  3033. if (next === 98 || next === 66) {
  3034. this.readRadixNumber(2);
  3035. return;
  3036. }
  3037. }
  3038. case 49:
  3039. case 50:
  3040. case 51:
  3041. case 52:
  3042. case 53:
  3043. case 54:
  3044. case 55:
  3045. case 56:
  3046. case 57:
  3047. this.readNumber(false);
  3048. return;
  3049. case 34:
  3050. case 39:
  3051. this.readString(code);
  3052. return;
  3053. case 47:
  3054. this.readToken_slash();
  3055. return;
  3056. case 37:
  3057. case 42:
  3058. this.readToken_mult_modulo(code);
  3059. return;
  3060. case 124:
  3061. case 38:
  3062. this.readToken_pipe_amp(code);
  3063. return;
  3064. case 94:
  3065. this.readToken_caret();
  3066. return;
  3067. case 43:
  3068. case 45:
  3069. this.readToken_plus_min(code);
  3070. return;
  3071. case 60:
  3072. this.readToken_lt();
  3073. return;
  3074. case 62:
  3075. this.readToken_gt();
  3076. return;
  3077. case 61:
  3078. case 33:
  3079. this.readToken_eq_excl(code);
  3080. return;
  3081. case 126:
  3082. this.finishOp(34, 1);
  3083. return;
  3084. case 64:
  3085. ++this.state.pos;
  3086. this.finishToken(24);
  3087. return;
  3088. case 35:
  3089. this.readToken_numberSign();
  3090. return;
  3091. case 92:
  3092. this.readWord();
  3093. return;
  3094. default:
  3095. if (isIdentifierStart(code)) {
  3096. this.readWord(code);
  3097. return;
  3098. }
  3099. }
  3100. throw this.raise(this.state.pos, ErrorMessages.InvalidOrUnexpectedToken, String.fromCodePoint(code));
  3101. }
  3102. finishOp(type, size) {
  3103. const str = this.input.slice(this.state.pos, this.state.pos + size);
  3104. this.state.pos += size;
  3105. this.finishToken(type, str);
  3106. }
  3107. readRegexp() {
  3108. const start = this.state.start + 1;
  3109. let escaped, inClass;
  3110. let {
  3111. pos
  3112. } = this.state;
  3113. for (;; ++pos) {
  3114. if (pos >= this.length) {
  3115. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  3116. }
  3117. const ch = this.input.charCodeAt(pos);
  3118. if (isNewLine(ch)) {
  3119. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  3120. }
  3121. if (escaped) {
  3122. escaped = false;
  3123. } else {
  3124. if (ch === 91) {
  3125. inClass = true;
  3126. } else if (ch === 93 && inClass) {
  3127. inClass = false;
  3128. } else if (ch === 47 && !inClass) {
  3129. break;
  3130. }
  3131. escaped = ch === 92;
  3132. }
  3133. }
  3134. const content = this.input.slice(start, pos);
  3135. ++pos;
  3136. let mods = "";
  3137. while (pos < this.length) {
  3138. const cp = this.codePointAtPos(pos);
  3139. const char = String.fromCharCode(cp);
  3140. if (VALID_REGEX_FLAGS.has(cp)) {
  3141. if (mods.includes(char)) {
  3142. this.raise(pos + 1, ErrorMessages.DuplicateRegExpFlags);
  3143. }
  3144. } else if (isIdentifierChar(cp) || cp === 92) {
  3145. this.raise(pos + 1, ErrorMessages.MalformedRegExpFlags);
  3146. } else {
  3147. break;
  3148. }
  3149. ++pos;
  3150. mods += char;
  3151. }
  3152. this.state.pos = pos;
  3153. this.finishToken(127, {
  3154. pattern: content,
  3155. flags: mods
  3156. });
  3157. }
  3158. readInt(radix, len, forceLen, allowNumSeparator = true) {
  3159. const start = this.state.pos;
  3160. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  3161. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  3162. let invalid = false;
  3163. let total = 0;
  3164. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  3165. const code = this.input.charCodeAt(this.state.pos);
  3166. let val;
  3167. if (code === 95) {
  3168. const prev = this.input.charCodeAt(this.state.pos - 1);
  3169. const next = this.input.charCodeAt(this.state.pos + 1);
  3170. if (allowedSiblings.indexOf(next) === -1) {
  3171. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  3172. } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  3173. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  3174. }
  3175. if (!allowNumSeparator) {
  3176. this.raise(this.state.pos, ErrorMessages.NumericSeparatorInEscapeSequence);
  3177. }
  3178. ++this.state.pos;
  3179. continue;
  3180. }
  3181. if (code >= 97) {
  3182. val = code - 97 + 10;
  3183. } else if (code >= 65) {
  3184. val = code - 65 + 10;
  3185. } else if (_isDigit(code)) {
  3186. val = code - 48;
  3187. } else {
  3188. val = Infinity;
  3189. }
  3190. if (val >= radix) {
  3191. if (this.options.errorRecovery && val <= 9) {
  3192. val = 0;
  3193. this.raise(this.state.start + i + 2, ErrorMessages.InvalidDigit, radix);
  3194. } else if (forceLen) {
  3195. val = 0;
  3196. invalid = true;
  3197. } else {
  3198. break;
  3199. }
  3200. }
  3201. ++this.state.pos;
  3202. total = total * radix + val;
  3203. }
  3204. if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
  3205. return null;
  3206. }
  3207. return total;
  3208. }
  3209. readRadixNumber(radix) {
  3210. const start = this.state.pos;
  3211. let isBigInt = false;
  3212. this.state.pos += 2;
  3213. const val = this.readInt(radix);
  3214. if (val == null) {
  3215. this.raise(this.state.start + 2, ErrorMessages.InvalidDigit, radix);
  3216. }
  3217. const next = this.input.charCodeAt(this.state.pos);
  3218. if (next === 110) {
  3219. ++this.state.pos;
  3220. isBigInt = true;
  3221. } else if (next === 109) {
  3222. throw this.raise(start, ErrorMessages.InvalidDecimal);
  3223. }
  3224. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  3225. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  3226. }
  3227. if (isBigInt) {
  3228. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  3229. this.finishToken(125, str);
  3230. return;
  3231. }
  3232. this.finishToken(124, val);
  3233. }
  3234. readNumber(startsWithDot) {
  3235. const start = this.state.pos;
  3236. let isFloat = false;
  3237. let isBigInt = false;
  3238. let isDecimal = false;
  3239. let hasExponent = false;
  3240. let isOctal = false;
  3241. if (!startsWithDot && this.readInt(10) === null) {
  3242. this.raise(start, ErrorMessages.InvalidNumber);
  3243. }
  3244. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  3245. if (hasLeadingZero) {
  3246. const integer = this.input.slice(start, this.state.pos);
  3247. this.recordStrictModeErrors(start, ErrorMessages.StrictOctalLiteral);
  3248. if (!this.state.strict) {
  3249. const underscorePos = integer.indexOf("_");
  3250. if (underscorePos > 0) {
  3251. this.raise(underscorePos + start, ErrorMessages.ZeroDigitNumericSeparator);
  3252. }
  3253. }
  3254. isOctal = hasLeadingZero && !/[89]/.test(integer);
  3255. }
  3256. let next = this.input.charCodeAt(this.state.pos);
  3257. if (next === 46 && !isOctal) {
  3258. ++this.state.pos;
  3259. this.readInt(10);
  3260. isFloat = true;
  3261. next = this.input.charCodeAt(this.state.pos);
  3262. }
  3263. if ((next === 69 || next === 101) && !isOctal) {
  3264. next = this.input.charCodeAt(++this.state.pos);
  3265. if (next === 43 || next === 45) {
  3266. ++this.state.pos;
  3267. }
  3268. if (this.readInt(10) === null) {
  3269. this.raise(start, ErrorMessages.InvalidOrMissingExponent);
  3270. }
  3271. isFloat = true;
  3272. hasExponent = true;
  3273. next = this.input.charCodeAt(this.state.pos);
  3274. }
  3275. if (next === 110) {
  3276. if (isFloat || hasLeadingZero) {
  3277. this.raise(start, ErrorMessages.InvalidBigIntLiteral);
  3278. }
  3279. ++this.state.pos;
  3280. isBigInt = true;
  3281. }
  3282. if (next === 109) {
  3283. this.expectPlugin("decimal", this.state.pos);
  3284. if (hasExponent || hasLeadingZero) {
  3285. this.raise(start, ErrorMessages.InvalidDecimal);
  3286. }
  3287. ++this.state.pos;
  3288. isDecimal = true;
  3289. }
  3290. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  3291. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  3292. }
  3293. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  3294. if (isBigInt) {
  3295. this.finishToken(125, str);
  3296. return;
  3297. }
  3298. if (isDecimal) {
  3299. this.finishToken(126, str);
  3300. return;
  3301. }
  3302. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  3303. this.finishToken(124, val);
  3304. }
  3305. readCodePoint(throwOnInvalid) {
  3306. const ch = this.input.charCodeAt(this.state.pos);
  3307. let code;
  3308. if (ch === 123) {
  3309. const codePos = ++this.state.pos;
  3310. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
  3311. ++this.state.pos;
  3312. if (code !== null && code > 0x10ffff) {
  3313. if (throwOnInvalid) {
  3314. this.raise(codePos, ErrorMessages.InvalidCodePoint);
  3315. } else {
  3316. return null;
  3317. }
  3318. }
  3319. } else {
  3320. code = this.readHexChar(4, false, throwOnInvalid);
  3321. }
  3322. return code;
  3323. }
  3324. readString(quote) {
  3325. let out = "",
  3326. chunkStart = ++this.state.pos;
  3327. for (;;) {
  3328. if (this.state.pos >= this.length) {
  3329. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  3330. }
  3331. const ch = this.input.charCodeAt(this.state.pos);
  3332. if (ch === quote) break;
  3333. if (ch === 92) {
  3334. out += this.input.slice(chunkStart, this.state.pos);
  3335. out += this.readEscapedChar(false);
  3336. chunkStart = this.state.pos;
  3337. } else if (ch === 8232 || ch === 8233) {
  3338. ++this.state.pos;
  3339. ++this.state.curLine;
  3340. this.state.lineStart = this.state.pos;
  3341. } else if (isNewLine(ch)) {
  3342. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  3343. } else {
  3344. ++this.state.pos;
  3345. }
  3346. }
  3347. out += this.input.slice(chunkStart, this.state.pos++);
  3348. this.finishToken(123, out);
  3349. }
  3350. readTmplToken() {
  3351. let out = "",
  3352. chunkStart = this.state.pos,
  3353. containsInvalid = false;
  3354. for (;;) {
  3355. if (this.state.pos >= this.length) {
  3356. throw this.raise(this.state.start, ErrorMessages.UnterminatedTemplate);
  3357. }
  3358. const ch = this.input.charCodeAt(this.state.pos);
  3359. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  3360. if (this.state.pos === this.state.start && this.match(20)) {
  3361. if (ch === 36) {
  3362. this.state.pos += 2;
  3363. this.finishToken(23);
  3364. return;
  3365. } else {
  3366. ++this.state.pos;
  3367. this.finishToken(22);
  3368. return;
  3369. }
  3370. }
  3371. out += this.input.slice(chunkStart, this.state.pos);
  3372. this.finishToken(20, containsInvalid ? null : out);
  3373. return;
  3374. }
  3375. if (ch === 92) {
  3376. out += this.input.slice(chunkStart, this.state.pos);
  3377. const escaped = this.readEscapedChar(true);
  3378. if (escaped === null) {
  3379. containsInvalid = true;
  3380. } else {
  3381. out += escaped;
  3382. }
  3383. chunkStart = this.state.pos;
  3384. } else if (isNewLine(ch)) {
  3385. out += this.input.slice(chunkStart, this.state.pos);
  3386. ++this.state.pos;
  3387. switch (ch) {
  3388. case 13:
  3389. if (this.input.charCodeAt(this.state.pos) === 10) {
  3390. ++this.state.pos;
  3391. }
  3392. case 10:
  3393. out += "\n";
  3394. break;
  3395. default:
  3396. out += String.fromCharCode(ch);
  3397. break;
  3398. }
  3399. ++this.state.curLine;
  3400. this.state.lineStart = this.state.pos;
  3401. chunkStart = this.state.pos;
  3402. } else {
  3403. ++this.state.pos;
  3404. }
  3405. }
  3406. }
  3407. recordStrictModeErrors(pos, message) {
  3408. if (this.state.strict && !this.state.strictErrors.has(pos)) {
  3409. this.raise(pos, message);
  3410. } else {
  3411. this.state.strictErrors.set(pos, message);
  3412. }
  3413. }
  3414. readEscapedChar(inTemplate) {
  3415. const throwOnInvalid = !inTemplate;
  3416. const ch = this.input.charCodeAt(++this.state.pos);
  3417. ++this.state.pos;
  3418. switch (ch) {
  3419. case 110:
  3420. return "\n";
  3421. case 114:
  3422. return "\r";
  3423. case 120:
  3424. {
  3425. const code = this.readHexChar(2, false, throwOnInvalid);
  3426. return code === null ? null : String.fromCharCode(code);
  3427. }
  3428. case 117:
  3429. {
  3430. const code = this.readCodePoint(throwOnInvalid);
  3431. return code === null ? null : String.fromCodePoint(code);
  3432. }
  3433. case 116:
  3434. return "\t";
  3435. case 98:
  3436. return "\b";
  3437. case 118:
  3438. return "\u000b";
  3439. case 102:
  3440. return "\f";
  3441. case 13:
  3442. if (this.input.charCodeAt(this.state.pos) === 10) {
  3443. ++this.state.pos;
  3444. }
  3445. case 10:
  3446. this.state.lineStart = this.state.pos;
  3447. ++this.state.curLine;
  3448. case 8232:
  3449. case 8233:
  3450. return "";
  3451. case 56:
  3452. case 57:
  3453. if (inTemplate) {
  3454. return null;
  3455. } else {
  3456. this.recordStrictModeErrors(this.state.pos - 1, ErrorMessages.StrictNumericEscape);
  3457. }
  3458. default:
  3459. if (ch >= 48 && ch <= 55) {
  3460. const codePos = this.state.pos - 1;
  3461. const match = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/);
  3462. let octalStr = match[0];
  3463. let octal = parseInt(octalStr, 8);
  3464. if (octal > 255) {
  3465. octalStr = octalStr.slice(0, -1);
  3466. octal = parseInt(octalStr, 8);
  3467. }
  3468. this.state.pos += octalStr.length - 1;
  3469. const next = this.input.charCodeAt(this.state.pos);
  3470. if (octalStr !== "0" || next === 56 || next === 57) {
  3471. if (inTemplate) {
  3472. return null;
  3473. } else {
  3474. this.recordStrictModeErrors(codePos, ErrorMessages.StrictNumericEscape);
  3475. }
  3476. }
  3477. return String.fromCharCode(octal);
  3478. }
  3479. return String.fromCharCode(ch);
  3480. }
  3481. }
  3482. readHexChar(len, forceLen, throwOnInvalid) {
  3483. const codePos = this.state.pos;
  3484. const n = this.readInt(16, len, forceLen, false);
  3485. if (n === null) {
  3486. if (throwOnInvalid) {
  3487. this.raise(codePos, ErrorMessages.InvalidEscapeSequence);
  3488. } else {
  3489. this.state.pos = codePos - 1;
  3490. }
  3491. }
  3492. return n;
  3493. }
  3494. readWord1(firstCode) {
  3495. this.state.containsEsc = false;
  3496. let word = "";
  3497. const start = this.state.pos;
  3498. let chunkStart = this.state.pos;
  3499. if (firstCode !== undefined) {
  3500. this.state.pos += firstCode <= 0xffff ? 1 : 2;
  3501. }
  3502. while (this.state.pos < this.length) {
  3503. const ch = this.codePointAtPos(this.state.pos);
  3504. if (isIdentifierChar(ch)) {
  3505. this.state.pos += ch <= 0xffff ? 1 : 2;
  3506. } else if (ch === 92) {
  3507. this.state.containsEsc = true;
  3508. word += this.input.slice(chunkStart, this.state.pos);
  3509. const escStart = this.state.pos;
  3510. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  3511. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  3512. this.raise(this.state.pos, ErrorMessages.MissingUnicodeEscape);
  3513. chunkStart = this.state.pos - 1;
  3514. continue;
  3515. }
  3516. ++this.state.pos;
  3517. const esc = this.readCodePoint(true);
  3518. if (esc !== null) {
  3519. if (!identifierCheck(esc)) {
  3520. this.raise(escStart, ErrorMessages.EscapedCharNotAnIdentifier);
  3521. }
  3522. word += String.fromCodePoint(esc);
  3523. }
  3524. chunkStart = this.state.pos;
  3525. } else {
  3526. break;
  3527. }
  3528. }
  3529. return word + this.input.slice(chunkStart, this.state.pos);
  3530. }
  3531. readWord(firstCode) {
  3532. const word = this.readWord1(firstCode);
  3533. const type = keywords$1.get(word);
  3534. if (type !== undefined) {
  3535. this.finishToken(type, tokenLabelName(type));
  3536. } else {
  3537. this.finishToken(122, word);
  3538. }
  3539. }
  3540. checkKeywordEscapes() {
  3541. const {
  3542. type
  3543. } = this.state;
  3544. if (tokenIsKeyword(type) && this.state.containsEsc) {
  3545. this.raise(this.state.start, ErrorMessages.InvalidEscapedReservedWord, tokenLabelName(type));
  3546. }
  3547. }
  3548. updateContext(prevType) {
  3549. const {
  3550. context,
  3551. type
  3552. } = this.state;
  3553. switch (type) {
  3554. case 8:
  3555. context.pop();
  3556. break;
  3557. case 5:
  3558. case 7:
  3559. case 23:
  3560. context.push(types$1.brace);
  3561. break;
  3562. case 22:
  3563. if (context[context.length - 1] === types$1.template) {
  3564. context.pop();
  3565. } else {
  3566. context.push(types$1.template);
  3567. }
  3568. break;
  3569. }
  3570. }
  3571. }
  3572. class ClassScope {
  3573. constructor() {
  3574. this.privateNames = new Set();
  3575. this.loneAccessors = new Map();
  3576. this.undefinedPrivateNames = new Map();
  3577. }
  3578. }
  3579. class ClassScopeHandler {
  3580. constructor(raise) {
  3581. this.stack = [];
  3582. this.undefinedPrivateNames = new Map();
  3583. this.raise = raise;
  3584. }
  3585. current() {
  3586. return this.stack[this.stack.length - 1];
  3587. }
  3588. enter() {
  3589. this.stack.push(new ClassScope());
  3590. }
  3591. exit() {
  3592. const oldClassScope = this.stack.pop();
  3593. const current = this.current();
  3594. for (const [name, pos] of Array.from(oldClassScope.undefinedPrivateNames)) {
  3595. if (current) {
  3596. if (!current.undefinedPrivateNames.has(name)) {
  3597. current.undefinedPrivateNames.set(name, pos);
  3598. }
  3599. } else {
  3600. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  3601. }
  3602. }
  3603. }
  3604. declarePrivateName(name, elementType, pos) {
  3605. const classScope = this.current();
  3606. let redefined = classScope.privateNames.has(name);
  3607. if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
  3608. const accessor = redefined && classScope.loneAccessors.get(name);
  3609. if (accessor) {
  3610. const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
  3611. const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
  3612. const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
  3613. const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
  3614. redefined = oldKind === newKind || oldStatic !== newStatic;
  3615. if (!redefined) classScope.loneAccessors.delete(name);
  3616. } else if (!redefined) {
  3617. classScope.loneAccessors.set(name, elementType);
  3618. }
  3619. }
  3620. if (redefined) {
  3621. this.raise(pos, ErrorMessages.PrivateNameRedeclaration, name);
  3622. }
  3623. classScope.privateNames.add(name);
  3624. classScope.undefinedPrivateNames.delete(name);
  3625. }
  3626. usePrivateName(name, pos) {
  3627. let classScope;
  3628. for (classScope of this.stack) {
  3629. if (classScope.privateNames.has(name)) return;
  3630. }
  3631. if (classScope) {
  3632. classScope.undefinedPrivateNames.set(name, pos);
  3633. } else {
  3634. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  3635. }
  3636. }
  3637. }
  3638. const kExpression = 0,
  3639. kMaybeArrowParameterDeclaration = 1,
  3640. kMaybeAsyncArrowParameterDeclaration = 2,
  3641. kParameterDeclaration = 3;
  3642. class ExpressionScope {
  3643. constructor(type = kExpression) {
  3644. this.type = void 0;
  3645. this.type = type;
  3646. }
  3647. canBeArrowParameterDeclaration() {
  3648. return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration;
  3649. }
  3650. isCertainlyParameterDeclaration() {
  3651. return this.type === kParameterDeclaration;
  3652. }
  3653. }
  3654. class ArrowHeadParsingScope extends ExpressionScope {
  3655. constructor(type) {
  3656. super(type);
  3657. this.errors = new Map();
  3658. }
  3659. recordDeclarationError(pos, template) {
  3660. this.errors.set(pos, template);
  3661. }
  3662. clearDeclarationError(pos) {
  3663. this.errors.delete(pos);
  3664. }
  3665. iterateErrors(iterator) {
  3666. this.errors.forEach(iterator);
  3667. }
  3668. }
  3669. class ExpressionScopeHandler {
  3670. constructor(raise) {
  3671. this.stack = [new ExpressionScope()];
  3672. this.raise = raise;
  3673. }
  3674. enter(scope) {
  3675. this.stack.push(scope);
  3676. }
  3677. exit() {
  3678. this.stack.pop();
  3679. }
  3680. recordParameterInitializerError(pos, template) {
  3681. const {
  3682. stack
  3683. } = this;
  3684. let i = stack.length - 1;
  3685. let scope = stack[i];
  3686. while (!scope.isCertainlyParameterDeclaration()) {
  3687. if (scope.canBeArrowParameterDeclaration()) {
  3688. scope.recordDeclarationError(pos, template);
  3689. } else {
  3690. return;
  3691. }
  3692. scope = stack[--i];
  3693. }
  3694. this.raise(pos, template);
  3695. }
  3696. recordParenthesizedIdentifierError(pos, template) {
  3697. const {
  3698. stack
  3699. } = this;
  3700. const scope = stack[stack.length - 1];
  3701. if (scope.isCertainlyParameterDeclaration()) {
  3702. this.raise(pos, template);
  3703. } else if (scope.canBeArrowParameterDeclaration()) {
  3704. scope.recordDeclarationError(pos, template);
  3705. } else {
  3706. return;
  3707. }
  3708. }
  3709. recordAsyncArrowParametersError(pos, template) {
  3710. const {
  3711. stack
  3712. } = this;
  3713. let i = stack.length - 1;
  3714. let scope = stack[i];
  3715. while (scope.canBeArrowParameterDeclaration()) {
  3716. if (scope.type === kMaybeAsyncArrowParameterDeclaration) {
  3717. scope.recordDeclarationError(pos, template);
  3718. }
  3719. scope = stack[--i];
  3720. }
  3721. }
  3722. validateAsPattern() {
  3723. const {
  3724. stack
  3725. } = this;
  3726. const currentScope = stack[stack.length - 1];
  3727. if (!currentScope.canBeArrowParameterDeclaration()) return;
  3728. currentScope.iterateErrors((template, pos) => {
  3729. this.raise(pos, template);
  3730. let i = stack.length - 2;
  3731. let scope = stack[i];
  3732. while (scope.canBeArrowParameterDeclaration()) {
  3733. scope.clearDeclarationError(pos);
  3734. scope = stack[--i];
  3735. }
  3736. });
  3737. }
  3738. }
  3739. function newParameterDeclarationScope() {
  3740. return new ExpressionScope(kParameterDeclaration);
  3741. }
  3742. function newArrowHeadScope() {
  3743. return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration);
  3744. }
  3745. function newAsyncArrowScope() {
  3746. return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration);
  3747. }
  3748. function newExpressionScope() {
  3749. return new ExpressionScope();
  3750. }
  3751. const PARAM = 0b0000,
  3752. PARAM_YIELD = 0b0001,
  3753. PARAM_AWAIT = 0b0010,
  3754. PARAM_RETURN = 0b0100,
  3755. PARAM_IN = 0b1000;
  3756. class ProductionParameterHandler {
  3757. constructor() {
  3758. this.stacks = [];
  3759. }
  3760. enter(flags) {
  3761. this.stacks.push(flags);
  3762. }
  3763. exit() {
  3764. this.stacks.pop();
  3765. }
  3766. currentFlags() {
  3767. return this.stacks[this.stacks.length - 1];
  3768. }
  3769. get hasAwait() {
  3770. return (this.currentFlags() & PARAM_AWAIT) > 0;
  3771. }
  3772. get hasYield() {
  3773. return (this.currentFlags() & PARAM_YIELD) > 0;
  3774. }
  3775. get hasReturn() {
  3776. return (this.currentFlags() & PARAM_RETURN) > 0;
  3777. }
  3778. get hasIn() {
  3779. return (this.currentFlags() & PARAM_IN) > 0;
  3780. }
  3781. }
  3782. function functionFlags(isAsync, isGenerator) {
  3783. return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
  3784. }
  3785. class UtilParser extends Tokenizer {
  3786. addExtra(node, key, val) {
  3787. if (!node) return;
  3788. const extra = node.extra = node.extra || {};
  3789. extra[key] = val;
  3790. }
  3791. isContextual(token) {
  3792. return this.state.type === token && !this.state.containsEsc;
  3793. }
  3794. isUnparsedContextual(nameStart, name) {
  3795. const nameEnd = nameStart + name.length;
  3796. if (this.input.slice(nameStart, nameEnd) === name) {
  3797. const nextCh = this.input.charCodeAt(nameEnd);
  3798. return !(isIdentifierChar(nextCh) || (nextCh & 0xfc00) === 0xd800);
  3799. }
  3800. return false;
  3801. }
  3802. isLookaheadContextual(name) {
  3803. const next = this.nextTokenStart();
  3804. return this.isUnparsedContextual(next, name);
  3805. }
  3806. eatContextual(token) {
  3807. if (this.isContextual(token)) {
  3808. this.next();
  3809. return true;
  3810. }
  3811. return false;
  3812. }
  3813. expectContextual(token, template) {
  3814. if (!this.eatContextual(token)) this.unexpected(null, template);
  3815. }
  3816. canInsertSemicolon() {
  3817. return this.match(129) || this.match(8) || this.hasPrecedingLineBreak();
  3818. }
  3819. hasPrecedingLineBreak() {
  3820. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  3821. }
  3822. hasFollowingLineBreak() {
  3823. skipWhiteSpaceToLineBreak.lastIndex = this.state.end;
  3824. return skipWhiteSpaceToLineBreak.test(this.input);
  3825. }
  3826. isLineTerminator() {
  3827. return this.eat(13) || this.canInsertSemicolon();
  3828. }
  3829. semicolon(allowAsi = true) {
  3830. if (allowAsi ? this.isLineTerminator() : this.eat(13)) return;
  3831. this.raise(this.state.lastTokEnd, ErrorMessages.MissingSemicolon);
  3832. }
  3833. expect(type, pos) {
  3834. this.eat(type) || this.unexpected(pos, type);
  3835. }
  3836. assertNoSpace(message = "Unexpected space.") {
  3837. if (this.state.start > this.state.lastTokEnd) {
  3838. this.raise(this.state.lastTokEnd, {
  3839. code: ErrorCodes.SyntaxError,
  3840. reasonCode: "UnexpectedSpace",
  3841. template: message
  3842. });
  3843. }
  3844. }
  3845. unexpected(pos, messageOrType = {
  3846. code: ErrorCodes.SyntaxError,
  3847. reasonCode: "UnexpectedToken",
  3848. template: "Unexpected token"
  3849. }) {
  3850. if (isTokenType(messageOrType)) {
  3851. messageOrType = {
  3852. code: ErrorCodes.SyntaxError,
  3853. reasonCode: "UnexpectedToken",
  3854. template: `Unexpected token, expected "${tokenLabelName(messageOrType)}"`
  3855. };
  3856. }
  3857. throw this.raise(pos != null ? pos : this.state.start, messageOrType);
  3858. }
  3859. expectPlugin(name, pos) {
  3860. if (!this.hasPlugin(name)) {
  3861. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  3862. missingPlugin: [name]
  3863. }, `This experimental syntax requires enabling the parser plugin: '${name}'`);
  3864. }
  3865. return true;
  3866. }
  3867. expectOnePlugin(names, pos) {
  3868. if (!names.some(n => this.hasPlugin(n))) {
  3869. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  3870. missingPlugin: names
  3871. }, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`);
  3872. }
  3873. }
  3874. tryParse(fn, oldState = this.state.clone()) {
  3875. const abortSignal = {
  3876. node: null
  3877. };
  3878. try {
  3879. const node = fn((node = null) => {
  3880. abortSignal.node = node;
  3881. throw abortSignal;
  3882. });
  3883. if (this.state.errors.length > oldState.errors.length) {
  3884. const failState = this.state;
  3885. this.state = oldState;
  3886. this.state.tokensLength = failState.tokensLength;
  3887. return {
  3888. node,
  3889. error: failState.errors[oldState.errors.length],
  3890. thrown: false,
  3891. aborted: false,
  3892. failState
  3893. };
  3894. }
  3895. return {
  3896. node,
  3897. error: null,
  3898. thrown: false,
  3899. aborted: false,
  3900. failState: null
  3901. };
  3902. } catch (error) {
  3903. const failState = this.state;
  3904. this.state = oldState;
  3905. if (error instanceof SyntaxError) {
  3906. return {
  3907. node: null,
  3908. error,
  3909. thrown: true,
  3910. aborted: false,
  3911. failState
  3912. };
  3913. }
  3914. if (error === abortSignal) {
  3915. return {
  3916. node: abortSignal.node,
  3917. error: null,
  3918. thrown: false,
  3919. aborted: true,
  3920. failState
  3921. };
  3922. }
  3923. throw error;
  3924. }
  3925. }
  3926. checkExpressionErrors(refExpressionErrors, andThrow) {
  3927. if (!refExpressionErrors) return false;
  3928. const {
  3929. shorthandAssign,
  3930. doubleProto,
  3931. optionalParameters
  3932. } = refExpressionErrors;
  3933. const hasErrors = shorthandAssign + doubleProto + optionalParameters > -3;
  3934. if (!andThrow) {
  3935. return hasErrors;
  3936. } else if (hasErrors) {
  3937. if (shorthandAssign >= 0) {
  3938. this.unexpected(shorthandAssign);
  3939. }
  3940. if (doubleProto >= 0) {
  3941. this.raise(doubleProto, ErrorMessages.DuplicateProto);
  3942. }
  3943. if (optionalParameters >= 0) {
  3944. this.unexpected(optionalParameters);
  3945. }
  3946. }
  3947. }
  3948. isLiteralPropertyName() {
  3949. return tokenIsLiteralPropertyName(this.state.type);
  3950. }
  3951. isPrivateName(node) {
  3952. return node.type === "PrivateName";
  3953. }
  3954. getPrivateNameSV(node) {
  3955. return node.id.name;
  3956. }
  3957. hasPropertyAsPrivateName(node) {
  3958. return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property);
  3959. }
  3960. isOptionalChain(node) {
  3961. return node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression";
  3962. }
  3963. isObjectProperty(node) {
  3964. return node.type === "ObjectProperty";
  3965. }
  3966. isObjectMethod(node) {
  3967. return node.type === "ObjectMethod";
  3968. }
  3969. initializeScopes(inModule = this.options.sourceType === "module") {
  3970. const oldLabels = this.state.labels;
  3971. this.state.labels = [];
  3972. const oldExportedIdentifiers = this.exportedIdentifiers;
  3973. this.exportedIdentifiers = new Set();
  3974. const oldInModule = this.inModule;
  3975. this.inModule = inModule;
  3976. const oldScope = this.scope;
  3977. const ScopeHandler = this.getScopeHandler();
  3978. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  3979. const oldProdParam = this.prodParam;
  3980. this.prodParam = new ProductionParameterHandler();
  3981. const oldClassScope = this.classScope;
  3982. this.classScope = new ClassScopeHandler(this.raise.bind(this));
  3983. const oldExpressionScope = this.expressionScope;
  3984. this.expressionScope = new ExpressionScopeHandler(this.raise.bind(this));
  3985. return () => {
  3986. this.state.labels = oldLabels;
  3987. this.exportedIdentifiers = oldExportedIdentifiers;
  3988. this.inModule = oldInModule;
  3989. this.scope = oldScope;
  3990. this.prodParam = oldProdParam;
  3991. this.classScope = oldClassScope;
  3992. this.expressionScope = oldExpressionScope;
  3993. };
  3994. }
  3995. enterInitialScopes() {
  3996. let paramFlags = PARAM;
  3997. if (this.inModule) {
  3998. paramFlags |= PARAM_AWAIT;
  3999. }
  4000. this.scope.enter(SCOPE_PROGRAM);
  4001. this.prodParam.enter(paramFlags);
  4002. }
  4003. }
  4004. class ExpressionErrors {
  4005. constructor() {
  4006. this.shorthandAssign = -1;
  4007. this.doubleProto = -1;
  4008. this.optionalParameters = -1;
  4009. }
  4010. }
  4011. let Node$5 = class Node {
  4012. constructor(parser, pos, loc) {
  4013. this.type = "";
  4014. this.start = pos;
  4015. this.end = 0;
  4016. this.loc = new SourceLocation(loc);
  4017. if (parser != null && parser.options.ranges) this.range = [pos, 0];
  4018. if (parser != null && parser.filename) this.loc.filename = parser.filename;
  4019. }
  4020. };
  4021. const NodePrototype = Node$5.prototype;
  4022. {
  4023. NodePrototype.__clone = function () {
  4024. const newNode = new Node$5();
  4025. const keys = Object.keys(this);
  4026. for (let i = 0, length = keys.length; i < length; i++) {
  4027. const key = keys[i];
  4028. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  4029. newNode[key] = this[key];
  4030. }
  4031. }
  4032. return newNode;
  4033. };
  4034. }
  4035. function clonePlaceholder(node) {
  4036. return cloneIdentifier(node);
  4037. }
  4038. function cloneIdentifier(node) {
  4039. const {
  4040. type,
  4041. start,
  4042. end,
  4043. loc,
  4044. range,
  4045. extra,
  4046. name
  4047. } = node;
  4048. const cloned = Object.create(NodePrototype);
  4049. cloned.type = type;
  4050. cloned.start = start;
  4051. cloned.end = end;
  4052. cloned.loc = loc;
  4053. cloned.range = range;
  4054. cloned.extra = extra;
  4055. cloned.name = name;
  4056. if (type === "Placeholder") {
  4057. cloned.expectedNode = node.expectedNode;
  4058. }
  4059. return cloned;
  4060. }
  4061. function cloneStringLiteral(node) {
  4062. const {
  4063. type,
  4064. start,
  4065. end,
  4066. loc,
  4067. range,
  4068. extra
  4069. } = node;
  4070. if (type === "Placeholder") {
  4071. return clonePlaceholder(node);
  4072. }
  4073. const cloned = Object.create(NodePrototype);
  4074. cloned.type = "StringLiteral";
  4075. cloned.start = start;
  4076. cloned.end = end;
  4077. cloned.loc = loc;
  4078. cloned.range = range;
  4079. cloned.extra = extra;
  4080. cloned.value = node.value;
  4081. return cloned;
  4082. }
  4083. class NodeUtils extends UtilParser {
  4084. startNode() {
  4085. return new Node$5(this, this.state.start, this.state.startLoc);
  4086. }
  4087. startNodeAt(pos, loc) {
  4088. return new Node$5(this, pos, loc);
  4089. }
  4090. startNodeAtNode(type) {
  4091. return this.startNodeAt(type.start, type.loc.start);
  4092. }
  4093. finishNode(node, type) {
  4094. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  4095. }
  4096. finishNodeAt(node, type, pos, loc) {
  4097. node.type = type;
  4098. node.end = pos;
  4099. node.loc.end = loc;
  4100. if (this.options.ranges) node.range[1] = pos;
  4101. if (this.options.attachComment) this.processComment(node);
  4102. return node;
  4103. }
  4104. resetStartLocation(node, start, startLoc) {
  4105. node.start = start;
  4106. node.loc.start = startLoc;
  4107. if (this.options.ranges) node.range[0] = start;
  4108. }
  4109. resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
  4110. node.end = end;
  4111. node.loc.end = endLoc;
  4112. if (this.options.ranges) node.range[1] = end;
  4113. }
  4114. resetStartLocationFromNode(node, locationNode) {
  4115. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  4116. }
  4117. }
  4118. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  4119. const FlowErrors = makeErrorTemplates({
  4120. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  4121. AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.",
  4122. AssignReservedType: "Cannot overwrite reserved type %0.",
  4123. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  4124. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  4125. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.",
  4126. EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
  4127. EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
  4128. EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
  4129. EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  4130. EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  4131. EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
  4132. EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
  4133. EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
  4134. EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
  4135. EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
  4136. EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
  4137. GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
  4138. ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.",
  4139. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.",
  4140. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.",
  4141. InexactVariance: "Explicit inexact syntax cannot have variance.",
  4142. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.",
  4143. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  4144. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.",
  4145. NestedFlowComment: "Cannot have a flow comment inside another flow comment.",
  4146. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  4147. SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
  4148. SpreadVariance: "Spread properties cannot have variance.",
  4149. ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.",
  4150. ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
  4151. ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
  4152. ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.",
  4153. ThisParamNoDefault: "The `this` parameter may not have a default value.",
  4154. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  4155. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.",
  4156. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.",
  4157. UnexpectedReservedType: "Unexpected reserved type %0.",
  4158. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.",
  4159. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  4160. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.",
  4161. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".',
  4162. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.",
  4163. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",
  4164. UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead.",
  4165. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.",
  4166. UnterminatedFlowComment: "Unterminated flow-comment."
  4167. }, ErrorCodes.SyntaxError, "flow");
  4168. function isEsModuleType(bodyElement) {
  4169. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  4170. }
  4171. function hasTypeImportKind(node) {
  4172. return node.importKind === "type" || node.importKind === "typeof";
  4173. }
  4174. function isMaybeDefaultImport(type) {
  4175. return tokenIsKeywordOrIdentifier(type) && type !== 91;
  4176. }
  4177. const exportSuggestions = {
  4178. const: "declare export var",
  4179. let: "declare export var",
  4180. type: "export type",
  4181. interface: "export interface"
  4182. };
  4183. function partition(list, test) {
  4184. const list1 = [];
  4185. const list2 = [];
  4186. for (let i = 0; i < list.length; i++) {
  4187. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  4188. }
  4189. return [list1, list2];
  4190. }
  4191. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  4192. var flow = (superClass => class extends superClass {
  4193. constructor(...args) {
  4194. super(...args);
  4195. this.flowPragma = undefined;
  4196. }
  4197. getScopeHandler() {
  4198. return FlowScopeHandler;
  4199. }
  4200. shouldParseTypes() {
  4201. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  4202. }
  4203. shouldParseEnums() {
  4204. return !!this.getPluginOption("flow", "enums");
  4205. }
  4206. finishToken(type, val) {
  4207. if (type !== 123 && type !== 13 && type !== 26) {
  4208. if (this.flowPragma === undefined) {
  4209. this.flowPragma = null;
  4210. }
  4211. }
  4212. return super.finishToken(type, val);
  4213. }
  4214. addComment(comment) {
  4215. if (this.flowPragma === undefined) {
  4216. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  4217. if (!matches) ; else if (matches[1] === "flow") {
  4218. this.flowPragma = "flow";
  4219. } else if (matches[1] === "noflow") {
  4220. this.flowPragma = "noflow";
  4221. } else {
  4222. throw new Error("Unexpected flow pragma");
  4223. }
  4224. }
  4225. return super.addComment(comment);
  4226. }
  4227. flowParseTypeInitialiser(tok) {
  4228. const oldInType = this.state.inType;
  4229. this.state.inType = true;
  4230. this.expect(tok || 14);
  4231. const type = this.flowParseType();
  4232. this.state.inType = oldInType;
  4233. return type;
  4234. }
  4235. flowParsePredicate() {
  4236. const node = this.startNode();
  4237. const moduloPos = this.state.start;
  4238. this.next();
  4239. this.expectContextual(101);
  4240. if (this.state.lastTokStart > moduloPos + 1) {
  4241. this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
  4242. }
  4243. if (this.eat(10)) {
  4244. node.value = this.parseExpression();
  4245. this.expect(11);
  4246. return this.finishNode(node, "DeclaredPredicate");
  4247. } else {
  4248. return this.finishNode(node, "InferredPredicate");
  4249. }
  4250. }
  4251. flowParseTypeAndPredicateInitialiser() {
  4252. const oldInType = this.state.inType;
  4253. this.state.inType = true;
  4254. this.expect(14);
  4255. let type = null;
  4256. let predicate = null;
  4257. if (this.match(48)) {
  4258. this.state.inType = oldInType;
  4259. predicate = this.flowParsePredicate();
  4260. } else {
  4261. type = this.flowParseType();
  4262. this.state.inType = oldInType;
  4263. if (this.match(48)) {
  4264. predicate = this.flowParsePredicate();
  4265. }
  4266. }
  4267. return [type, predicate];
  4268. }
  4269. flowParseDeclareClass(node) {
  4270. this.next();
  4271. this.flowParseInterfaceish(node, true);
  4272. return this.finishNode(node, "DeclareClass");
  4273. }
  4274. flowParseDeclareFunction(node) {
  4275. this.next();
  4276. const id = node.id = this.parseIdentifier();
  4277. const typeNode = this.startNode();
  4278. const typeContainer = this.startNode();
  4279. if (this.match(43)) {
  4280. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  4281. } else {
  4282. typeNode.typeParameters = null;
  4283. }
  4284. this.expect(10);
  4285. const tmp = this.flowParseFunctionTypeParams();
  4286. typeNode.params = tmp.params;
  4287. typeNode.rest = tmp.rest;
  4288. typeNode.this = tmp._this;
  4289. this.expect(11);
  4290. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  4291. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  4292. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  4293. this.resetEndLocation(id);
  4294. this.semicolon();
  4295. this.scope.declareName(node.id.name, BIND_FLOW_DECLARE_FN, node.id.start);
  4296. return this.finishNode(node, "DeclareFunction");
  4297. }
  4298. flowParseDeclare(node, insideModule) {
  4299. if (this.match(74)) {
  4300. return this.flowParseDeclareClass(node);
  4301. } else if (this.match(62)) {
  4302. return this.flowParseDeclareFunction(node);
  4303. } else if (this.match(68)) {
  4304. return this.flowParseDeclareVariable(node);
  4305. } else if (this.eatContextual(117)) {
  4306. if (this.match(16)) {
  4307. return this.flowParseDeclareModuleExports(node);
  4308. } else {
  4309. if (insideModule) {
  4310. this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
  4311. }
  4312. return this.flowParseDeclareModule(node);
  4313. }
  4314. } else if (this.isContextual(120)) {
  4315. return this.flowParseDeclareTypeAlias(node);
  4316. } else if (this.isContextual(121)) {
  4317. return this.flowParseDeclareOpaqueType(node);
  4318. } else if (this.isContextual(119)) {
  4319. return this.flowParseDeclareInterface(node);
  4320. } else if (this.match(76)) {
  4321. return this.flowParseDeclareExportDeclaration(node, insideModule);
  4322. } else {
  4323. throw this.unexpected();
  4324. }
  4325. }
  4326. flowParseDeclareVariable(node) {
  4327. this.next();
  4328. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  4329. this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
  4330. this.semicolon();
  4331. return this.finishNode(node, "DeclareVariable");
  4332. }
  4333. flowParseDeclareModule(node) {
  4334. this.scope.enter(SCOPE_OTHER);
  4335. if (this.match(123)) {
  4336. node.id = this.parseExprAtom();
  4337. } else {
  4338. node.id = this.parseIdentifier();
  4339. }
  4340. const bodyNode = node.body = this.startNode();
  4341. const body = bodyNode.body = [];
  4342. this.expect(5);
  4343. while (!this.match(8)) {
  4344. let bodyNode = this.startNode();
  4345. if (this.match(77)) {
  4346. this.next();
  4347. if (!this.isContextual(120) && !this.match(81)) {
  4348. this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule);
  4349. }
  4350. this.parseImport(bodyNode);
  4351. } else {
  4352. this.expectContextual(115, FlowErrors.UnsupportedStatementInDeclareModule);
  4353. bodyNode = this.flowParseDeclare(bodyNode, true);
  4354. }
  4355. body.push(bodyNode);
  4356. }
  4357. this.scope.exit();
  4358. this.expect(8);
  4359. this.finishNode(bodyNode, "BlockStatement");
  4360. let kind = null;
  4361. let hasModuleExport = false;
  4362. body.forEach(bodyElement => {
  4363. if (isEsModuleType(bodyElement)) {
  4364. if (kind === "CommonJS") {
  4365. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  4366. }
  4367. kind = "ES";
  4368. } else if (bodyElement.type === "DeclareModuleExports") {
  4369. if (hasModuleExport) {
  4370. this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports);
  4371. }
  4372. if (kind === "ES") {
  4373. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  4374. }
  4375. kind = "CommonJS";
  4376. hasModuleExport = true;
  4377. }
  4378. });
  4379. node.kind = kind || "CommonJS";
  4380. return this.finishNode(node, "DeclareModule");
  4381. }
  4382. flowParseDeclareExportDeclaration(node, insideModule) {
  4383. this.expect(76);
  4384. if (this.eat(59)) {
  4385. if (this.match(62) || this.match(74)) {
  4386. node.declaration = this.flowParseDeclare(this.startNode());
  4387. } else {
  4388. node.declaration = this.flowParseType();
  4389. this.semicolon();
  4390. }
  4391. node.default = true;
  4392. return this.finishNode(node, "DeclareExportDeclaration");
  4393. } else {
  4394. if (this.match(69) || this.isLet() || (this.isContextual(120) || this.isContextual(119)) && !insideModule) {
  4395. const label = this.state.value;
  4396. const suggestion = exportSuggestions[label];
  4397. throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion);
  4398. }
  4399. if (this.match(68) || this.match(62) || this.match(74) || this.isContextual(121)) {
  4400. node.declaration = this.flowParseDeclare(this.startNode());
  4401. node.default = false;
  4402. return this.finishNode(node, "DeclareExportDeclaration");
  4403. } else if (this.match(49) || this.match(5) || this.isContextual(119) || this.isContextual(120) || this.isContextual(121)) {
  4404. node = this.parseExport(node);
  4405. if (node.type === "ExportNamedDeclaration") {
  4406. node.type = "ExportDeclaration";
  4407. node.default = false;
  4408. delete node.exportKind;
  4409. }
  4410. node.type = "Declare" + node.type;
  4411. return node;
  4412. }
  4413. }
  4414. throw this.unexpected();
  4415. }
  4416. flowParseDeclareModuleExports(node) {
  4417. this.next();
  4418. this.expectContextual(102);
  4419. node.typeAnnotation = this.flowParseTypeAnnotation();
  4420. this.semicolon();
  4421. return this.finishNode(node, "DeclareModuleExports");
  4422. }
  4423. flowParseDeclareTypeAlias(node) {
  4424. this.next();
  4425. this.flowParseTypeAlias(node);
  4426. node.type = "DeclareTypeAlias";
  4427. return node;
  4428. }
  4429. flowParseDeclareOpaqueType(node) {
  4430. this.next();
  4431. this.flowParseOpaqueType(node, true);
  4432. node.type = "DeclareOpaqueType";
  4433. return node;
  4434. }
  4435. flowParseDeclareInterface(node) {
  4436. this.next();
  4437. this.flowParseInterfaceish(node);
  4438. return this.finishNode(node, "DeclareInterface");
  4439. }
  4440. flowParseInterfaceish(node, isClass = false) {
  4441. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  4442. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
  4443. if (this.match(43)) {
  4444. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4445. } else {
  4446. node.typeParameters = null;
  4447. }
  4448. node.extends = [];
  4449. node.implements = [];
  4450. node.mixins = [];
  4451. if (this.eat(75)) {
  4452. do {
  4453. node.extends.push(this.flowParseInterfaceExtends());
  4454. } while (!isClass && this.eat(12));
  4455. }
  4456. if (this.isContextual(108)) {
  4457. this.next();
  4458. do {
  4459. node.mixins.push(this.flowParseInterfaceExtends());
  4460. } while (this.eat(12));
  4461. }
  4462. if (this.isContextual(104)) {
  4463. this.next();
  4464. do {
  4465. node.implements.push(this.flowParseInterfaceExtends());
  4466. } while (this.eat(12));
  4467. }
  4468. node.body = this.flowParseObjectType({
  4469. allowStatic: isClass,
  4470. allowExact: false,
  4471. allowSpread: false,
  4472. allowProto: isClass,
  4473. allowInexact: false
  4474. });
  4475. }
  4476. flowParseInterfaceExtends() {
  4477. const node = this.startNode();
  4478. node.id = this.flowParseQualifiedTypeIdentifier();
  4479. if (this.match(43)) {
  4480. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4481. } else {
  4482. node.typeParameters = null;
  4483. }
  4484. return this.finishNode(node, "InterfaceExtends");
  4485. }
  4486. flowParseInterface(node) {
  4487. this.flowParseInterfaceish(node);
  4488. return this.finishNode(node, "InterfaceDeclaration");
  4489. }
  4490. checkNotUnderscore(word) {
  4491. if (word === "_") {
  4492. this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
  4493. }
  4494. }
  4495. checkReservedType(word, startLoc, declaration) {
  4496. if (!reservedTypes.has(word)) return;
  4497. this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word);
  4498. }
  4499. flowParseRestrictedIdentifier(liberal, declaration) {
  4500. this.checkReservedType(this.state.value, this.state.start, declaration);
  4501. return this.parseIdentifier(liberal);
  4502. }
  4503. flowParseTypeAlias(node) {
  4504. node.id = this.flowParseRestrictedIdentifier(false, true);
  4505. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  4506. if (this.match(43)) {
  4507. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4508. } else {
  4509. node.typeParameters = null;
  4510. }
  4511. node.right = this.flowParseTypeInitialiser(27);
  4512. this.semicolon();
  4513. return this.finishNode(node, "TypeAlias");
  4514. }
  4515. flowParseOpaqueType(node, declare) {
  4516. this.expectContextual(120);
  4517. node.id = this.flowParseRestrictedIdentifier(true, true);
  4518. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  4519. if (this.match(43)) {
  4520. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4521. } else {
  4522. node.typeParameters = null;
  4523. }
  4524. node.supertype = null;
  4525. if (this.match(14)) {
  4526. node.supertype = this.flowParseTypeInitialiser(14);
  4527. }
  4528. node.impltype = null;
  4529. if (!declare) {
  4530. node.impltype = this.flowParseTypeInitialiser(27);
  4531. }
  4532. this.semicolon();
  4533. return this.finishNode(node, "OpaqueType");
  4534. }
  4535. flowParseTypeParameter(requireDefault = false) {
  4536. const nodeStart = this.state.start;
  4537. const node = this.startNode();
  4538. const variance = this.flowParseVariance();
  4539. const ident = this.flowParseTypeAnnotatableIdentifier();
  4540. node.name = ident.name;
  4541. node.variance = variance;
  4542. node.bound = ident.typeAnnotation;
  4543. if (this.match(27)) {
  4544. this.eat(27);
  4545. node.default = this.flowParseType();
  4546. } else {
  4547. if (requireDefault) {
  4548. this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
  4549. }
  4550. }
  4551. return this.finishNode(node, "TypeParameter");
  4552. }
  4553. flowParseTypeParameterDeclaration() {
  4554. const oldInType = this.state.inType;
  4555. const node = this.startNode();
  4556. node.params = [];
  4557. this.state.inType = true;
  4558. if (this.match(43) || this.match(132)) {
  4559. this.next();
  4560. } else {
  4561. this.unexpected();
  4562. }
  4563. let defaultRequired = false;
  4564. do {
  4565. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  4566. node.params.push(typeParameter);
  4567. if (typeParameter.default) {
  4568. defaultRequired = true;
  4569. }
  4570. if (!this.match(44)) {
  4571. this.expect(12);
  4572. }
  4573. } while (!this.match(44));
  4574. this.expect(44);
  4575. this.state.inType = oldInType;
  4576. return this.finishNode(node, "TypeParameterDeclaration");
  4577. }
  4578. flowParseTypeParameterInstantiation() {
  4579. const node = this.startNode();
  4580. const oldInType = this.state.inType;
  4581. node.params = [];
  4582. this.state.inType = true;
  4583. this.expect(43);
  4584. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  4585. this.state.noAnonFunctionType = false;
  4586. while (!this.match(44)) {
  4587. node.params.push(this.flowParseType());
  4588. if (!this.match(44)) {
  4589. this.expect(12);
  4590. }
  4591. }
  4592. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4593. this.expect(44);
  4594. this.state.inType = oldInType;
  4595. return this.finishNode(node, "TypeParameterInstantiation");
  4596. }
  4597. flowParseTypeParameterInstantiationCallOrNew() {
  4598. const node = this.startNode();
  4599. const oldInType = this.state.inType;
  4600. node.params = [];
  4601. this.state.inType = true;
  4602. this.expect(43);
  4603. while (!this.match(44)) {
  4604. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  4605. if (!this.match(44)) {
  4606. this.expect(12);
  4607. }
  4608. }
  4609. this.expect(44);
  4610. this.state.inType = oldInType;
  4611. return this.finishNode(node, "TypeParameterInstantiation");
  4612. }
  4613. flowParseInterfaceType() {
  4614. const node = this.startNode();
  4615. this.expectContextual(119);
  4616. node.extends = [];
  4617. if (this.eat(75)) {
  4618. do {
  4619. node.extends.push(this.flowParseInterfaceExtends());
  4620. } while (this.eat(12));
  4621. }
  4622. node.body = this.flowParseObjectType({
  4623. allowStatic: false,
  4624. allowExact: false,
  4625. allowSpread: false,
  4626. allowProto: false,
  4627. allowInexact: false
  4628. });
  4629. return this.finishNode(node, "InterfaceTypeAnnotation");
  4630. }
  4631. flowParseObjectPropertyKey() {
  4632. return this.match(124) || this.match(123) ? this.parseExprAtom() : this.parseIdentifier(true);
  4633. }
  4634. flowParseObjectTypeIndexer(node, isStatic, variance) {
  4635. node.static = isStatic;
  4636. if (this.lookahead().type === 14) {
  4637. node.id = this.flowParseObjectPropertyKey();
  4638. node.key = this.flowParseTypeInitialiser();
  4639. } else {
  4640. node.id = null;
  4641. node.key = this.flowParseType();
  4642. }
  4643. this.expect(3);
  4644. node.value = this.flowParseTypeInitialiser();
  4645. node.variance = variance;
  4646. return this.finishNode(node, "ObjectTypeIndexer");
  4647. }
  4648. flowParseObjectTypeInternalSlot(node, isStatic) {
  4649. node.static = isStatic;
  4650. node.id = this.flowParseObjectPropertyKey();
  4651. this.expect(3);
  4652. this.expect(3);
  4653. if (this.match(43) || this.match(10)) {
  4654. node.method = true;
  4655. node.optional = false;
  4656. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  4657. } else {
  4658. node.method = false;
  4659. if (this.eat(17)) {
  4660. node.optional = true;
  4661. }
  4662. node.value = this.flowParseTypeInitialiser();
  4663. }
  4664. return this.finishNode(node, "ObjectTypeInternalSlot");
  4665. }
  4666. flowParseObjectTypeMethodish(node) {
  4667. node.params = [];
  4668. node.rest = null;
  4669. node.typeParameters = null;
  4670. node.this = null;
  4671. if (this.match(43)) {
  4672. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4673. }
  4674. this.expect(10);
  4675. if (this.match(72)) {
  4676. node.this = this.flowParseFunctionTypeParam(true);
  4677. node.this.name = null;
  4678. if (!this.match(11)) {
  4679. this.expect(12);
  4680. }
  4681. }
  4682. while (!this.match(11) && !this.match(21)) {
  4683. node.params.push(this.flowParseFunctionTypeParam(false));
  4684. if (!this.match(11)) {
  4685. this.expect(12);
  4686. }
  4687. }
  4688. if (this.eat(21)) {
  4689. node.rest = this.flowParseFunctionTypeParam(false);
  4690. }
  4691. this.expect(11);
  4692. node.returnType = this.flowParseTypeInitialiser();
  4693. return this.finishNode(node, "FunctionTypeAnnotation");
  4694. }
  4695. flowParseObjectTypeCallProperty(node, isStatic) {
  4696. const valueNode = this.startNode();
  4697. node.static = isStatic;
  4698. node.value = this.flowParseObjectTypeMethodish(valueNode);
  4699. return this.finishNode(node, "ObjectTypeCallProperty");
  4700. }
  4701. flowParseObjectType({
  4702. allowStatic,
  4703. allowExact,
  4704. allowSpread,
  4705. allowProto,
  4706. allowInexact
  4707. }) {
  4708. const oldInType = this.state.inType;
  4709. this.state.inType = true;
  4710. const nodeStart = this.startNode();
  4711. nodeStart.callProperties = [];
  4712. nodeStart.properties = [];
  4713. nodeStart.indexers = [];
  4714. nodeStart.internalSlots = [];
  4715. let endDelim;
  4716. let exact;
  4717. let inexact = false;
  4718. if (allowExact && this.match(6)) {
  4719. this.expect(6);
  4720. endDelim = 9;
  4721. exact = true;
  4722. } else {
  4723. this.expect(5);
  4724. endDelim = 8;
  4725. exact = false;
  4726. }
  4727. nodeStart.exact = exact;
  4728. while (!this.match(endDelim)) {
  4729. let isStatic = false;
  4730. let protoStart = null;
  4731. let inexactStart = null;
  4732. const node = this.startNode();
  4733. if (allowProto && this.isContextual(109)) {
  4734. const lookahead = this.lookahead();
  4735. if (lookahead.type !== 14 && lookahead.type !== 17) {
  4736. this.next();
  4737. protoStart = this.state.start;
  4738. allowStatic = false;
  4739. }
  4740. }
  4741. if (allowStatic && this.isContextual(98)) {
  4742. const lookahead = this.lookahead();
  4743. if (lookahead.type !== 14 && lookahead.type !== 17) {
  4744. this.next();
  4745. isStatic = true;
  4746. }
  4747. }
  4748. const variance = this.flowParseVariance();
  4749. if (this.eat(0)) {
  4750. if (protoStart != null) {
  4751. this.unexpected(protoStart);
  4752. }
  4753. if (this.eat(0)) {
  4754. if (variance) {
  4755. this.unexpected(variance.start);
  4756. }
  4757. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  4758. } else {
  4759. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  4760. }
  4761. } else if (this.match(10) || this.match(43)) {
  4762. if (protoStart != null) {
  4763. this.unexpected(protoStart);
  4764. }
  4765. if (variance) {
  4766. this.unexpected(variance.start);
  4767. }
  4768. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  4769. } else {
  4770. let kind = "init";
  4771. if (this.isContextual(92) || this.isContextual(97)) {
  4772. const lookahead = this.lookahead();
  4773. if (tokenIsLiteralPropertyName(lookahead.type)) {
  4774. kind = this.state.value;
  4775. this.next();
  4776. }
  4777. }
  4778. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  4779. if (propOrInexact === null) {
  4780. inexact = true;
  4781. inexactStart = this.state.lastTokStart;
  4782. } else {
  4783. nodeStart.properties.push(propOrInexact);
  4784. }
  4785. }
  4786. this.flowObjectTypeSemicolon();
  4787. if (inexactStart && !this.match(8) && !this.match(9)) {
  4788. this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject);
  4789. }
  4790. }
  4791. this.expect(endDelim);
  4792. if (allowSpread) {
  4793. nodeStart.inexact = inexact;
  4794. }
  4795. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  4796. this.state.inType = oldInType;
  4797. return out;
  4798. }
  4799. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  4800. if (this.eat(21)) {
  4801. const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9);
  4802. if (isInexactToken) {
  4803. if (!allowSpread) {
  4804. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject);
  4805. } else if (!allowInexact) {
  4806. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact);
  4807. }
  4808. if (variance) {
  4809. this.raise(variance.start, FlowErrors.InexactVariance);
  4810. }
  4811. return null;
  4812. }
  4813. if (!allowSpread) {
  4814. this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType);
  4815. }
  4816. if (protoStart != null) {
  4817. this.unexpected(protoStart);
  4818. }
  4819. if (variance) {
  4820. this.raise(variance.start, FlowErrors.SpreadVariance);
  4821. }
  4822. node.argument = this.flowParseType();
  4823. return this.finishNode(node, "ObjectTypeSpreadProperty");
  4824. } else {
  4825. node.key = this.flowParseObjectPropertyKey();
  4826. node.static = isStatic;
  4827. node.proto = protoStart != null;
  4828. node.kind = kind;
  4829. let optional = false;
  4830. if (this.match(43) || this.match(10)) {
  4831. node.method = true;
  4832. if (protoStart != null) {
  4833. this.unexpected(protoStart);
  4834. }
  4835. if (variance) {
  4836. this.unexpected(variance.start);
  4837. }
  4838. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  4839. if (kind === "get" || kind === "set") {
  4840. this.flowCheckGetterSetterParams(node);
  4841. }
  4842. if (!allowSpread && node.key.name === "constructor" && node.value.this) {
  4843. this.raise(node.value.this.start, FlowErrors.ThisParamBannedInConstructor);
  4844. }
  4845. } else {
  4846. if (kind !== "init") this.unexpected();
  4847. node.method = false;
  4848. if (this.eat(17)) {
  4849. optional = true;
  4850. }
  4851. node.value = this.flowParseTypeInitialiser();
  4852. node.variance = variance;
  4853. }
  4854. node.optional = optional;
  4855. return this.finishNode(node, "ObjectTypeProperty");
  4856. }
  4857. }
  4858. flowCheckGetterSetterParams(property) {
  4859. const paramCount = property.kind === "get" ? 0 : 1;
  4860. const start = property.start;
  4861. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  4862. if (property.value.this) {
  4863. this.raise(property.value.this.start, property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam);
  4864. }
  4865. if (length !== paramCount) {
  4866. if (property.kind === "get") {
  4867. this.raise(start, ErrorMessages.BadGetterArity);
  4868. } else {
  4869. this.raise(start, ErrorMessages.BadSetterArity);
  4870. }
  4871. }
  4872. if (property.kind === "set" && property.value.rest) {
  4873. this.raise(start, ErrorMessages.BadSetterRestParameter);
  4874. }
  4875. }
  4876. flowObjectTypeSemicolon() {
  4877. if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) {
  4878. this.unexpected();
  4879. }
  4880. }
  4881. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  4882. startPos = startPos || this.state.start;
  4883. startLoc = startLoc || this.state.startLoc;
  4884. let node = id || this.flowParseRestrictedIdentifier(true);
  4885. while (this.eat(16)) {
  4886. const node2 = this.startNodeAt(startPos, startLoc);
  4887. node2.qualification = node;
  4888. node2.id = this.flowParseRestrictedIdentifier(true);
  4889. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  4890. }
  4891. return node;
  4892. }
  4893. flowParseGenericType(startPos, startLoc, id) {
  4894. const node = this.startNodeAt(startPos, startLoc);
  4895. node.typeParameters = null;
  4896. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  4897. if (this.match(43)) {
  4898. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4899. }
  4900. return this.finishNode(node, "GenericTypeAnnotation");
  4901. }
  4902. flowParseTypeofType() {
  4903. const node = this.startNode();
  4904. this.expect(81);
  4905. node.argument = this.flowParsePrimaryType();
  4906. return this.finishNode(node, "TypeofTypeAnnotation");
  4907. }
  4908. flowParseTupleType() {
  4909. const node = this.startNode();
  4910. node.types = [];
  4911. this.expect(0);
  4912. while (this.state.pos < this.length && !this.match(3)) {
  4913. node.types.push(this.flowParseType());
  4914. if (this.match(3)) break;
  4915. this.expect(12);
  4916. }
  4917. this.expect(3);
  4918. return this.finishNode(node, "TupleTypeAnnotation");
  4919. }
  4920. flowParseFunctionTypeParam(first) {
  4921. let name = null;
  4922. let optional = false;
  4923. let typeAnnotation = null;
  4924. const node = this.startNode();
  4925. const lh = this.lookahead();
  4926. const isThis = this.state.type === 72;
  4927. if (lh.type === 14 || lh.type === 17) {
  4928. if (isThis && !first) {
  4929. this.raise(node.start, FlowErrors.ThisParamMustBeFirst);
  4930. }
  4931. name = this.parseIdentifier(isThis);
  4932. if (this.eat(17)) {
  4933. optional = true;
  4934. if (isThis) {
  4935. this.raise(node.start, FlowErrors.ThisParamMayNotBeOptional);
  4936. }
  4937. }
  4938. typeAnnotation = this.flowParseTypeInitialiser();
  4939. } else {
  4940. typeAnnotation = this.flowParseType();
  4941. }
  4942. node.name = name;
  4943. node.optional = optional;
  4944. node.typeAnnotation = typeAnnotation;
  4945. return this.finishNode(node, "FunctionTypeParam");
  4946. }
  4947. reinterpretTypeAsFunctionTypeParam(type) {
  4948. const node = this.startNodeAt(type.start, type.loc.start);
  4949. node.name = null;
  4950. node.optional = false;
  4951. node.typeAnnotation = type;
  4952. return this.finishNode(node, "FunctionTypeParam");
  4953. }
  4954. flowParseFunctionTypeParams(params = []) {
  4955. let rest = null;
  4956. let _this = null;
  4957. if (this.match(72)) {
  4958. _this = this.flowParseFunctionTypeParam(true);
  4959. _this.name = null;
  4960. if (!this.match(11)) {
  4961. this.expect(12);
  4962. }
  4963. }
  4964. while (!this.match(11) && !this.match(21)) {
  4965. params.push(this.flowParseFunctionTypeParam(false));
  4966. if (!this.match(11)) {
  4967. this.expect(12);
  4968. }
  4969. }
  4970. if (this.eat(21)) {
  4971. rest = this.flowParseFunctionTypeParam(false);
  4972. }
  4973. return {
  4974. params,
  4975. rest,
  4976. _this
  4977. };
  4978. }
  4979. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  4980. switch (id.name) {
  4981. case "any":
  4982. return this.finishNode(node, "AnyTypeAnnotation");
  4983. case "bool":
  4984. case "boolean":
  4985. return this.finishNode(node, "BooleanTypeAnnotation");
  4986. case "mixed":
  4987. return this.finishNode(node, "MixedTypeAnnotation");
  4988. case "empty":
  4989. return this.finishNode(node, "EmptyTypeAnnotation");
  4990. case "number":
  4991. return this.finishNode(node, "NumberTypeAnnotation");
  4992. case "string":
  4993. return this.finishNode(node, "StringTypeAnnotation");
  4994. case "symbol":
  4995. return this.finishNode(node, "SymbolTypeAnnotation");
  4996. default:
  4997. this.checkNotUnderscore(id.name);
  4998. return this.flowParseGenericType(startPos, startLoc, id);
  4999. }
  5000. }
  5001. flowParsePrimaryType() {
  5002. const startPos = this.state.start;
  5003. const startLoc = this.state.startLoc;
  5004. const node = this.startNode();
  5005. let tmp;
  5006. let type;
  5007. let isGroupedType = false;
  5008. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5009. switch (this.state.type) {
  5010. case 5:
  5011. return this.flowParseObjectType({
  5012. allowStatic: false,
  5013. allowExact: false,
  5014. allowSpread: true,
  5015. allowProto: false,
  5016. allowInexact: true
  5017. });
  5018. case 6:
  5019. return this.flowParseObjectType({
  5020. allowStatic: false,
  5021. allowExact: true,
  5022. allowSpread: true,
  5023. allowProto: false,
  5024. allowInexact: false
  5025. });
  5026. case 0:
  5027. this.state.noAnonFunctionType = false;
  5028. type = this.flowParseTupleType();
  5029. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5030. return type;
  5031. case 43:
  5032. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5033. this.expect(10);
  5034. tmp = this.flowParseFunctionTypeParams();
  5035. node.params = tmp.params;
  5036. node.rest = tmp.rest;
  5037. node.this = tmp._this;
  5038. this.expect(11);
  5039. this.expect(19);
  5040. node.returnType = this.flowParseType();
  5041. return this.finishNode(node, "FunctionTypeAnnotation");
  5042. case 10:
  5043. this.next();
  5044. if (!this.match(11) && !this.match(21)) {
  5045. if (tokenIsIdentifier(this.state.type) || this.match(72)) {
  5046. const token = this.lookahead().type;
  5047. isGroupedType = token !== 17 && token !== 14;
  5048. } else {
  5049. isGroupedType = true;
  5050. }
  5051. }
  5052. if (isGroupedType) {
  5053. this.state.noAnonFunctionType = false;
  5054. type = this.flowParseType();
  5055. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5056. if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) {
  5057. this.expect(11);
  5058. return type;
  5059. } else {
  5060. this.eat(12);
  5061. }
  5062. }
  5063. if (type) {
  5064. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  5065. } else {
  5066. tmp = this.flowParseFunctionTypeParams();
  5067. }
  5068. node.params = tmp.params;
  5069. node.rest = tmp.rest;
  5070. node.this = tmp._this;
  5071. this.expect(11);
  5072. this.expect(19);
  5073. node.returnType = this.flowParseType();
  5074. node.typeParameters = null;
  5075. return this.finishNode(node, "FunctionTypeAnnotation");
  5076. case 123:
  5077. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  5078. case 79:
  5079. case 80:
  5080. node.value = this.match(79);
  5081. this.next();
  5082. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  5083. case 47:
  5084. if (this.state.value === "-") {
  5085. this.next();
  5086. if (this.match(124)) {
  5087. return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node);
  5088. }
  5089. if (this.match(125)) {
  5090. return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node);
  5091. }
  5092. throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
  5093. }
  5094. throw this.unexpected();
  5095. case 124:
  5096. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  5097. case 125:
  5098. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  5099. case 82:
  5100. this.next();
  5101. return this.finishNode(node, "VoidTypeAnnotation");
  5102. case 78:
  5103. this.next();
  5104. return this.finishNode(node, "NullLiteralTypeAnnotation");
  5105. case 72:
  5106. this.next();
  5107. return this.finishNode(node, "ThisTypeAnnotation");
  5108. case 49:
  5109. this.next();
  5110. return this.finishNode(node, "ExistsTypeAnnotation");
  5111. case 81:
  5112. return this.flowParseTypeofType();
  5113. default:
  5114. if (tokenIsKeyword(this.state.type)) {
  5115. const label = tokenLabelName(this.state.type);
  5116. this.next();
  5117. return super.createIdentifier(node, label);
  5118. } else if (tokenIsIdentifier(this.state.type)) {
  5119. if (this.isContextual(119)) {
  5120. return this.flowParseInterfaceType();
  5121. }
  5122. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  5123. }
  5124. }
  5125. throw this.unexpected();
  5126. }
  5127. flowParsePostfixType() {
  5128. const startPos = this.state.start;
  5129. const startLoc = this.state.startLoc;
  5130. let type = this.flowParsePrimaryType();
  5131. let seenOptionalIndexedAccess = false;
  5132. while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) {
  5133. const node = this.startNodeAt(startPos, startLoc);
  5134. const optional = this.eat(18);
  5135. seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional;
  5136. this.expect(0);
  5137. if (!optional && this.match(3)) {
  5138. node.elementType = type;
  5139. this.next();
  5140. type = this.finishNode(node, "ArrayTypeAnnotation");
  5141. } else {
  5142. node.objectType = type;
  5143. node.indexType = this.flowParseType();
  5144. this.expect(3);
  5145. if (seenOptionalIndexedAccess) {
  5146. node.optional = optional;
  5147. type = this.finishNode(node, "OptionalIndexedAccessType");
  5148. } else {
  5149. type = this.finishNode(node, "IndexedAccessType");
  5150. }
  5151. }
  5152. }
  5153. return type;
  5154. }
  5155. flowParsePrefixType() {
  5156. const node = this.startNode();
  5157. if (this.eat(17)) {
  5158. node.typeAnnotation = this.flowParsePrefixType();
  5159. return this.finishNode(node, "NullableTypeAnnotation");
  5160. } else {
  5161. return this.flowParsePostfixType();
  5162. }
  5163. }
  5164. flowParseAnonFunctionWithoutParens() {
  5165. const param = this.flowParsePrefixType();
  5166. if (!this.state.noAnonFunctionType && this.eat(19)) {
  5167. const node = this.startNodeAt(param.start, param.loc.start);
  5168. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  5169. node.rest = null;
  5170. node.this = null;
  5171. node.returnType = this.flowParseType();
  5172. node.typeParameters = null;
  5173. return this.finishNode(node, "FunctionTypeAnnotation");
  5174. }
  5175. return param;
  5176. }
  5177. flowParseIntersectionType() {
  5178. const node = this.startNode();
  5179. this.eat(41);
  5180. const type = this.flowParseAnonFunctionWithoutParens();
  5181. node.types = [type];
  5182. while (this.eat(41)) {
  5183. node.types.push(this.flowParseAnonFunctionWithoutParens());
  5184. }
  5185. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  5186. }
  5187. flowParseUnionType() {
  5188. const node = this.startNode();
  5189. this.eat(39);
  5190. const type = this.flowParseIntersectionType();
  5191. node.types = [type];
  5192. while (this.eat(39)) {
  5193. node.types.push(this.flowParseIntersectionType());
  5194. }
  5195. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  5196. }
  5197. flowParseType() {
  5198. const oldInType = this.state.inType;
  5199. this.state.inType = true;
  5200. const type = this.flowParseUnionType();
  5201. this.state.inType = oldInType;
  5202. return type;
  5203. }
  5204. flowParseTypeOrImplicitInstantiation() {
  5205. if (this.state.type === 122 && this.state.value === "_") {
  5206. const startPos = this.state.start;
  5207. const startLoc = this.state.startLoc;
  5208. const node = this.parseIdentifier();
  5209. return this.flowParseGenericType(startPos, startLoc, node);
  5210. } else {
  5211. return this.flowParseType();
  5212. }
  5213. }
  5214. flowParseTypeAnnotation() {
  5215. const node = this.startNode();
  5216. node.typeAnnotation = this.flowParseTypeInitialiser();
  5217. return this.finishNode(node, "TypeAnnotation");
  5218. }
  5219. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  5220. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  5221. if (this.match(14)) {
  5222. ident.typeAnnotation = this.flowParseTypeAnnotation();
  5223. this.resetEndLocation(ident);
  5224. }
  5225. return ident;
  5226. }
  5227. typeCastToParameter(node) {
  5228. node.expression.typeAnnotation = node.typeAnnotation;
  5229. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  5230. return node.expression;
  5231. }
  5232. flowParseVariance() {
  5233. let variance = null;
  5234. if (this.match(47)) {
  5235. variance = this.startNode();
  5236. if (this.state.value === "+") {
  5237. variance.kind = "plus";
  5238. } else {
  5239. variance.kind = "minus";
  5240. }
  5241. this.next();
  5242. this.finishNode(variance, "Variance");
  5243. }
  5244. return variance;
  5245. }
  5246. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  5247. if (allowExpressionBody) {
  5248. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  5249. }
  5250. return super.parseFunctionBody(node, false, isMethod);
  5251. }
  5252. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  5253. if (this.match(14)) {
  5254. const typeNode = this.startNode();
  5255. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  5256. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  5257. }
  5258. super.parseFunctionBodyAndFinish(node, type, isMethod);
  5259. }
  5260. parseStatement(context, topLevel) {
  5261. if (this.state.strict && this.isContextual(119)) {
  5262. const lookahead = this.lookahead();
  5263. if (tokenIsKeywordOrIdentifier(lookahead.type)) {
  5264. const node = this.startNode();
  5265. this.next();
  5266. return this.flowParseInterface(node);
  5267. }
  5268. } else if (this.shouldParseEnums() && this.isContextual(116)) {
  5269. const node = this.startNode();
  5270. this.next();
  5271. return this.flowParseEnumDeclaration(node);
  5272. }
  5273. const stmt = super.parseStatement(context, topLevel);
  5274. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  5275. this.flowPragma = null;
  5276. }
  5277. return stmt;
  5278. }
  5279. parseExpressionStatement(node, expr) {
  5280. if (expr.type === "Identifier") {
  5281. if (expr.name === "declare") {
  5282. if (this.match(74) || tokenIsIdentifier(this.state.type) || this.match(62) || this.match(68) || this.match(76)) {
  5283. return this.flowParseDeclare(node);
  5284. }
  5285. } else if (tokenIsIdentifier(this.state.type)) {
  5286. if (expr.name === "interface") {
  5287. return this.flowParseInterface(node);
  5288. } else if (expr.name === "type") {
  5289. return this.flowParseTypeAlias(node);
  5290. } else if (expr.name === "opaque") {
  5291. return this.flowParseOpaqueType(node, false);
  5292. }
  5293. }
  5294. }
  5295. return super.parseExpressionStatement(node, expr);
  5296. }
  5297. shouldParseExportDeclaration() {
  5298. const {
  5299. type
  5300. } = this.state;
  5301. if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 116) {
  5302. return !this.state.containsEsc;
  5303. }
  5304. return super.shouldParseExportDeclaration();
  5305. }
  5306. isExportDefaultSpecifier() {
  5307. const {
  5308. type
  5309. } = this.state;
  5310. if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 116) {
  5311. return this.state.containsEsc;
  5312. }
  5313. return super.isExportDefaultSpecifier();
  5314. }
  5315. parseExportDefaultExpression() {
  5316. if (this.shouldParseEnums() && this.isContextual(116)) {
  5317. const node = this.startNode();
  5318. this.next();
  5319. return this.flowParseEnumDeclaration(node);
  5320. }
  5321. return super.parseExportDefaultExpression();
  5322. }
  5323. parseConditional(expr, startPos, startLoc, refExpressionErrors) {
  5324. if (!this.match(17)) return expr;
  5325. if (this.state.maybeInArrowParameters) {
  5326. const nextCh = this.lookaheadCharCode();
  5327. if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) {
  5328. this.setOptionalParametersError(refExpressionErrors);
  5329. return expr;
  5330. }
  5331. }
  5332. this.expect(17);
  5333. const state = this.state.clone();
  5334. const originalNoArrowAt = this.state.noArrowAt;
  5335. const node = this.startNodeAt(startPos, startLoc);
  5336. let {
  5337. consequent,
  5338. failed
  5339. } = this.tryParseConditionalConsequent();
  5340. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  5341. if (failed || invalid.length > 0) {
  5342. const noArrowAt = [...originalNoArrowAt];
  5343. if (invalid.length > 0) {
  5344. this.state = state;
  5345. this.state.noArrowAt = noArrowAt;
  5346. for (let i = 0; i < invalid.length; i++) {
  5347. noArrowAt.push(invalid[i].start);
  5348. }
  5349. ({
  5350. consequent,
  5351. failed
  5352. } = this.tryParseConditionalConsequent());
  5353. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  5354. }
  5355. if (failed && valid.length > 1) {
  5356. this.raise(state.start, FlowErrors.AmbiguousConditionalArrow);
  5357. }
  5358. if (failed && valid.length === 1) {
  5359. this.state = state;
  5360. noArrowAt.push(valid[0].start);
  5361. this.state.noArrowAt = noArrowAt;
  5362. ({
  5363. consequent,
  5364. failed
  5365. } = this.tryParseConditionalConsequent());
  5366. }
  5367. }
  5368. this.getArrowLikeExpressions(consequent, true);
  5369. this.state.noArrowAt = originalNoArrowAt;
  5370. this.expect(14);
  5371. node.test = expr;
  5372. node.consequent = consequent;
  5373. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined));
  5374. return this.finishNode(node, "ConditionalExpression");
  5375. }
  5376. tryParseConditionalConsequent() {
  5377. this.state.noArrowParamsConversionAt.push(this.state.start);
  5378. const consequent = this.parseMaybeAssignAllowIn();
  5379. const failed = !this.match(14);
  5380. this.state.noArrowParamsConversionAt.pop();
  5381. return {
  5382. consequent,
  5383. failed
  5384. };
  5385. }
  5386. getArrowLikeExpressions(node, disallowInvalid) {
  5387. const stack = [node];
  5388. const arrows = [];
  5389. while (stack.length !== 0) {
  5390. const node = stack.pop();
  5391. if (node.type === "ArrowFunctionExpression") {
  5392. if (node.typeParameters || !node.returnType) {
  5393. this.finishArrowValidation(node);
  5394. } else {
  5395. arrows.push(node);
  5396. }
  5397. stack.push(node.body);
  5398. } else if (node.type === "ConditionalExpression") {
  5399. stack.push(node.consequent);
  5400. stack.push(node.alternate);
  5401. }
  5402. }
  5403. if (disallowInvalid) {
  5404. arrows.forEach(node => this.finishArrowValidation(node));
  5405. return [arrows, []];
  5406. }
  5407. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  5408. }
  5409. finishArrowValidation(node) {
  5410. var _node$extra;
  5411. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma, false);
  5412. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  5413. super.checkParams(node, false, true);
  5414. this.scope.exit();
  5415. }
  5416. forwardNoArrowParamsConversionAt(node, parse) {
  5417. let result;
  5418. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  5419. this.state.noArrowParamsConversionAt.push(this.state.start);
  5420. result = parse();
  5421. this.state.noArrowParamsConversionAt.pop();
  5422. } else {
  5423. result = parse();
  5424. }
  5425. return result;
  5426. }
  5427. parseParenItem(node, startPos, startLoc) {
  5428. node = super.parseParenItem(node, startPos, startLoc);
  5429. if (this.eat(17)) {
  5430. node.optional = true;
  5431. this.resetEndLocation(node);
  5432. }
  5433. if (this.match(14)) {
  5434. const typeCastNode = this.startNodeAt(startPos, startLoc);
  5435. typeCastNode.expression = node;
  5436. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  5437. return this.finishNode(typeCastNode, "TypeCastExpression");
  5438. }
  5439. return node;
  5440. }
  5441. assertModuleNodeAllowed(node) {
  5442. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  5443. return;
  5444. }
  5445. super.assertModuleNodeAllowed(node);
  5446. }
  5447. parseExport(node) {
  5448. const decl = super.parseExport(node);
  5449. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  5450. decl.exportKind = decl.exportKind || "value";
  5451. }
  5452. return decl;
  5453. }
  5454. parseExportDeclaration(node) {
  5455. if (this.isContextual(120)) {
  5456. node.exportKind = "type";
  5457. const declarationNode = this.startNode();
  5458. this.next();
  5459. if (this.match(5)) {
  5460. node.specifiers = this.parseExportSpecifiers(true);
  5461. this.parseExportFrom(node);
  5462. return null;
  5463. } else {
  5464. return this.flowParseTypeAlias(declarationNode);
  5465. }
  5466. } else if (this.isContextual(121)) {
  5467. node.exportKind = "type";
  5468. const declarationNode = this.startNode();
  5469. this.next();
  5470. return this.flowParseOpaqueType(declarationNode, false);
  5471. } else if (this.isContextual(119)) {
  5472. node.exportKind = "type";
  5473. const declarationNode = this.startNode();
  5474. this.next();
  5475. return this.flowParseInterface(declarationNode);
  5476. } else if (this.shouldParseEnums() && this.isContextual(116)) {
  5477. node.exportKind = "value";
  5478. const declarationNode = this.startNode();
  5479. this.next();
  5480. return this.flowParseEnumDeclaration(declarationNode);
  5481. } else {
  5482. return super.parseExportDeclaration(node);
  5483. }
  5484. }
  5485. eatExportStar(node) {
  5486. if (super.eatExportStar(...arguments)) return true;
  5487. if (this.isContextual(120) && this.lookahead().type === 49) {
  5488. node.exportKind = "type";
  5489. this.next();
  5490. this.next();
  5491. return true;
  5492. }
  5493. return false;
  5494. }
  5495. maybeParseExportNamespaceSpecifier(node) {
  5496. const pos = this.state.start;
  5497. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  5498. if (hasNamespace && node.exportKind === "type") {
  5499. this.unexpected(pos);
  5500. }
  5501. return hasNamespace;
  5502. }
  5503. parseClassId(node, isStatement, optionalId) {
  5504. super.parseClassId(node, isStatement, optionalId);
  5505. if (this.match(43)) {
  5506. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5507. }
  5508. }
  5509. parseClassMember(classBody, member, state) {
  5510. const pos = this.state.start;
  5511. if (this.isContextual(115)) {
  5512. if (this.parseClassMemberFromModifier(classBody, member)) {
  5513. return;
  5514. }
  5515. member.declare = true;
  5516. }
  5517. super.parseClassMember(classBody, member, state);
  5518. if (member.declare) {
  5519. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") {
  5520. this.raise(pos, FlowErrors.DeclareClassElement);
  5521. } else if (member.value) {
  5522. this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
  5523. }
  5524. }
  5525. }
  5526. isIterator(word) {
  5527. return word === "iterator" || word === "asyncIterator";
  5528. }
  5529. readIterator() {
  5530. const word = super.readWord1();
  5531. const fullWord = "@@" + word;
  5532. if (!this.isIterator(word) || !this.state.inType) {
  5533. this.raise(this.state.pos, ErrorMessages.InvalidIdentifier, fullWord);
  5534. }
  5535. this.finishToken(122, fullWord);
  5536. }
  5537. getTokenFromCode(code) {
  5538. const next = this.input.charCodeAt(this.state.pos + 1);
  5539. if (code === 123 && next === 124) {
  5540. return this.finishOp(6, 2);
  5541. } else if (this.state.inType && (code === 62 || code === 60)) {
  5542. return this.finishOp(code === 62 ? 44 : 43, 1);
  5543. } else if (this.state.inType && code === 63) {
  5544. if (next === 46) {
  5545. return this.finishOp(18, 2);
  5546. }
  5547. return this.finishOp(17, 1);
  5548. } else if (isIteratorStart(code, next)) {
  5549. this.state.pos += 2;
  5550. return this.readIterator();
  5551. } else {
  5552. return super.getTokenFromCode(code);
  5553. }
  5554. }
  5555. isAssignable(node, isBinding) {
  5556. if (node.type === "TypeCastExpression") {
  5557. return this.isAssignable(node.expression, isBinding);
  5558. } else {
  5559. return super.isAssignable(node, isBinding);
  5560. }
  5561. }
  5562. toAssignable(node, isLHS = false) {
  5563. if (node.type === "TypeCastExpression") {
  5564. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  5565. } else {
  5566. return super.toAssignable(node, isLHS);
  5567. }
  5568. }
  5569. toAssignableList(exprList, trailingCommaPos, isLHS) {
  5570. for (let i = 0; i < exprList.length; i++) {
  5571. const expr = exprList[i];
  5572. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  5573. exprList[i] = this.typeCastToParameter(expr);
  5574. }
  5575. }
  5576. return super.toAssignableList(exprList, trailingCommaPos, isLHS);
  5577. }
  5578. toReferencedList(exprList, isParenthesizedExpr) {
  5579. for (let i = 0; i < exprList.length; i++) {
  5580. var _expr$extra;
  5581. const expr = exprList[i];
  5582. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  5583. this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
  5584. }
  5585. }
  5586. return exprList;
  5587. }
  5588. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  5589. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  5590. if (canBePattern && !this.state.maybeInArrowParameters) {
  5591. this.toReferencedList(node.elements);
  5592. }
  5593. return node;
  5594. }
  5595. checkLVal(expr, ...args) {
  5596. if (expr.type !== "TypeCastExpression") {
  5597. return super.checkLVal(expr, ...args);
  5598. }
  5599. }
  5600. parseClassProperty(node) {
  5601. if (this.match(14)) {
  5602. node.typeAnnotation = this.flowParseTypeAnnotation();
  5603. }
  5604. return super.parseClassProperty(node);
  5605. }
  5606. parseClassPrivateProperty(node) {
  5607. if (this.match(14)) {
  5608. node.typeAnnotation = this.flowParseTypeAnnotation();
  5609. }
  5610. return super.parseClassPrivateProperty(node);
  5611. }
  5612. isClassMethod() {
  5613. return this.match(43) || super.isClassMethod();
  5614. }
  5615. isClassProperty() {
  5616. return this.match(14) || super.isClassProperty();
  5617. }
  5618. isNonstaticConstructor(method) {
  5619. return !this.match(14) && super.isNonstaticConstructor(method);
  5620. }
  5621. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  5622. if (method.variance) {
  5623. this.unexpected(method.variance.start);
  5624. }
  5625. delete method.variance;
  5626. if (this.match(43)) {
  5627. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5628. }
  5629. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  5630. if (method.params && isConstructor) {
  5631. const params = method.params;
  5632. if (params.length > 0 && this.isThisParam(params[0])) {
  5633. this.raise(method.start, FlowErrors.ThisParamBannedInConstructor);
  5634. }
  5635. } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) {
  5636. const params = method.value.params;
  5637. if (params.length > 0 && this.isThisParam(params[0])) {
  5638. this.raise(method.start, FlowErrors.ThisParamBannedInConstructor);
  5639. }
  5640. }
  5641. }
  5642. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  5643. if (method.variance) {
  5644. this.unexpected(method.variance.start);
  5645. }
  5646. delete method.variance;
  5647. if (this.match(43)) {
  5648. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5649. }
  5650. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  5651. }
  5652. parseClassSuper(node) {
  5653. super.parseClassSuper(node);
  5654. if (node.superClass && this.match(43)) {
  5655. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  5656. }
  5657. if (this.isContextual(104)) {
  5658. this.next();
  5659. const implemented = node.implements = [];
  5660. do {
  5661. const node = this.startNode();
  5662. node.id = this.flowParseRestrictedIdentifier(true);
  5663. if (this.match(43)) {
  5664. node.typeParameters = this.flowParseTypeParameterInstantiation();
  5665. } else {
  5666. node.typeParameters = null;
  5667. }
  5668. implemented.push(this.finishNode(node, "ClassImplements"));
  5669. } while (this.eat(12));
  5670. }
  5671. }
  5672. checkGetterSetterParams(method) {
  5673. super.checkGetterSetterParams(method);
  5674. const params = this.getObjectOrClassMethodParams(method);
  5675. if (params.length > 0) {
  5676. const param = params[0];
  5677. if (this.isThisParam(param) && method.kind === "get") {
  5678. this.raise(param.start, FlowErrors.GetterMayNotHaveThisParam);
  5679. } else if (this.isThisParam(param)) {
  5680. this.raise(param.start, FlowErrors.SetterMayNotHaveThisParam);
  5681. }
  5682. }
  5683. }
  5684. parsePropertyNamePrefixOperator(node) {
  5685. node.variance = this.flowParseVariance();
  5686. }
  5687. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  5688. if (prop.variance) {
  5689. this.unexpected(prop.variance.start);
  5690. }
  5691. delete prop.variance;
  5692. let typeParameters;
  5693. if (this.match(43) && !isAccessor) {
  5694. typeParameters = this.flowParseTypeParameterDeclaration();
  5695. if (!this.match(10)) this.unexpected();
  5696. }
  5697. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  5698. if (typeParameters) {
  5699. (prop.value || prop).typeParameters = typeParameters;
  5700. }
  5701. }
  5702. parseAssignableListItemTypes(param) {
  5703. if (this.eat(17)) {
  5704. if (param.type !== "Identifier") {
  5705. this.raise(param.start, FlowErrors.PatternIsOptional);
  5706. }
  5707. if (this.isThisParam(param)) {
  5708. this.raise(param.start, FlowErrors.ThisParamMayNotBeOptional);
  5709. }
  5710. param.optional = true;
  5711. }
  5712. if (this.match(14)) {
  5713. param.typeAnnotation = this.flowParseTypeAnnotation();
  5714. } else if (this.isThisParam(param)) {
  5715. this.raise(param.start, FlowErrors.ThisParamAnnotationRequired);
  5716. }
  5717. if (this.match(27) && this.isThisParam(param)) {
  5718. this.raise(param.start, FlowErrors.ThisParamNoDefault);
  5719. }
  5720. this.resetEndLocation(param);
  5721. return param;
  5722. }
  5723. parseMaybeDefault(startPos, startLoc, left) {
  5724. const node = super.parseMaybeDefault(startPos, startLoc, left);
  5725. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5726. this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer);
  5727. }
  5728. return node;
  5729. }
  5730. shouldParseDefaultImport(node) {
  5731. if (!hasTypeImportKind(node)) {
  5732. return super.shouldParseDefaultImport(node);
  5733. }
  5734. return isMaybeDefaultImport(this.state.type);
  5735. }
  5736. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  5737. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  5738. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  5739. node.specifiers.push(this.finishNode(specifier, type));
  5740. }
  5741. maybeParseDefaultImportSpecifier(node) {
  5742. node.importKind = "value";
  5743. let kind = null;
  5744. if (this.match(81)) {
  5745. kind = "typeof";
  5746. } else if (this.isContextual(120)) {
  5747. kind = "type";
  5748. }
  5749. if (kind) {
  5750. const lh = this.lookahead();
  5751. const {
  5752. type
  5753. } = lh;
  5754. if (kind === "type" && type === 49) {
  5755. this.unexpected(lh.start);
  5756. }
  5757. if (isMaybeDefaultImport(type) || type === 5 || type === 49) {
  5758. this.next();
  5759. node.importKind = kind;
  5760. }
  5761. }
  5762. return super.maybeParseDefaultImportSpecifier(node);
  5763. }
  5764. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly) {
  5765. const firstIdent = specifier.imported;
  5766. let specifierTypeKind = null;
  5767. if (firstIdent.type === "Identifier") {
  5768. if (firstIdent.name === "type") {
  5769. specifierTypeKind = "type";
  5770. } else if (firstIdent.name === "typeof") {
  5771. specifierTypeKind = "typeof";
  5772. }
  5773. }
  5774. let isBinding = false;
  5775. if (this.isContextual(87) && !this.isLookaheadContextual("as")) {
  5776. const as_ident = this.parseIdentifier(true);
  5777. if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) {
  5778. specifier.imported = as_ident;
  5779. specifier.importKind = specifierTypeKind;
  5780. specifier.local = cloneIdentifier(as_ident);
  5781. } else {
  5782. specifier.imported = firstIdent;
  5783. specifier.importKind = null;
  5784. specifier.local = this.parseIdentifier();
  5785. }
  5786. } else {
  5787. if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) {
  5788. specifier.imported = this.parseIdentifier(true);
  5789. specifier.importKind = specifierTypeKind;
  5790. } else {
  5791. if (importedIsString) {
  5792. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, firstIdent.value);
  5793. }
  5794. specifier.imported = firstIdent;
  5795. specifier.importKind = null;
  5796. }
  5797. if (this.eatContextual(87)) {
  5798. specifier.local = this.parseIdentifier();
  5799. } else {
  5800. isBinding = true;
  5801. specifier.local = cloneIdentifier(specifier.imported);
  5802. }
  5803. }
  5804. const specifierIsTypeImport = hasTypeImportKind(specifier);
  5805. if (isInTypeOnlyImport && specifierIsTypeImport) {
  5806. this.raise(specifier.start, FlowErrors.ImportTypeShorthandOnlyInPureImport);
  5807. }
  5808. if (isInTypeOnlyImport || specifierIsTypeImport) {
  5809. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  5810. }
  5811. if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) {
  5812. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  5813. }
  5814. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  5815. return this.finishNode(specifier, "ImportSpecifier");
  5816. }
  5817. parseBindingAtom() {
  5818. switch (this.state.type) {
  5819. case 72:
  5820. return this.parseIdentifier(true);
  5821. default:
  5822. return super.parseBindingAtom();
  5823. }
  5824. }
  5825. parseFunctionParams(node, allowModifiers) {
  5826. const kind = node.kind;
  5827. if (kind !== "get" && kind !== "set" && this.match(43)) {
  5828. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5829. }
  5830. super.parseFunctionParams(node, allowModifiers);
  5831. }
  5832. parseVarId(decl, kind) {
  5833. super.parseVarId(decl, kind);
  5834. if (this.match(14)) {
  5835. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  5836. this.resetEndLocation(decl.id);
  5837. }
  5838. }
  5839. parseAsyncArrowFromCallExpression(node, call) {
  5840. if (this.match(14)) {
  5841. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5842. this.state.noAnonFunctionType = true;
  5843. node.returnType = this.flowParseTypeAnnotation();
  5844. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5845. }
  5846. return super.parseAsyncArrowFromCallExpression(node, call);
  5847. }
  5848. shouldParseAsyncArrow() {
  5849. return this.match(14) || super.shouldParseAsyncArrow();
  5850. }
  5851. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  5852. var _jsx;
  5853. let state = null;
  5854. let jsx;
  5855. if (this.hasPlugin("jsx") && (this.match(132) || this.match(43))) {
  5856. state = this.state.clone();
  5857. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  5858. if (!jsx.error) return jsx.node;
  5859. const {
  5860. context
  5861. } = this.state;
  5862. const curContext = context[context.length - 1];
  5863. if (curContext === types$1.j_oTag) {
  5864. context.length -= 2;
  5865. } else if (curContext === types$1.j_expr) {
  5866. context.length -= 1;
  5867. }
  5868. }
  5869. if ((_jsx = jsx) != null && _jsx.error || this.match(43)) {
  5870. var _jsx2, _jsx3;
  5871. state = state || this.state.clone();
  5872. let typeParameters;
  5873. const arrow = this.tryParse(abort => {
  5874. var _arrowExpression$extr;
  5875. typeParameters = this.flowParseTypeParameterDeclaration();
  5876. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  5877. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  5878. this.resetStartLocationFromNode(result, typeParameters);
  5879. return result;
  5880. });
  5881. if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort();
  5882. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  5883. if (expr.type !== "ArrowFunctionExpression") abort();
  5884. expr.typeParameters = typeParameters;
  5885. this.resetStartLocationFromNode(expr, typeParameters);
  5886. return arrowExpression;
  5887. }, state);
  5888. let arrowExpression = null;
  5889. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  5890. if (!arrow.error && !arrow.aborted) {
  5891. if (arrow.node.async) {
  5892. this.raise(typeParameters.start, FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction);
  5893. }
  5894. return arrow.node;
  5895. }
  5896. arrowExpression = arrow.node;
  5897. }
  5898. if ((_jsx2 = jsx) != null && _jsx2.node) {
  5899. this.state = jsx.failState;
  5900. return jsx.node;
  5901. }
  5902. if (arrowExpression) {
  5903. this.state = arrow.failState;
  5904. return arrowExpression;
  5905. }
  5906. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  5907. if (arrow.thrown) throw arrow.error;
  5908. throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
  5909. }
  5910. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  5911. }
  5912. parseArrow(node) {
  5913. if (this.match(14)) {
  5914. const result = this.tryParse(() => {
  5915. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5916. this.state.noAnonFunctionType = true;
  5917. const typeNode = this.startNode();
  5918. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  5919. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5920. if (this.canInsertSemicolon()) this.unexpected();
  5921. if (!this.match(19)) this.unexpected();
  5922. return typeNode;
  5923. });
  5924. if (result.thrown) return null;
  5925. if (result.error) this.state = result.failState;
  5926. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  5927. }
  5928. return super.parseArrow(node);
  5929. }
  5930. shouldParseArrow(params) {
  5931. return this.match(14) || super.shouldParseArrow(params);
  5932. }
  5933. setArrowFunctionParameters(node, params) {
  5934. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  5935. node.params = params;
  5936. } else {
  5937. super.setArrowFunctionParameters(node, params);
  5938. }
  5939. }
  5940. checkParams(node, allowDuplicates, isArrowFunction) {
  5941. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  5942. return;
  5943. }
  5944. for (let i = 0; i < node.params.length; i++) {
  5945. if (this.isThisParam(node.params[i]) && i > 0) {
  5946. this.raise(node.params[i].start, FlowErrors.ThisParamMustBeFirst);
  5947. }
  5948. }
  5949. return super.checkParams(...arguments);
  5950. }
  5951. parseParenAndDistinguishExpression(canBeArrow) {
  5952. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  5953. }
  5954. parseSubscripts(base, startPos, startLoc, noCalls) {
  5955. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  5956. this.next();
  5957. const node = this.startNodeAt(startPos, startLoc);
  5958. node.callee = base;
  5959. node.arguments = this.parseCallExpressionArguments(11, false);
  5960. base = this.finishNode(node, "CallExpression");
  5961. } else if (base.type === "Identifier" && base.name === "async" && this.match(43)) {
  5962. const state = this.state.clone();
  5963. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  5964. if (!arrow.error && !arrow.aborted) return arrow.node;
  5965. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  5966. if (result.node && !result.error) return result.node;
  5967. if (arrow.node) {
  5968. this.state = arrow.failState;
  5969. return arrow.node;
  5970. }
  5971. if (result.node) {
  5972. this.state = result.failState;
  5973. return result.node;
  5974. }
  5975. throw arrow.error || result.error;
  5976. }
  5977. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  5978. }
  5979. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  5980. if (this.match(18) && this.isLookaheadToken_lt()) {
  5981. subscriptState.optionalChainMember = true;
  5982. if (noCalls) {
  5983. subscriptState.stop = true;
  5984. return base;
  5985. }
  5986. this.next();
  5987. const node = this.startNodeAt(startPos, startLoc);
  5988. node.callee = base;
  5989. node.typeArguments = this.flowParseTypeParameterInstantiation();
  5990. this.expect(10);
  5991. node.arguments = this.parseCallExpressionArguments(11, false);
  5992. node.optional = true;
  5993. return this.finishCallExpression(node, true);
  5994. } else if (!noCalls && this.shouldParseTypes() && this.match(43)) {
  5995. const node = this.startNodeAt(startPos, startLoc);
  5996. node.callee = base;
  5997. const result = this.tryParse(() => {
  5998. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  5999. this.expect(10);
  6000. node.arguments = this.parseCallExpressionArguments(11, false);
  6001. if (subscriptState.optionalChainMember) node.optional = false;
  6002. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  6003. });
  6004. if (result.node) {
  6005. if (result.error) this.state = result.failState;
  6006. return result.node;
  6007. }
  6008. }
  6009. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  6010. }
  6011. parseNewArguments(node) {
  6012. let targs = null;
  6013. if (this.shouldParseTypes() && this.match(43)) {
  6014. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  6015. }
  6016. node.typeArguments = targs;
  6017. super.parseNewArguments(node);
  6018. }
  6019. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  6020. const node = this.startNodeAt(startPos, startLoc);
  6021. this.parseFunctionParams(node);
  6022. if (!this.parseArrow(node)) return;
  6023. return this.parseArrowExpression(node, undefined, true);
  6024. }
  6025. readToken_mult_modulo(code) {
  6026. const next = this.input.charCodeAt(this.state.pos + 1);
  6027. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  6028. this.state.hasFlowComment = false;
  6029. this.state.pos += 2;
  6030. this.nextToken();
  6031. return;
  6032. }
  6033. super.readToken_mult_modulo(code);
  6034. }
  6035. readToken_pipe_amp(code) {
  6036. const next = this.input.charCodeAt(this.state.pos + 1);
  6037. if (code === 124 && next === 125) {
  6038. this.finishOp(9, 2);
  6039. return;
  6040. }
  6041. super.readToken_pipe_amp(code);
  6042. }
  6043. parseTopLevel(file, program) {
  6044. const fileNode = super.parseTopLevel(file, program);
  6045. if (this.state.hasFlowComment) {
  6046. this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment);
  6047. }
  6048. return fileNode;
  6049. }
  6050. skipBlockComment() {
  6051. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  6052. if (this.state.hasFlowComment) {
  6053. this.unexpected(null, FlowErrors.NestedFlowComment);
  6054. }
  6055. this.hasFlowCommentCompletion();
  6056. this.state.pos += this.skipFlowComment();
  6057. this.state.hasFlowComment = true;
  6058. return;
  6059. }
  6060. if (this.state.hasFlowComment) {
  6061. const end = this.input.indexOf("*-/", this.state.pos += 2);
  6062. if (end === -1) {
  6063. throw this.raise(this.state.pos - 2, ErrorMessages.UnterminatedComment);
  6064. }
  6065. this.state.pos = end + 3;
  6066. return;
  6067. }
  6068. return super.skipBlockComment();
  6069. }
  6070. skipFlowComment() {
  6071. const {
  6072. pos
  6073. } = this.state;
  6074. let shiftToFirstNonWhiteSpace = 2;
  6075. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  6076. shiftToFirstNonWhiteSpace++;
  6077. }
  6078. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  6079. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  6080. if (ch2 === 58 && ch3 === 58) {
  6081. return shiftToFirstNonWhiteSpace + 2;
  6082. }
  6083. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  6084. return shiftToFirstNonWhiteSpace + 12;
  6085. }
  6086. if (ch2 === 58 && ch3 !== 58) {
  6087. return shiftToFirstNonWhiteSpace;
  6088. }
  6089. return false;
  6090. }
  6091. hasFlowCommentCompletion() {
  6092. const end = this.input.indexOf("*/", this.state.pos);
  6093. if (end === -1) {
  6094. throw this.raise(this.state.pos, ErrorMessages.UnterminatedComment);
  6095. }
  6096. }
  6097. flowEnumErrorBooleanMemberNotInitialized(pos, {
  6098. enumName,
  6099. memberName
  6100. }) {
  6101. this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName);
  6102. }
  6103. flowEnumErrorInvalidMemberName(pos, {
  6104. enumName,
  6105. memberName
  6106. }) {
  6107. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  6108. this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName);
  6109. }
  6110. flowEnumErrorDuplicateMemberName(pos, {
  6111. enumName,
  6112. memberName
  6113. }) {
  6114. this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName);
  6115. }
  6116. flowEnumErrorInconsistentMemberValues(pos, {
  6117. enumName
  6118. }) {
  6119. this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName);
  6120. }
  6121. flowEnumErrorInvalidExplicitType(pos, {
  6122. enumName,
  6123. suppliedType
  6124. }) {
  6125. return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType);
  6126. }
  6127. flowEnumErrorInvalidMemberInitializer(pos, {
  6128. enumName,
  6129. explicitType,
  6130. memberName
  6131. }) {
  6132. let message = null;
  6133. switch (explicitType) {
  6134. case "boolean":
  6135. case "number":
  6136. case "string":
  6137. message = FlowErrors.EnumInvalidMemberInitializerPrimaryType;
  6138. break;
  6139. case "symbol":
  6140. message = FlowErrors.EnumInvalidMemberInitializerSymbolType;
  6141. break;
  6142. default:
  6143. message = FlowErrors.EnumInvalidMemberInitializerUnknownType;
  6144. }
  6145. return this.raise(pos, message, enumName, memberName, explicitType);
  6146. }
  6147. flowEnumErrorNumberMemberNotInitialized(pos, {
  6148. enumName,
  6149. memberName
  6150. }) {
  6151. this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName);
  6152. }
  6153. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  6154. enumName
  6155. }) {
  6156. this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName);
  6157. }
  6158. flowEnumMemberInit() {
  6159. const startPos = this.state.start;
  6160. const endOfInit = () => this.match(12) || this.match(8);
  6161. switch (this.state.type) {
  6162. case 124:
  6163. {
  6164. const literal = this.parseNumericLiteral(this.state.value);
  6165. if (endOfInit()) {
  6166. return {
  6167. type: "number",
  6168. pos: literal.start,
  6169. value: literal
  6170. };
  6171. }
  6172. return {
  6173. type: "invalid",
  6174. pos: startPos
  6175. };
  6176. }
  6177. case 123:
  6178. {
  6179. const literal = this.parseStringLiteral(this.state.value);
  6180. if (endOfInit()) {
  6181. return {
  6182. type: "string",
  6183. pos: literal.start,
  6184. value: literal
  6185. };
  6186. }
  6187. return {
  6188. type: "invalid",
  6189. pos: startPos
  6190. };
  6191. }
  6192. case 79:
  6193. case 80:
  6194. {
  6195. const literal = this.parseBooleanLiteral(this.match(79));
  6196. if (endOfInit()) {
  6197. return {
  6198. type: "boolean",
  6199. pos: literal.start,
  6200. value: literal
  6201. };
  6202. }
  6203. return {
  6204. type: "invalid",
  6205. pos: startPos
  6206. };
  6207. }
  6208. default:
  6209. return {
  6210. type: "invalid",
  6211. pos: startPos
  6212. };
  6213. }
  6214. }
  6215. flowEnumMemberRaw() {
  6216. const pos = this.state.start;
  6217. const id = this.parseIdentifier(true);
  6218. const init = this.eat(27) ? this.flowEnumMemberInit() : {
  6219. type: "none",
  6220. pos
  6221. };
  6222. return {
  6223. id,
  6224. init
  6225. };
  6226. }
  6227. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  6228. const {
  6229. explicitType
  6230. } = context;
  6231. if (explicitType === null) {
  6232. return;
  6233. }
  6234. if (explicitType !== expectedType) {
  6235. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  6236. }
  6237. }
  6238. flowEnumMembers({
  6239. enumName,
  6240. explicitType
  6241. }) {
  6242. const seenNames = new Set();
  6243. const members = {
  6244. booleanMembers: [],
  6245. numberMembers: [],
  6246. stringMembers: [],
  6247. defaultedMembers: []
  6248. };
  6249. let hasUnknownMembers = false;
  6250. while (!this.match(8)) {
  6251. if (this.eat(21)) {
  6252. hasUnknownMembers = true;
  6253. break;
  6254. }
  6255. const memberNode = this.startNode();
  6256. const {
  6257. id,
  6258. init
  6259. } = this.flowEnumMemberRaw();
  6260. const memberName = id.name;
  6261. if (memberName === "") {
  6262. continue;
  6263. }
  6264. if (/^[a-z]/.test(memberName)) {
  6265. this.flowEnumErrorInvalidMemberName(id.start, {
  6266. enumName,
  6267. memberName
  6268. });
  6269. }
  6270. if (seenNames.has(memberName)) {
  6271. this.flowEnumErrorDuplicateMemberName(id.start, {
  6272. enumName,
  6273. memberName
  6274. });
  6275. }
  6276. seenNames.add(memberName);
  6277. const context = {
  6278. enumName,
  6279. explicitType,
  6280. memberName
  6281. };
  6282. memberNode.id = id;
  6283. switch (init.type) {
  6284. case "boolean":
  6285. {
  6286. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  6287. memberNode.init = init.value;
  6288. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  6289. break;
  6290. }
  6291. case "number":
  6292. {
  6293. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  6294. memberNode.init = init.value;
  6295. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  6296. break;
  6297. }
  6298. case "string":
  6299. {
  6300. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  6301. memberNode.init = init.value;
  6302. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  6303. break;
  6304. }
  6305. case "invalid":
  6306. {
  6307. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  6308. }
  6309. case "none":
  6310. {
  6311. switch (explicitType) {
  6312. case "boolean":
  6313. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  6314. break;
  6315. case "number":
  6316. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  6317. break;
  6318. default:
  6319. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  6320. }
  6321. }
  6322. }
  6323. if (!this.match(8)) {
  6324. this.expect(12);
  6325. }
  6326. }
  6327. return {
  6328. members,
  6329. hasUnknownMembers
  6330. };
  6331. }
  6332. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  6333. enumName
  6334. }) {
  6335. if (initializedMembers.length === 0) {
  6336. return defaultedMembers;
  6337. } else if (defaultedMembers.length === 0) {
  6338. return initializedMembers;
  6339. } else if (defaultedMembers.length > initializedMembers.length) {
  6340. for (const member of initializedMembers) {
  6341. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  6342. enumName
  6343. });
  6344. }
  6345. return defaultedMembers;
  6346. } else {
  6347. for (const member of defaultedMembers) {
  6348. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  6349. enumName
  6350. });
  6351. }
  6352. return initializedMembers;
  6353. }
  6354. }
  6355. flowEnumParseExplicitType({
  6356. enumName
  6357. }) {
  6358. if (this.eatContextual(95)) {
  6359. if (!tokenIsIdentifier(this.state.type)) {
  6360. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  6361. enumName,
  6362. suppliedType: null
  6363. });
  6364. }
  6365. const {
  6366. value
  6367. } = this.state;
  6368. this.next();
  6369. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  6370. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  6371. enumName,
  6372. suppliedType: value
  6373. });
  6374. }
  6375. return value;
  6376. }
  6377. return null;
  6378. }
  6379. flowEnumBody(node, {
  6380. enumName,
  6381. nameLoc
  6382. }) {
  6383. const explicitType = this.flowEnumParseExplicitType({
  6384. enumName
  6385. });
  6386. this.expect(5);
  6387. const {
  6388. members,
  6389. hasUnknownMembers
  6390. } = this.flowEnumMembers({
  6391. enumName,
  6392. explicitType
  6393. });
  6394. node.hasUnknownMembers = hasUnknownMembers;
  6395. switch (explicitType) {
  6396. case "boolean":
  6397. node.explicitType = true;
  6398. node.members = members.booleanMembers;
  6399. this.expect(8);
  6400. return this.finishNode(node, "EnumBooleanBody");
  6401. case "number":
  6402. node.explicitType = true;
  6403. node.members = members.numberMembers;
  6404. this.expect(8);
  6405. return this.finishNode(node, "EnumNumberBody");
  6406. case "string":
  6407. node.explicitType = true;
  6408. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  6409. enumName
  6410. });
  6411. this.expect(8);
  6412. return this.finishNode(node, "EnumStringBody");
  6413. case "symbol":
  6414. node.members = members.defaultedMembers;
  6415. this.expect(8);
  6416. return this.finishNode(node, "EnumSymbolBody");
  6417. default:
  6418. {
  6419. const empty = () => {
  6420. node.members = [];
  6421. this.expect(8);
  6422. return this.finishNode(node, "EnumStringBody");
  6423. };
  6424. node.explicitType = false;
  6425. const boolsLen = members.booleanMembers.length;
  6426. const numsLen = members.numberMembers.length;
  6427. const strsLen = members.stringMembers.length;
  6428. const defaultedLen = members.defaultedMembers.length;
  6429. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  6430. return empty();
  6431. } else if (!boolsLen && !numsLen) {
  6432. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  6433. enumName
  6434. });
  6435. this.expect(8);
  6436. return this.finishNode(node, "EnumStringBody");
  6437. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  6438. for (const member of members.defaultedMembers) {
  6439. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  6440. enumName,
  6441. memberName: member.id.name
  6442. });
  6443. }
  6444. node.members = members.booleanMembers;
  6445. this.expect(8);
  6446. return this.finishNode(node, "EnumBooleanBody");
  6447. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  6448. for (const member of members.defaultedMembers) {
  6449. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  6450. enumName,
  6451. memberName: member.id.name
  6452. });
  6453. }
  6454. node.members = members.numberMembers;
  6455. this.expect(8);
  6456. return this.finishNode(node, "EnumNumberBody");
  6457. } else {
  6458. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  6459. enumName
  6460. });
  6461. return empty();
  6462. }
  6463. }
  6464. }
  6465. }
  6466. flowParseEnumDeclaration(node) {
  6467. const id = this.parseIdentifier();
  6468. node.id = id;
  6469. node.body = this.flowEnumBody(this.startNode(), {
  6470. enumName: id.name,
  6471. nameLoc: id.start
  6472. });
  6473. return this.finishNode(node, "EnumDeclaration");
  6474. }
  6475. isLookaheadToken_lt() {
  6476. const next = this.nextTokenStart();
  6477. if (this.input.charCodeAt(next) === 60) {
  6478. const afterNext = this.input.charCodeAt(next + 1);
  6479. return afterNext !== 60 && afterNext !== 61;
  6480. }
  6481. return false;
  6482. }
  6483. maybeUnwrapTypeCastExpression(node) {
  6484. return node.type === "TypeCastExpression" ? node.expression : node;
  6485. }
  6486. });
  6487. const entities = {
  6488. quot: "\u0022",
  6489. amp: "&",
  6490. apos: "\u0027",
  6491. lt: "<",
  6492. gt: ">",
  6493. nbsp: "\u00A0",
  6494. iexcl: "\u00A1",
  6495. cent: "\u00A2",
  6496. pound: "\u00A3",
  6497. curren: "\u00A4",
  6498. yen: "\u00A5",
  6499. brvbar: "\u00A6",
  6500. sect: "\u00A7",
  6501. uml: "\u00A8",
  6502. copy: "\u00A9",
  6503. ordf: "\u00AA",
  6504. laquo: "\u00AB",
  6505. not: "\u00AC",
  6506. shy: "\u00AD",
  6507. reg: "\u00AE",
  6508. macr: "\u00AF",
  6509. deg: "\u00B0",
  6510. plusmn: "\u00B1",
  6511. sup2: "\u00B2",
  6512. sup3: "\u00B3",
  6513. acute: "\u00B4",
  6514. micro: "\u00B5",
  6515. para: "\u00B6",
  6516. middot: "\u00B7",
  6517. cedil: "\u00B8",
  6518. sup1: "\u00B9",
  6519. ordm: "\u00BA",
  6520. raquo: "\u00BB",
  6521. frac14: "\u00BC",
  6522. frac12: "\u00BD",
  6523. frac34: "\u00BE",
  6524. iquest: "\u00BF",
  6525. Agrave: "\u00C0",
  6526. Aacute: "\u00C1",
  6527. Acirc: "\u00C2",
  6528. Atilde: "\u00C3",
  6529. Auml: "\u00C4",
  6530. Aring: "\u00C5",
  6531. AElig: "\u00C6",
  6532. Ccedil: "\u00C7",
  6533. Egrave: "\u00C8",
  6534. Eacute: "\u00C9",
  6535. Ecirc: "\u00CA",
  6536. Euml: "\u00CB",
  6537. Igrave: "\u00CC",
  6538. Iacute: "\u00CD",
  6539. Icirc: "\u00CE",
  6540. Iuml: "\u00CF",
  6541. ETH: "\u00D0",
  6542. Ntilde: "\u00D1",
  6543. Ograve: "\u00D2",
  6544. Oacute: "\u00D3",
  6545. Ocirc: "\u00D4",
  6546. Otilde: "\u00D5",
  6547. Ouml: "\u00D6",
  6548. times: "\u00D7",
  6549. Oslash: "\u00D8",
  6550. Ugrave: "\u00D9",
  6551. Uacute: "\u00DA",
  6552. Ucirc: "\u00DB",
  6553. Uuml: "\u00DC",
  6554. Yacute: "\u00DD",
  6555. THORN: "\u00DE",
  6556. szlig: "\u00DF",
  6557. agrave: "\u00E0",
  6558. aacute: "\u00E1",
  6559. acirc: "\u00E2",
  6560. atilde: "\u00E3",
  6561. auml: "\u00E4",
  6562. aring: "\u00E5",
  6563. aelig: "\u00E6",
  6564. ccedil: "\u00E7",
  6565. egrave: "\u00E8",
  6566. eacute: "\u00E9",
  6567. ecirc: "\u00EA",
  6568. euml: "\u00EB",
  6569. igrave: "\u00EC",
  6570. iacute: "\u00ED",
  6571. icirc: "\u00EE",
  6572. iuml: "\u00EF",
  6573. eth: "\u00F0",
  6574. ntilde: "\u00F1",
  6575. ograve: "\u00F2",
  6576. oacute: "\u00F3",
  6577. ocirc: "\u00F4",
  6578. otilde: "\u00F5",
  6579. ouml: "\u00F6",
  6580. divide: "\u00F7",
  6581. oslash: "\u00F8",
  6582. ugrave: "\u00F9",
  6583. uacute: "\u00FA",
  6584. ucirc: "\u00FB",
  6585. uuml: "\u00FC",
  6586. yacute: "\u00FD",
  6587. thorn: "\u00FE",
  6588. yuml: "\u00FF",
  6589. OElig: "\u0152",
  6590. oelig: "\u0153",
  6591. Scaron: "\u0160",
  6592. scaron: "\u0161",
  6593. Yuml: "\u0178",
  6594. fnof: "\u0192",
  6595. circ: "\u02C6",
  6596. tilde: "\u02DC",
  6597. Alpha: "\u0391",
  6598. Beta: "\u0392",
  6599. Gamma: "\u0393",
  6600. Delta: "\u0394",
  6601. Epsilon: "\u0395",
  6602. Zeta: "\u0396",
  6603. Eta: "\u0397",
  6604. Theta: "\u0398",
  6605. Iota: "\u0399",
  6606. Kappa: "\u039A",
  6607. Lambda: "\u039B",
  6608. Mu: "\u039C",
  6609. Nu: "\u039D",
  6610. Xi: "\u039E",
  6611. Omicron: "\u039F",
  6612. Pi: "\u03A0",
  6613. Rho: "\u03A1",
  6614. Sigma: "\u03A3",
  6615. Tau: "\u03A4",
  6616. Upsilon: "\u03A5",
  6617. Phi: "\u03A6",
  6618. Chi: "\u03A7",
  6619. Psi: "\u03A8",
  6620. Omega: "\u03A9",
  6621. alpha: "\u03B1",
  6622. beta: "\u03B2",
  6623. gamma: "\u03B3",
  6624. delta: "\u03B4",
  6625. epsilon: "\u03B5",
  6626. zeta: "\u03B6",
  6627. eta: "\u03B7",
  6628. theta: "\u03B8",
  6629. iota: "\u03B9",
  6630. kappa: "\u03BA",
  6631. lambda: "\u03BB",
  6632. mu: "\u03BC",
  6633. nu: "\u03BD",
  6634. xi: "\u03BE",
  6635. omicron: "\u03BF",
  6636. pi: "\u03C0",
  6637. rho: "\u03C1",
  6638. sigmaf: "\u03C2",
  6639. sigma: "\u03C3",
  6640. tau: "\u03C4",
  6641. upsilon: "\u03C5",
  6642. phi: "\u03C6",
  6643. chi: "\u03C7",
  6644. psi: "\u03C8",
  6645. omega: "\u03C9",
  6646. thetasym: "\u03D1",
  6647. upsih: "\u03D2",
  6648. piv: "\u03D6",
  6649. ensp: "\u2002",
  6650. emsp: "\u2003",
  6651. thinsp: "\u2009",
  6652. zwnj: "\u200C",
  6653. zwj: "\u200D",
  6654. lrm: "\u200E",
  6655. rlm: "\u200F",
  6656. ndash: "\u2013",
  6657. mdash: "\u2014",
  6658. lsquo: "\u2018",
  6659. rsquo: "\u2019",
  6660. sbquo: "\u201A",
  6661. ldquo: "\u201C",
  6662. rdquo: "\u201D",
  6663. bdquo: "\u201E",
  6664. dagger: "\u2020",
  6665. Dagger: "\u2021",
  6666. bull: "\u2022",
  6667. hellip: "\u2026",
  6668. permil: "\u2030",
  6669. prime: "\u2032",
  6670. Prime: "\u2033",
  6671. lsaquo: "\u2039",
  6672. rsaquo: "\u203A",
  6673. oline: "\u203E",
  6674. frasl: "\u2044",
  6675. euro: "\u20AC",
  6676. image: "\u2111",
  6677. weierp: "\u2118",
  6678. real: "\u211C",
  6679. trade: "\u2122",
  6680. alefsym: "\u2135",
  6681. larr: "\u2190",
  6682. uarr: "\u2191",
  6683. rarr: "\u2192",
  6684. darr: "\u2193",
  6685. harr: "\u2194",
  6686. crarr: "\u21B5",
  6687. lArr: "\u21D0",
  6688. uArr: "\u21D1",
  6689. rArr: "\u21D2",
  6690. dArr: "\u21D3",
  6691. hArr: "\u21D4",
  6692. forall: "\u2200",
  6693. part: "\u2202",
  6694. exist: "\u2203",
  6695. empty: "\u2205",
  6696. nabla: "\u2207",
  6697. isin: "\u2208",
  6698. notin: "\u2209",
  6699. ni: "\u220B",
  6700. prod: "\u220F",
  6701. sum: "\u2211",
  6702. minus: "\u2212",
  6703. lowast: "\u2217",
  6704. radic: "\u221A",
  6705. prop: "\u221D",
  6706. infin: "\u221E",
  6707. ang: "\u2220",
  6708. and: "\u2227",
  6709. or: "\u2228",
  6710. cap: "\u2229",
  6711. cup: "\u222A",
  6712. int: "\u222B",
  6713. there4: "\u2234",
  6714. sim: "\u223C",
  6715. cong: "\u2245",
  6716. asymp: "\u2248",
  6717. ne: "\u2260",
  6718. equiv: "\u2261",
  6719. le: "\u2264",
  6720. ge: "\u2265",
  6721. sub: "\u2282",
  6722. sup: "\u2283",
  6723. nsub: "\u2284",
  6724. sube: "\u2286",
  6725. supe: "\u2287",
  6726. oplus: "\u2295",
  6727. otimes: "\u2297",
  6728. perp: "\u22A5",
  6729. sdot: "\u22C5",
  6730. lceil: "\u2308",
  6731. rceil: "\u2309",
  6732. lfloor: "\u230A",
  6733. rfloor: "\u230B",
  6734. lang: "\u2329",
  6735. rang: "\u232A",
  6736. loz: "\u25CA",
  6737. spades: "\u2660",
  6738. clubs: "\u2663",
  6739. hearts: "\u2665",
  6740. diams: "\u2666"
  6741. };
  6742. const HEX_NUMBER = /^[\da-fA-F]+$/;
  6743. const DECIMAL_NUMBER = /^\d+$/;
  6744. const JsxErrors = makeErrorTemplates({
  6745. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.",
  6746. MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>.",
  6747. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.",
  6748. UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
  6749. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.",
  6750. UnterminatedJsxContent: "Unterminated JSX contents.",
  6751. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  6752. }, ErrorCodes.SyntaxError, "jsx");
  6753. types$1.j_oTag = new TokContext("<tag");
  6754. types$1.j_cTag = new TokContext("</tag");
  6755. types$1.j_expr = new TokContext("<tag>...</tag>", true);
  6756. function isFragment(object) {
  6757. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  6758. }
  6759. function getQualifiedJSXName(object) {
  6760. if (object.type === "JSXIdentifier") {
  6761. return object.name;
  6762. }
  6763. if (object.type === "JSXNamespacedName") {
  6764. return object.namespace.name + ":" + object.name.name;
  6765. }
  6766. if (object.type === "JSXMemberExpression") {
  6767. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  6768. }
  6769. throw new Error("Node had unexpected type: " + object.type);
  6770. }
  6771. var jsx = (superClass => class extends superClass {
  6772. jsxReadToken() {
  6773. let out = "";
  6774. let chunkStart = this.state.pos;
  6775. for (;;) {
  6776. if (this.state.pos >= this.length) {
  6777. throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent);
  6778. }
  6779. const ch = this.input.charCodeAt(this.state.pos);
  6780. switch (ch) {
  6781. case 60:
  6782. case 123:
  6783. if (this.state.pos === this.state.start) {
  6784. if (ch === 60 && this.state.canStartJSXElement) {
  6785. ++this.state.pos;
  6786. return this.finishToken(132);
  6787. }
  6788. return super.getTokenFromCode(ch);
  6789. }
  6790. out += this.input.slice(chunkStart, this.state.pos);
  6791. return this.finishToken(131, out);
  6792. case 38:
  6793. out += this.input.slice(chunkStart, this.state.pos);
  6794. out += this.jsxReadEntity();
  6795. chunkStart = this.state.pos;
  6796. break;
  6797. case 62:
  6798. case 125:
  6799. default:
  6800. if (isNewLine(ch)) {
  6801. out += this.input.slice(chunkStart, this.state.pos);
  6802. out += this.jsxReadNewLine(true);
  6803. chunkStart = this.state.pos;
  6804. } else {
  6805. ++this.state.pos;
  6806. }
  6807. }
  6808. }
  6809. }
  6810. jsxReadNewLine(normalizeCRLF) {
  6811. const ch = this.input.charCodeAt(this.state.pos);
  6812. let out;
  6813. ++this.state.pos;
  6814. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  6815. ++this.state.pos;
  6816. out = normalizeCRLF ? "\n" : "\r\n";
  6817. } else {
  6818. out = String.fromCharCode(ch);
  6819. }
  6820. ++this.state.curLine;
  6821. this.state.lineStart = this.state.pos;
  6822. return out;
  6823. }
  6824. jsxReadString(quote) {
  6825. let out = "";
  6826. let chunkStart = ++this.state.pos;
  6827. for (;;) {
  6828. if (this.state.pos >= this.length) {
  6829. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  6830. }
  6831. const ch = this.input.charCodeAt(this.state.pos);
  6832. if (ch === quote) break;
  6833. if (ch === 38) {
  6834. out += this.input.slice(chunkStart, this.state.pos);
  6835. out += this.jsxReadEntity();
  6836. chunkStart = this.state.pos;
  6837. } else if (isNewLine(ch)) {
  6838. out += this.input.slice(chunkStart, this.state.pos);
  6839. out += this.jsxReadNewLine(false);
  6840. chunkStart = this.state.pos;
  6841. } else {
  6842. ++this.state.pos;
  6843. }
  6844. }
  6845. out += this.input.slice(chunkStart, this.state.pos++);
  6846. return this.finishToken(123, out);
  6847. }
  6848. jsxReadEntity() {
  6849. let str = "";
  6850. let count = 0;
  6851. let entity;
  6852. let ch = this.input[this.state.pos];
  6853. const startPos = ++this.state.pos;
  6854. while (this.state.pos < this.length && count++ < 10) {
  6855. ch = this.input[this.state.pos++];
  6856. if (ch === ";") {
  6857. if (str[0] === "#") {
  6858. if (str[1] === "x") {
  6859. str = str.substr(2);
  6860. if (HEX_NUMBER.test(str)) {
  6861. entity = String.fromCodePoint(parseInt(str, 16));
  6862. }
  6863. } else {
  6864. str = str.substr(1);
  6865. if (DECIMAL_NUMBER.test(str)) {
  6866. entity = String.fromCodePoint(parseInt(str, 10));
  6867. }
  6868. }
  6869. } else {
  6870. entity = entities[str];
  6871. }
  6872. break;
  6873. }
  6874. str += ch;
  6875. }
  6876. if (!entity) {
  6877. this.state.pos = startPos;
  6878. return "&";
  6879. }
  6880. return entity;
  6881. }
  6882. jsxReadWord() {
  6883. let ch;
  6884. const start = this.state.pos;
  6885. do {
  6886. ch = this.input.charCodeAt(++this.state.pos);
  6887. } while (isIdentifierChar(ch) || ch === 45);
  6888. return this.finishToken(130, this.input.slice(start, this.state.pos));
  6889. }
  6890. jsxParseIdentifier() {
  6891. const node = this.startNode();
  6892. if (this.match(130)) {
  6893. node.name = this.state.value;
  6894. } else if (tokenIsKeyword(this.state.type)) {
  6895. node.name = tokenLabelName(this.state.type);
  6896. } else {
  6897. this.unexpected();
  6898. }
  6899. this.next();
  6900. return this.finishNode(node, "JSXIdentifier");
  6901. }
  6902. jsxParseNamespacedName() {
  6903. const startPos = this.state.start;
  6904. const startLoc = this.state.startLoc;
  6905. const name = this.jsxParseIdentifier();
  6906. if (!this.eat(14)) return name;
  6907. const node = this.startNodeAt(startPos, startLoc);
  6908. node.namespace = name;
  6909. node.name = this.jsxParseIdentifier();
  6910. return this.finishNode(node, "JSXNamespacedName");
  6911. }
  6912. jsxParseElementName() {
  6913. const startPos = this.state.start;
  6914. const startLoc = this.state.startLoc;
  6915. let node = this.jsxParseNamespacedName();
  6916. if (node.type === "JSXNamespacedName") {
  6917. return node;
  6918. }
  6919. while (this.eat(16)) {
  6920. const newNode = this.startNodeAt(startPos, startLoc);
  6921. newNode.object = node;
  6922. newNode.property = this.jsxParseIdentifier();
  6923. node = this.finishNode(newNode, "JSXMemberExpression");
  6924. }
  6925. return node;
  6926. }
  6927. jsxParseAttributeValue() {
  6928. let node;
  6929. switch (this.state.type) {
  6930. case 5:
  6931. node = this.startNode();
  6932. this.next();
  6933. node = this.jsxParseExpressionContainer(node);
  6934. if (node.expression.type === "JSXEmptyExpression") {
  6935. this.raise(node.start, JsxErrors.AttributeIsEmpty);
  6936. }
  6937. return node;
  6938. case 132:
  6939. case 123:
  6940. return this.parseExprAtom();
  6941. default:
  6942. throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue);
  6943. }
  6944. }
  6945. jsxParseEmptyExpression() {
  6946. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  6947. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  6948. }
  6949. jsxParseSpreadChild(node) {
  6950. this.next();
  6951. node.expression = this.parseExpression();
  6952. this.expect(8);
  6953. return this.finishNode(node, "JSXSpreadChild");
  6954. }
  6955. jsxParseExpressionContainer(node) {
  6956. if (this.match(8)) {
  6957. node.expression = this.jsxParseEmptyExpression();
  6958. } else {
  6959. const expression = this.parseExpression();
  6960. node.expression = expression;
  6961. }
  6962. this.expect(8);
  6963. return this.finishNode(node, "JSXExpressionContainer");
  6964. }
  6965. jsxParseAttribute() {
  6966. const node = this.startNode();
  6967. if (this.eat(5)) {
  6968. this.expect(21);
  6969. node.argument = this.parseMaybeAssignAllowIn();
  6970. this.expect(8);
  6971. return this.finishNode(node, "JSXSpreadAttribute");
  6972. }
  6973. node.name = this.jsxParseNamespacedName();
  6974. node.value = this.eat(27) ? this.jsxParseAttributeValue() : null;
  6975. return this.finishNode(node, "JSXAttribute");
  6976. }
  6977. jsxParseOpeningElementAt(startPos, startLoc) {
  6978. const node = this.startNodeAt(startPos, startLoc);
  6979. if (this.match(133)) {
  6980. this.expect(133);
  6981. return this.finishNode(node, "JSXOpeningFragment");
  6982. }
  6983. node.name = this.jsxParseElementName();
  6984. return this.jsxParseOpeningElementAfterName(node);
  6985. }
  6986. jsxParseOpeningElementAfterName(node) {
  6987. const attributes = [];
  6988. while (!this.match(50) && !this.match(133)) {
  6989. attributes.push(this.jsxParseAttribute());
  6990. }
  6991. node.attributes = attributes;
  6992. node.selfClosing = this.eat(50);
  6993. this.expect(133);
  6994. return this.finishNode(node, "JSXOpeningElement");
  6995. }
  6996. jsxParseClosingElementAt(startPos, startLoc) {
  6997. const node = this.startNodeAt(startPos, startLoc);
  6998. if (this.match(133)) {
  6999. this.expect(133);
  7000. return this.finishNode(node, "JSXClosingFragment");
  7001. }
  7002. node.name = this.jsxParseElementName();
  7003. this.expect(133);
  7004. return this.finishNode(node, "JSXClosingElement");
  7005. }
  7006. jsxParseElementAt(startPos, startLoc) {
  7007. const node = this.startNodeAt(startPos, startLoc);
  7008. const children = [];
  7009. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  7010. let closingElement = null;
  7011. if (!openingElement.selfClosing) {
  7012. contents: for (;;) {
  7013. switch (this.state.type) {
  7014. case 132:
  7015. startPos = this.state.start;
  7016. startLoc = this.state.startLoc;
  7017. this.next();
  7018. if (this.eat(50)) {
  7019. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  7020. break contents;
  7021. }
  7022. children.push(this.jsxParseElementAt(startPos, startLoc));
  7023. break;
  7024. case 131:
  7025. children.push(this.parseExprAtom());
  7026. break;
  7027. case 5:
  7028. {
  7029. const node = this.startNode();
  7030. this.next();
  7031. if (this.match(21)) {
  7032. children.push(this.jsxParseSpreadChild(node));
  7033. } else {
  7034. children.push(this.jsxParseExpressionContainer(node));
  7035. }
  7036. break;
  7037. }
  7038. default:
  7039. throw this.unexpected();
  7040. }
  7041. }
  7042. if (isFragment(openingElement) && !isFragment(closingElement)) {
  7043. this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment);
  7044. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  7045. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  7046. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  7047. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  7048. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  7049. }
  7050. }
  7051. }
  7052. if (isFragment(openingElement)) {
  7053. node.openingFragment = openingElement;
  7054. node.closingFragment = closingElement;
  7055. } else {
  7056. node.openingElement = openingElement;
  7057. node.closingElement = closingElement;
  7058. }
  7059. node.children = children;
  7060. if (this.match(43)) {
  7061. throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements);
  7062. }
  7063. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  7064. }
  7065. jsxParseElement() {
  7066. const startPos = this.state.start;
  7067. const startLoc = this.state.startLoc;
  7068. this.next();
  7069. return this.jsxParseElementAt(startPos, startLoc);
  7070. }
  7071. parseExprAtom(refExpressionErrors) {
  7072. if (this.match(131)) {
  7073. return this.parseLiteral(this.state.value, "JSXText");
  7074. } else if (this.match(132)) {
  7075. return this.jsxParseElement();
  7076. } else if (this.match(43) && this.input.charCodeAt(this.state.pos) !== 33) {
  7077. this.replaceToken(132);
  7078. return this.jsxParseElement();
  7079. } else {
  7080. return super.parseExprAtom(refExpressionErrors);
  7081. }
  7082. }
  7083. getTokenFromCode(code) {
  7084. const context = this.curContext();
  7085. if (context === types$1.j_expr) {
  7086. return this.jsxReadToken();
  7087. }
  7088. if (context === types$1.j_oTag || context === types$1.j_cTag) {
  7089. if (isIdentifierStart(code)) {
  7090. return this.jsxReadWord();
  7091. }
  7092. if (code === 62) {
  7093. ++this.state.pos;
  7094. return this.finishToken(133);
  7095. }
  7096. if ((code === 34 || code === 39) && context === types$1.j_oTag) {
  7097. return this.jsxReadString(code);
  7098. }
  7099. }
  7100. if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  7101. ++this.state.pos;
  7102. return this.finishToken(132);
  7103. }
  7104. return super.getTokenFromCode(code);
  7105. }
  7106. updateContext(prevType) {
  7107. super.updateContext(prevType);
  7108. const {
  7109. context,
  7110. type
  7111. } = this.state;
  7112. if (type === 50 && prevType === 132) {
  7113. context.splice(-2, 2, types$1.j_cTag);
  7114. this.state.canStartJSXElement = false;
  7115. } else if (type === 132) {
  7116. context.push(types$1.j_expr, types$1.j_oTag);
  7117. } else if (type === 133) {
  7118. const out = context.pop();
  7119. if (out === types$1.j_oTag && prevType === 50 || out === types$1.j_cTag) {
  7120. context.pop();
  7121. this.state.canStartJSXElement = context[context.length - 1] === types$1.j_expr;
  7122. } else {
  7123. this.state.canStartJSXElement = true;
  7124. }
  7125. } else {
  7126. this.state.canStartJSXElement = tokenComesBeforeExpression(type);
  7127. }
  7128. }
  7129. });
  7130. class TypeScriptScope extends Scope {
  7131. constructor(...args) {
  7132. super(...args);
  7133. this.types = new Set();
  7134. this.enums = new Set();
  7135. this.constEnums = new Set();
  7136. this.classes = new Set();
  7137. this.exportOnlyBindings = new Set();
  7138. }
  7139. }
  7140. class TypeScriptScopeHandler extends ScopeHandler {
  7141. createScope(flags) {
  7142. return new TypeScriptScope(flags);
  7143. }
  7144. declareName(name, bindingType, pos) {
  7145. const scope = this.currentScope();
  7146. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  7147. this.maybeExportDefined(scope, name);
  7148. scope.exportOnlyBindings.add(name);
  7149. return;
  7150. }
  7151. super.declareName(...arguments);
  7152. if (bindingType & BIND_KIND_TYPE) {
  7153. if (!(bindingType & BIND_KIND_VALUE)) {
  7154. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  7155. this.maybeExportDefined(scope, name);
  7156. }
  7157. scope.types.add(name);
  7158. }
  7159. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.add(name);
  7160. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.add(name);
  7161. if (bindingType & BIND_FLAGS_CLASS) scope.classes.add(name);
  7162. }
  7163. isRedeclaredInScope(scope, name, bindingType) {
  7164. if (scope.enums.has(name)) {
  7165. if (bindingType & BIND_FLAGS_TS_ENUM) {
  7166. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  7167. const wasConst = scope.constEnums.has(name);
  7168. return isConst !== wasConst;
  7169. }
  7170. return true;
  7171. }
  7172. if (bindingType & BIND_FLAGS_CLASS && scope.classes.has(name)) {
  7173. if (scope.lexical.has(name)) {
  7174. return !!(bindingType & BIND_KIND_VALUE);
  7175. } else {
  7176. return false;
  7177. }
  7178. }
  7179. if (bindingType & BIND_KIND_TYPE && scope.types.has(name)) {
  7180. return true;
  7181. }
  7182. return super.isRedeclaredInScope(...arguments);
  7183. }
  7184. checkLocalExport(id) {
  7185. const topLevelScope = this.scopeStack[0];
  7186. const {
  7187. name
  7188. } = id;
  7189. if (!topLevelScope.types.has(name) && !topLevelScope.exportOnlyBindings.has(name)) {
  7190. super.checkLocalExport(id);
  7191. }
  7192. }
  7193. }
  7194. function nonNull(x) {
  7195. if (x == null) {
  7196. throw new Error(`Unexpected ${x} value.`);
  7197. }
  7198. return x;
  7199. }
  7200. function assert$1(x) {
  7201. if (!x) {
  7202. throw new Error("Assert fail");
  7203. }
  7204. }
  7205. const TSErrors = makeErrorTemplates({
  7206. AbstractMethodHasImplementation: "Method '%0' cannot have an implementation because it is marked abstract.",
  7207. AbstractPropertyHasInitializer: "Property '%0' cannot have an initializer because it is marked abstract.",
  7208. AccesorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.",
  7209. AccesorCannotHaveTypeParameters: "An accessor cannot have type parameters.",
  7210. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.",
  7211. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.",
  7212. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  7213. DeclareAccessor: "'declare' is not allowed in %0ters.",
  7214. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  7215. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  7216. DuplicateAccessibilityModifier: "Accessibility modifier already seen.",
  7217. DuplicateModifier: "Duplicate modifier: '%0'.",
  7218. EmptyHeritageClauseType: "'%0' list cannot be empty.",
  7219. EmptyTypeArguments: "Type argument list cannot be empty.",
  7220. EmptyTypeParameters: "Type parameter list cannot be empty.",
  7221. ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.",
  7222. ImportAliasHasImportType: "An import alias can not use 'import type'.",
  7223. IncompatibleModifiers: "'%0' modifier cannot be used with '%1' modifier.",
  7224. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.",
  7225. IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0').",
  7226. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.",
  7227. IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.",
  7228. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.",
  7229. InvalidModifierOnTypeMember: "'%0' modifier cannot appear on a type member.",
  7230. InvalidModifiersOrder: "'%0' modifier must precede '%1' modifier.",
  7231. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  7232. MissingInterfaceName: "'interface' declarations must be followed by an identifier.",
  7233. MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.",
  7234. NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.",
  7235. NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.",
  7236. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  7237. OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.",
  7238. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  7239. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  7240. PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0').",
  7241. ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.",
  7242. ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",
  7243. ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",
  7244. SetAccesorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.",
  7245. SetAccesorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.",
  7246. SetAccesorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.",
  7247. StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.",
  7248. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  7249. TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.",
  7250. TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",
  7251. TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",
  7252. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  7253. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  7254. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  7255. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  7256. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.",
  7257. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  7258. UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0."
  7259. }, ErrorCodes.SyntaxError, "typescript");
  7260. function keywordTypeFromName(value) {
  7261. switch (value) {
  7262. case "any":
  7263. return "TSAnyKeyword";
  7264. case "boolean":
  7265. return "TSBooleanKeyword";
  7266. case "bigint":
  7267. return "TSBigIntKeyword";
  7268. case "never":
  7269. return "TSNeverKeyword";
  7270. case "number":
  7271. return "TSNumberKeyword";
  7272. case "object":
  7273. return "TSObjectKeyword";
  7274. case "string":
  7275. return "TSStringKeyword";
  7276. case "symbol":
  7277. return "TSSymbolKeyword";
  7278. case "undefined":
  7279. return "TSUndefinedKeyword";
  7280. case "unknown":
  7281. return "TSUnknownKeyword";
  7282. default:
  7283. return undefined;
  7284. }
  7285. }
  7286. function tsIsAccessModifier(modifier) {
  7287. return modifier === "private" || modifier === "public" || modifier === "protected";
  7288. }
  7289. var typescript = (superClass => class extends superClass {
  7290. getScopeHandler() {
  7291. return TypeScriptScopeHandler;
  7292. }
  7293. tsIsIdentifier() {
  7294. return tokenIsIdentifier(this.state.type);
  7295. }
  7296. tsTokenCanFollowModifier() {
  7297. return (this.match(0) || this.match(5) || this.match(49) || this.match(21) || this.match(128) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak();
  7298. }
  7299. tsNextTokenCanFollowModifier() {
  7300. this.next();
  7301. return this.tsTokenCanFollowModifier();
  7302. }
  7303. tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock) {
  7304. if (!tokenIsIdentifier(this.state.type)) {
  7305. return undefined;
  7306. }
  7307. const modifier = this.state.value;
  7308. if (allowedModifiers.indexOf(modifier) !== -1) {
  7309. if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) {
  7310. return undefined;
  7311. }
  7312. if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  7313. return modifier;
  7314. }
  7315. }
  7316. return undefined;
  7317. }
  7318. tsParseModifiers(modified, allowedModifiers, disallowedModifiers, errorTemplate, stopOnStartOfClassStaticBlock) {
  7319. const enforceOrder = (pos, modifier, before, after) => {
  7320. if (modifier === before && modified[after]) {
  7321. this.raise(pos, TSErrors.InvalidModifiersOrder, before, after);
  7322. }
  7323. };
  7324. const incompatible = (pos, modifier, mod1, mod2) => {
  7325. if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) {
  7326. this.raise(pos, TSErrors.IncompatibleModifiers, mod1, mod2);
  7327. }
  7328. };
  7329. for (;;) {
  7330. const startPos = this.state.start;
  7331. const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock);
  7332. if (!modifier) break;
  7333. if (tsIsAccessModifier(modifier)) {
  7334. if (modified.accessibility) {
  7335. this.raise(startPos, TSErrors.DuplicateAccessibilityModifier);
  7336. } else {
  7337. enforceOrder(startPos, modifier, modifier, "override");
  7338. enforceOrder(startPos, modifier, modifier, "static");
  7339. enforceOrder(startPos, modifier, modifier, "readonly");
  7340. modified.accessibility = modifier;
  7341. }
  7342. } else {
  7343. if (Object.hasOwnProperty.call(modified, modifier)) {
  7344. this.raise(startPos, TSErrors.DuplicateModifier, modifier);
  7345. } else {
  7346. enforceOrder(startPos, modifier, "static", "readonly");
  7347. enforceOrder(startPos, modifier, "static", "override");
  7348. enforceOrder(startPos, modifier, "override", "readonly");
  7349. enforceOrder(startPos, modifier, "abstract", "override");
  7350. incompatible(startPos, modifier, "declare", "override");
  7351. incompatible(startPos, modifier, "static", "abstract");
  7352. }
  7353. modified[modifier] = true;
  7354. }
  7355. if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) {
  7356. this.raise(startPos, errorTemplate, modifier);
  7357. }
  7358. }
  7359. }
  7360. tsIsListTerminator(kind) {
  7361. switch (kind) {
  7362. case "EnumMembers":
  7363. case "TypeMembers":
  7364. return this.match(8);
  7365. case "HeritageClauseElement":
  7366. return this.match(5);
  7367. case "TupleElementTypes":
  7368. return this.match(3);
  7369. case "TypeParametersOrArguments":
  7370. return this.match(44);
  7371. }
  7372. throw new Error("Unreachable");
  7373. }
  7374. tsParseList(kind, parseElement) {
  7375. const result = [];
  7376. while (!this.tsIsListTerminator(kind)) {
  7377. result.push(parseElement());
  7378. }
  7379. return result;
  7380. }
  7381. tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) {
  7382. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos));
  7383. }
  7384. tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) {
  7385. const result = [];
  7386. let trailingCommaPos = -1;
  7387. for (;;) {
  7388. if (this.tsIsListTerminator(kind)) {
  7389. break;
  7390. }
  7391. trailingCommaPos = -1;
  7392. const element = parseElement();
  7393. if (element == null) {
  7394. return undefined;
  7395. }
  7396. result.push(element);
  7397. if (this.eat(12)) {
  7398. trailingCommaPos = this.state.lastTokStart;
  7399. continue;
  7400. }
  7401. if (this.tsIsListTerminator(kind)) {
  7402. break;
  7403. }
  7404. if (expectSuccess) {
  7405. this.expect(12);
  7406. }
  7407. return undefined;
  7408. }
  7409. if (refTrailingCommaPos) {
  7410. refTrailingCommaPos.value = trailingCommaPos;
  7411. }
  7412. return result;
  7413. }
  7414. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) {
  7415. if (!skipFirstToken) {
  7416. if (bracket) {
  7417. this.expect(0);
  7418. } else {
  7419. this.expect(43);
  7420. }
  7421. }
  7422. const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos);
  7423. if (bracket) {
  7424. this.expect(3);
  7425. } else {
  7426. this.expect(44);
  7427. }
  7428. return result;
  7429. }
  7430. tsParseImportType() {
  7431. const node = this.startNode();
  7432. this.expect(77);
  7433. this.expect(10);
  7434. if (!this.match(123)) {
  7435. this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument);
  7436. }
  7437. node.argument = this.parseExprAtom();
  7438. this.expect(11);
  7439. if (this.eat(16)) {
  7440. node.qualifier = this.tsParseEntityName(true);
  7441. }
  7442. if (this.match(43)) {
  7443. node.typeParameters = this.tsParseTypeArguments();
  7444. }
  7445. return this.finishNode(node, "TSImportType");
  7446. }
  7447. tsParseEntityName(allowReservedWords) {
  7448. let entity = this.parseIdentifier();
  7449. while (this.eat(16)) {
  7450. const node = this.startNodeAtNode(entity);
  7451. node.left = entity;
  7452. node.right = this.parseIdentifier(allowReservedWords);
  7453. entity = this.finishNode(node, "TSQualifiedName");
  7454. }
  7455. return entity;
  7456. }
  7457. tsParseTypeReference() {
  7458. const node = this.startNode();
  7459. node.typeName = this.tsParseEntityName(false);
  7460. if (!this.hasPrecedingLineBreak() && this.match(43)) {
  7461. node.typeParameters = this.tsParseTypeArguments();
  7462. }
  7463. return this.finishNode(node, "TSTypeReference");
  7464. }
  7465. tsParseThisTypePredicate(lhs) {
  7466. this.next();
  7467. const node = this.startNodeAtNode(lhs);
  7468. node.parameterName = lhs;
  7469. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  7470. node.asserts = false;
  7471. return this.finishNode(node, "TSTypePredicate");
  7472. }
  7473. tsParseThisTypeNode() {
  7474. const node = this.startNode();
  7475. this.next();
  7476. return this.finishNode(node, "TSThisType");
  7477. }
  7478. tsParseTypeQuery() {
  7479. const node = this.startNode();
  7480. this.expect(81);
  7481. if (this.match(77)) {
  7482. node.exprName = this.tsParseImportType();
  7483. } else {
  7484. node.exprName = this.tsParseEntityName(true);
  7485. }
  7486. return this.finishNode(node, "TSTypeQuery");
  7487. }
  7488. tsParseTypeParameter() {
  7489. const node = this.startNode();
  7490. node.name = this.tsParseTypeParameterName();
  7491. node.constraint = this.tsEatThenParseType(75);
  7492. node.default = this.tsEatThenParseType(27);
  7493. return this.finishNode(node, "TSTypeParameter");
  7494. }
  7495. tsTryParseTypeParameters() {
  7496. if (this.match(43)) {
  7497. return this.tsParseTypeParameters();
  7498. }
  7499. }
  7500. tsParseTypeParameters() {
  7501. const node = this.startNode();
  7502. if (this.match(43) || this.match(132)) {
  7503. this.next();
  7504. } else {
  7505. this.unexpected();
  7506. }
  7507. const refTrailingCommaPos = {
  7508. value: -1
  7509. };
  7510. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true, refTrailingCommaPos);
  7511. if (node.params.length === 0) {
  7512. this.raise(node.start, TSErrors.EmptyTypeParameters);
  7513. }
  7514. if (refTrailingCommaPos.value !== -1) {
  7515. this.addExtra(node, "trailingComma", refTrailingCommaPos.value);
  7516. }
  7517. return this.finishNode(node, "TSTypeParameterDeclaration");
  7518. }
  7519. tsTryNextParseConstantContext() {
  7520. if (this.lookahead().type === 69) {
  7521. this.next();
  7522. return this.tsParseTypeReference();
  7523. }
  7524. return null;
  7525. }
  7526. tsFillSignature(returnToken, signature) {
  7527. const returnTokenRequired = returnToken === 19;
  7528. signature.typeParameters = this.tsTryParseTypeParameters();
  7529. this.expect(10);
  7530. signature.parameters = this.tsParseBindingListForSignature();
  7531. if (returnTokenRequired) {
  7532. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  7533. } else if (this.match(returnToken)) {
  7534. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  7535. }
  7536. }
  7537. tsParseBindingListForSignature() {
  7538. return this.parseBindingList(11, 41).map(pattern => {
  7539. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  7540. this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type);
  7541. }
  7542. return pattern;
  7543. });
  7544. }
  7545. tsParseTypeMemberSemicolon() {
  7546. if (!this.eat(12) && !this.isLineTerminator()) {
  7547. this.expect(13);
  7548. }
  7549. }
  7550. tsParseSignatureMember(kind, node) {
  7551. this.tsFillSignature(14, node);
  7552. this.tsParseTypeMemberSemicolon();
  7553. return this.finishNode(node, kind);
  7554. }
  7555. tsIsUnambiguouslyIndexSignature() {
  7556. this.next();
  7557. if (tokenIsIdentifier(this.state.type)) {
  7558. this.next();
  7559. return this.match(14);
  7560. }
  7561. return false;
  7562. }
  7563. tsTryParseIndexSignature(node) {
  7564. if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  7565. return undefined;
  7566. }
  7567. this.expect(0);
  7568. const id = this.parseIdentifier();
  7569. id.typeAnnotation = this.tsParseTypeAnnotation();
  7570. this.resetEndLocation(id);
  7571. this.expect(3);
  7572. node.parameters = [id];
  7573. const type = this.tsTryParseTypeAnnotation();
  7574. if (type) node.typeAnnotation = type;
  7575. this.tsParseTypeMemberSemicolon();
  7576. return this.finishNode(node, "TSIndexSignature");
  7577. }
  7578. tsParsePropertyOrMethodSignature(node, readonly) {
  7579. if (this.eat(17)) node.optional = true;
  7580. const nodeAny = node;
  7581. if (this.match(10) || this.match(43)) {
  7582. if (readonly) {
  7583. this.raise(node.start, TSErrors.ReadonlyForMethodSignature);
  7584. }
  7585. const method = nodeAny;
  7586. if (method.kind && this.match(43)) {
  7587. this.raise(this.state.pos, TSErrors.AccesorCannotHaveTypeParameters);
  7588. }
  7589. this.tsFillSignature(14, method);
  7590. this.tsParseTypeMemberSemicolon();
  7591. if (method.kind === "get") {
  7592. if (method.parameters.length > 0) {
  7593. this.raise(this.state.pos, ErrorMessages.BadGetterArity);
  7594. if (this.isThisParam(method.parameters[0])) {
  7595. this.raise(this.state.pos, TSErrors.AccesorCannotDeclareThisParameter);
  7596. }
  7597. }
  7598. } else if (method.kind === "set") {
  7599. if (method.parameters.length !== 1) {
  7600. this.raise(this.state.pos, ErrorMessages.BadSetterArity);
  7601. } else {
  7602. const firstParameter = method.parameters[0];
  7603. if (this.isThisParam(firstParameter)) {
  7604. this.raise(this.state.pos, TSErrors.AccesorCannotDeclareThisParameter);
  7605. }
  7606. if (firstParameter.type === "Identifier" && firstParameter.optional) {
  7607. this.raise(this.state.pos, TSErrors.SetAccesorCannotHaveOptionalParameter);
  7608. }
  7609. if (firstParameter.type === "RestElement") {
  7610. this.raise(this.state.pos, TSErrors.SetAccesorCannotHaveRestParameter);
  7611. }
  7612. }
  7613. if (method.typeAnnotation) {
  7614. this.raise(method.typeAnnotation.start, TSErrors.SetAccesorCannotHaveReturnType);
  7615. }
  7616. } else {
  7617. method.kind = "method";
  7618. }
  7619. return this.finishNode(method, "TSMethodSignature");
  7620. } else {
  7621. const property = nodeAny;
  7622. if (readonly) property.readonly = true;
  7623. const type = this.tsTryParseTypeAnnotation();
  7624. if (type) property.typeAnnotation = type;
  7625. this.tsParseTypeMemberSemicolon();
  7626. return this.finishNode(property, "TSPropertySignature");
  7627. }
  7628. }
  7629. tsParseTypeMember() {
  7630. const node = this.startNode();
  7631. if (this.match(10) || this.match(43)) {
  7632. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  7633. }
  7634. if (this.match(71)) {
  7635. const id = this.startNode();
  7636. this.next();
  7637. if (this.match(10) || this.match(43)) {
  7638. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  7639. } else {
  7640. node.key = this.createIdentifier(id, "new");
  7641. return this.tsParsePropertyOrMethodSignature(node, false);
  7642. }
  7643. }
  7644. this.tsParseModifiers(node, ["readonly"], ["declare", "abstract", "private", "protected", "public", "static", "override"], TSErrors.InvalidModifierOnTypeMember);
  7645. const idx = this.tsTryParseIndexSignature(node);
  7646. if (idx) {
  7647. return idx;
  7648. }
  7649. this.parsePropertyName(node);
  7650. if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) {
  7651. node.kind = node.key.name;
  7652. this.parsePropertyName(node);
  7653. }
  7654. return this.tsParsePropertyOrMethodSignature(node, !!node.readonly);
  7655. }
  7656. tsParseTypeLiteral() {
  7657. const node = this.startNode();
  7658. node.members = this.tsParseObjectTypeMembers();
  7659. return this.finishNode(node, "TSTypeLiteral");
  7660. }
  7661. tsParseObjectTypeMembers() {
  7662. this.expect(5);
  7663. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  7664. this.expect(8);
  7665. return members;
  7666. }
  7667. tsIsStartOfMappedType() {
  7668. this.next();
  7669. if (this.eat(47)) {
  7670. return this.isContextual(112);
  7671. }
  7672. if (this.isContextual(112)) {
  7673. this.next();
  7674. }
  7675. if (!this.match(0)) {
  7676. return false;
  7677. }
  7678. this.next();
  7679. if (!this.tsIsIdentifier()) {
  7680. return false;
  7681. }
  7682. this.next();
  7683. return this.match(52);
  7684. }
  7685. tsParseMappedTypeParameter() {
  7686. const node = this.startNode();
  7687. node.name = this.tsParseTypeParameterName();
  7688. node.constraint = this.tsExpectThenParseType(52);
  7689. return this.finishNode(node, "TSTypeParameter");
  7690. }
  7691. tsParseMappedType() {
  7692. const node = this.startNode();
  7693. this.expect(5);
  7694. if (this.match(47)) {
  7695. node.readonly = this.state.value;
  7696. this.next();
  7697. this.expectContextual(112);
  7698. } else if (this.eatContextual(112)) {
  7699. node.readonly = true;
  7700. }
  7701. this.expect(0);
  7702. node.typeParameter = this.tsParseMappedTypeParameter();
  7703. node.nameType = this.eatContextual(87) ? this.tsParseType() : null;
  7704. this.expect(3);
  7705. if (this.match(47)) {
  7706. node.optional = this.state.value;
  7707. this.next();
  7708. this.expect(17);
  7709. } else if (this.eat(17)) {
  7710. node.optional = true;
  7711. }
  7712. node.typeAnnotation = this.tsTryParseType();
  7713. this.semicolon();
  7714. this.expect(8);
  7715. return this.finishNode(node, "TSMappedType");
  7716. }
  7717. tsParseTupleType() {
  7718. const node = this.startNode();
  7719. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  7720. let seenOptionalElement = false;
  7721. let labeledElements = null;
  7722. node.elementTypes.forEach(elementNode => {
  7723. var _labeledElements;
  7724. let {
  7725. type
  7726. } = elementNode;
  7727. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  7728. this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired);
  7729. }
  7730. seenOptionalElement = seenOptionalElement || type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType";
  7731. if (type === "TSRestType") {
  7732. elementNode = elementNode.typeAnnotation;
  7733. type = elementNode.type;
  7734. }
  7735. const isLabeled = type === "TSNamedTupleMember";
  7736. labeledElements = (_labeledElements = labeledElements) != null ? _labeledElements : isLabeled;
  7737. if (labeledElements !== isLabeled) {
  7738. this.raise(elementNode.start, TSErrors.MixedLabeledAndUnlabeledElements);
  7739. }
  7740. });
  7741. return this.finishNode(node, "TSTupleType");
  7742. }
  7743. tsParseTupleElementType() {
  7744. const {
  7745. start: startPos,
  7746. startLoc
  7747. } = this.state;
  7748. const rest = this.eat(21);
  7749. let type = this.tsParseType();
  7750. const optional = this.eat(17);
  7751. const labeled = this.eat(14);
  7752. if (labeled) {
  7753. const labeledNode = this.startNodeAtNode(type);
  7754. labeledNode.optional = optional;
  7755. if (type.type === "TSTypeReference" && !type.typeParameters && type.typeName.type === "Identifier") {
  7756. labeledNode.label = type.typeName;
  7757. } else {
  7758. this.raise(type.start, TSErrors.InvalidTupleMemberLabel);
  7759. labeledNode.label = type;
  7760. }
  7761. labeledNode.elementType = this.tsParseType();
  7762. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  7763. } else if (optional) {
  7764. const optionalTypeNode = this.startNodeAtNode(type);
  7765. optionalTypeNode.typeAnnotation = type;
  7766. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  7767. }
  7768. if (rest) {
  7769. const restNode = this.startNodeAt(startPos, startLoc);
  7770. restNode.typeAnnotation = type;
  7771. type = this.finishNode(restNode, "TSRestType");
  7772. }
  7773. return type;
  7774. }
  7775. tsParseParenthesizedType() {
  7776. const node = this.startNode();
  7777. this.expect(10);
  7778. node.typeAnnotation = this.tsParseType();
  7779. this.expect(11);
  7780. return this.finishNode(node, "TSParenthesizedType");
  7781. }
  7782. tsParseFunctionOrConstructorType(type, abstract) {
  7783. const node = this.startNode();
  7784. if (type === "TSConstructorType") {
  7785. node.abstract = !!abstract;
  7786. if (abstract) this.next();
  7787. this.next();
  7788. }
  7789. this.tsFillSignature(19, node);
  7790. return this.finishNode(node, type);
  7791. }
  7792. tsParseLiteralTypeNode() {
  7793. const node = this.startNode();
  7794. node.literal = (() => {
  7795. switch (this.state.type) {
  7796. case 124:
  7797. case 125:
  7798. case 123:
  7799. case 79:
  7800. case 80:
  7801. return this.parseExprAtom();
  7802. default:
  7803. throw this.unexpected();
  7804. }
  7805. })();
  7806. return this.finishNode(node, "TSLiteralType");
  7807. }
  7808. tsParseTemplateLiteralType() {
  7809. const node = this.startNode();
  7810. node.literal = this.parseTemplate(false);
  7811. return this.finishNode(node, "TSLiteralType");
  7812. }
  7813. parseTemplateSubstitution() {
  7814. if (this.state.inType) return this.tsParseType();
  7815. return super.parseTemplateSubstitution();
  7816. }
  7817. tsParseThisTypeOrThisTypePredicate() {
  7818. const thisKeyword = this.tsParseThisTypeNode();
  7819. if (this.isContextual(107) && !this.hasPrecedingLineBreak()) {
  7820. return this.tsParseThisTypePredicate(thisKeyword);
  7821. } else {
  7822. return thisKeyword;
  7823. }
  7824. }
  7825. tsParseNonArrayType() {
  7826. switch (this.state.type) {
  7827. case 123:
  7828. case 124:
  7829. case 125:
  7830. case 79:
  7831. case 80:
  7832. return this.tsParseLiteralTypeNode();
  7833. case 47:
  7834. if (this.state.value === "-") {
  7835. const node = this.startNode();
  7836. const nextToken = this.lookahead();
  7837. if (nextToken.type !== 124 && nextToken.type !== 125) {
  7838. throw this.unexpected();
  7839. }
  7840. node.literal = this.parseMaybeUnary();
  7841. return this.finishNode(node, "TSLiteralType");
  7842. }
  7843. break;
  7844. case 72:
  7845. return this.tsParseThisTypeOrThisTypePredicate();
  7846. case 81:
  7847. return this.tsParseTypeQuery();
  7848. case 77:
  7849. return this.tsParseImportType();
  7850. case 5:
  7851. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  7852. case 0:
  7853. return this.tsParseTupleType();
  7854. case 10:
  7855. return this.tsParseParenthesizedType();
  7856. case 22:
  7857. return this.tsParseTemplateLiteralType();
  7858. default:
  7859. {
  7860. const {
  7861. type
  7862. } = this.state;
  7863. if (tokenIsIdentifier(type) || type === 82 || type === 78) {
  7864. const nodeType = type === 82 ? "TSVoidKeyword" : type === 78 ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  7865. if (nodeType !== undefined && this.lookaheadCharCode() !== 46) {
  7866. const node = this.startNode();
  7867. this.next();
  7868. return this.finishNode(node, nodeType);
  7869. }
  7870. return this.tsParseTypeReference();
  7871. }
  7872. }
  7873. }
  7874. throw this.unexpected();
  7875. }
  7876. tsParseArrayTypeOrHigher() {
  7877. let type = this.tsParseNonArrayType();
  7878. while (!this.hasPrecedingLineBreak() && this.eat(0)) {
  7879. if (this.match(3)) {
  7880. const node = this.startNodeAtNode(type);
  7881. node.elementType = type;
  7882. this.expect(3);
  7883. type = this.finishNode(node, "TSArrayType");
  7884. } else {
  7885. const node = this.startNodeAtNode(type);
  7886. node.objectType = type;
  7887. node.indexType = this.tsParseType();
  7888. this.expect(3);
  7889. type = this.finishNode(node, "TSIndexedAccessType");
  7890. }
  7891. }
  7892. return type;
  7893. }
  7894. tsParseTypeOperator() {
  7895. const node = this.startNode();
  7896. const operator = this.state.value;
  7897. this.next();
  7898. node.operator = operator;
  7899. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  7900. if (operator === "readonly") {
  7901. this.tsCheckTypeAnnotationForReadOnly(node);
  7902. }
  7903. return this.finishNode(node, "TSTypeOperator");
  7904. }
  7905. tsCheckTypeAnnotationForReadOnly(node) {
  7906. switch (node.typeAnnotation.type) {
  7907. case "TSTupleType":
  7908. case "TSArrayType":
  7909. return;
  7910. default:
  7911. this.raise(node.start, TSErrors.UnexpectedReadonly);
  7912. }
  7913. }
  7914. tsParseInferType() {
  7915. const node = this.startNode();
  7916. this.expectContextual(106);
  7917. const typeParameter = this.startNode();
  7918. typeParameter.name = this.tsParseTypeParameterName();
  7919. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  7920. return this.finishNode(node, "TSInferType");
  7921. }
  7922. tsParseTypeOperatorOrHigher() {
  7923. const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc;
  7924. return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(106) ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  7925. }
  7926. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  7927. const node = this.startNode();
  7928. const hasLeadingOperator = this.eat(operator);
  7929. const types = [];
  7930. do {
  7931. types.push(parseConstituentType());
  7932. } while (this.eat(operator));
  7933. if (types.length === 1 && !hasLeadingOperator) {
  7934. return types[0];
  7935. }
  7936. node.types = types;
  7937. return this.finishNode(node, kind);
  7938. }
  7939. tsParseIntersectionTypeOrHigher() {
  7940. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 41);
  7941. }
  7942. tsParseUnionTypeOrHigher() {
  7943. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 39);
  7944. }
  7945. tsIsStartOfFunctionType() {
  7946. if (this.match(43)) {
  7947. return true;
  7948. }
  7949. return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  7950. }
  7951. tsSkipParameterStart() {
  7952. if (tokenIsIdentifier(this.state.type) || this.match(72)) {
  7953. this.next();
  7954. return true;
  7955. }
  7956. if (this.match(5)) {
  7957. let braceStackCounter = 1;
  7958. this.next();
  7959. while (braceStackCounter > 0) {
  7960. if (this.match(5)) {
  7961. ++braceStackCounter;
  7962. } else if (this.match(8)) {
  7963. --braceStackCounter;
  7964. }
  7965. this.next();
  7966. }
  7967. return true;
  7968. }
  7969. if (this.match(0)) {
  7970. let braceStackCounter = 1;
  7971. this.next();
  7972. while (braceStackCounter > 0) {
  7973. if (this.match(0)) {
  7974. ++braceStackCounter;
  7975. } else if (this.match(3)) {
  7976. --braceStackCounter;
  7977. }
  7978. this.next();
  7979. }
  7980. return true;
  7981. }
  7982. return false;
  7983. }
  7984. tsIsUnambiguouslyStartOfFunctionType() {
  7985. this.next();
  7986. if (this.match(11) || this.match(21)) {
  7987. return true;
  7988. }
  7989. if (this.tsSkipParameterStart()) {
  7990. if (this.match(14) || this.match(12) || this.match(17) || this.match(27)) {
  7991. return true;
  7992. }
  7993. if (this.match(11)) {
  7994. this.next();
  7995. if (this.match(19)) {
  7996. return true;
  7997. }
  7998. }
  7999. }
  8000. return false;
  8001. }
  8002. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  8003. return this.tsInType(() => {
  8004. const t = this.startNode();
  8005. this.expect(returnToken);
  8006. const node = this.startNode();
  8007. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  8008. if (asserts && this.match(72)) {
  8009. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  8010. if (thisTypePredicate.type === "TSThisType") {
  8011. node.parameterName = thisTypePredicate;
  8012. node.asserts = true;
  8013. node.typeAnnotation = null;
  8014. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  8015. } else {
  8016. this.resetStartLocationFromNode(thisTypePredicate, node);
  8017. thisTypePredicate.asserts = true;
  8018. }
  8019. t.typeAnnotation = thisTypePredicate;
  8020. return this.finishNode(t, "TSTypeAnnotation");
  8021. }
  8022. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  8023. if (!typePredicateVariable) {
  8024. if (!asserts) {
  8025. return this.tsParseTypeAnnotation(false, t);
  8026. }
  8027. node.parameterName = this.parseIdentifier();
  8028. node.asserts = asserts;
  8029. node.typeAnnotation = null;
  8030. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  8031. return this.finishNode(t, "TSTypeAnnotation");
  8032. }
  8033. const type = this.tsParseTypeAnnotation(false);
  8034. node.parameterName = typePredicateVariable;
  8035. node.typeAnnotation = type;
  8036. node.asserts = asserts;
  8037. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  8038. return this.finishNode(t, "TSTypeAnnotation");
  8039. });
  8040. }
  8041. tsTryParseTypeOrTypePredicateAnnotation() {
  8042. return this.match(14) ? this.tsParseTypeOrTypePredicateAnnotation(14) : undefined;
  8043. }
  8044. tsTryParseTypeAnnotation() {
  8045. return this.match(14) ? this.tsParseTypeAnnotation() : undefined;
  8046. }
  8047. tsTryParseType() {
  8048. return this.tsEatThenParseType(14);
  8049. }
  8050. tsParseTypePredicatePrefix() {
  8051. const id = this.parseIdentifier();
  8052. if (this.isContextual(107) && !this.hasPrecedingLineBreak()) {
  8053. this.next();
  8054. return id;
  8055. }
  8056. }
  8057. tsParseTypePredicateAsserts() {
  8058. if (this.state.type !== 100) {
  8059. return false;
  8060. }
  8061. const containsEsc = this.state.containsEsc;
  8062. this.next();
  8063. if (!tokenIsIdentifier(this.state.type) && !this.match(72)) {
  8064. return false;
  8065. }
  8066. if (containsEsc) {
  8067. this.raise(this.state.lastTokStart, ErrorMessages.InvalidEscapedReservedWord, "asserts");
  8068. }
  8069. return true;
  8070. }
  8071. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  8072. this.tsInType(() => {
  8073. if (eatColon) this.expect(14);
  8074. t.typeAnnotation = this.tsParseType();
  8075. });
  8076. return this.finishNode(t, "TSTypeAnnotation");
  8077. }
  8078. tsParseType() {
  8079. assert$1(this.state.inType);
  8080. const type = this.tsParseNonConditionalType();
  8081. if (this.hasPrecedingLineBreak() || !this.eat(75)) {
  8082. return type;
  8083. }
  8084. const node = this.startNodeAtNode(type);
  8085. node.checkType = type;
  8086. node.extendsType = this.tsParseNonConditionalType();
  8087. this.expect(17);
  8088. node.trueType = this.tsParseType();
  8089. this.expect(14);
  8090. node.falseType = this.tsParseType();
  8091. return this.finishNode(node, "TSConditionalType");
  8092. }
  8093. isAbstractConstructorSignature() {
  8094. return this.isContextual(114) && this.lookahead().type === 71;
  8095. }
  8096. tsParseNonConditionalType() {
  8097. if (this.tsIsStartOfFunctionType()) {
  8098. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  8099. }
  8100. if (this.match(71)) {
  8101. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  8102. } else if (this.isAbstractConstructorSignature()) {
  8103. return this.tsParseFunctionOrConstructorType("TSConstructorType", true);
  8104. }
  8105. return this.tsParseUnionTypeOrHigher();
  8106. }
  8107. tsParseTypeAssertion() {
  8108. if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  8109. this.raise(this.state.start, TSErrors.ReservedTypeAssertion);
  8110. }
  8111. const node = this.startNode();
  8112. const _const = this.tsTryNextParseConstantContext();
  8113. node.typeAnnotation = _const || this.tsNextThenParseType();
  8114. this.expect(44);
  8115. node.expression = this.parseMaybeUnary();
  8116. return this.finishNode(node, "TSTypeAssertion");
  8117. }
  8118. tsParseHeritageClause(descriptor) {
  8119. const originalStart = this.state.start;
  8120. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  8121. if (!delimitedList.length) {
  8122. this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor);
  8123. }
  8124. return delimitedList;
  8125. }
  8126. tsParseExpressionWithTypeArguments() {
  8127. const node = this.startNode();
  8128. node.expression = this.tsParseEntityName(false);
  8129. if (this.match(43)) {
  8130. node.typeParameters = this.tsParseTypeArguments();
  8131. }
  8132. return this.finishNode(node, "TSExpressionWithTypeArguments");
  8133. }
  8134. tsParseInterfaceDeclaration(node) {
  8135. if (tokenIsIdentifier(this.state.type)) {
  8136. node.id = this.parseIdentifier();
  8137. this.checkLVal(node.id, "typescript interface declaration", BIND_TS_INTERFACE);
  8138. } else {
  8139. node.id = null;
  8140. this.raise(this.state.start, TSErrors.MissingInterfaceName);
  8141. }
  8142. node.typeParameters = this.tsTryParseTypeParameters();
  8143. if (this.eat(75)) {
  8144. node.extends = this.tsParseHeritageClause("extends");
  8145. }
  8146. const body = this.startNode();
  8147. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  8148. node.body = this.finishNode(body, "TSInterfaceBody");
  8149. return this.finishNode(node, "TSInterfaceDeclaration");
  8150. }
  8151. tsParseTypeAliasDeclaration(node) {
  8152. node.id = this.parseIdentifier();
  8153. this.checkLVal(node.id, "typescript type alias", BIND_TS_TYPE);
  8154. node.typeParameters = this.tsTryParseTypeParameters();
  8155. node.typeAnnotation = this.tsInType(() => {
  8156. this.expect(27);
  8157. if (this.isContextual(105) && this.lookahead().type !== 16) {
  8158. const node = this.startNode();
  8159. this.next();
  8160. return this.finishNode(node, "TSIntrinsicKeyword");
  8161. }
  8162. return this.tsParseType();
  8163. });
  8164. this.semicolon();
  8165. return this.finishNode(node, "TSTypeAliasDeclaration");
  8166. }
  8167. tsInNoContext(cb) {
  8168. const oldContext = this.state.context;
  8169. this.state.context = [oldContext[0]];
  8170. try {
  8171. return cb();
  8172. } finally {
  8173. this.state.context = oldContext;
  8174. }
  8175. }
  8176. tsInType(cb) {
  8177. const oldInType = this.state.inType;
  8178. this.state.inType = true;
  8179. try {
  8180. return cb();
  8181. } finally {
  8182. this.state.inType = oldInType;
  8183. }
  8184. }
  8185. tsEatThenParseType(token) {
  8186. return !this.match(token) ? undefined : this.tsNextThenParseType();
  8187. }
  8188. tsExpectThenParseType(token) {
  8189. return this.tsDoThenParseType(() => this.expect(token));
  8190. }
  8191. tsNextThenParseType() {
  8192. return this.tsDoThenParseType(() => this.next());
  8193. }
  8194. tsDoThenParseType(cb) {
  8195. return this.tsInType(() => {
  8196. cb();
  8197. return this.tsParseType();
  8198. });
  8199. }
  8200. tsParseEnumMember() {
  8201. const node = this.startNode();
  8202. node.id = this.match(123) ? this.parseExprAtom() : this.parseIdentifier(true);
  8203. if (this.eat(27)) {
  8204. node.initializer = this.parseMaybeAssignAllowIn();
  8205. }
  8206. return this.finishNode(node, "TSEnumMember");
  8207. }
  8208. tsParseEnumDeclaration(node, isConst) {
  8209. if (isConst) node.const = true;
  8210. node.id = this.parseIdentifier();
  8211. this.checkLVal(node.id, "typescript enum declaration", isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM);
  8212. this.expect(5);
  8213. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  8214. this.expect(8);
  8215. return this.finishNode(node, "TSEnumDeclaration");
  8216. }
  8217. tsParseModuleBlock() {
  8218. const node = this.startNode();
  8219. this.scope.enter(SCOPE_OTHER);
  8220. this.expect(5);
  8221. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8);
  8222. this.scope.exit();
  8223. return this.finishNode(node, "TSModuleBlock");
  8224. }
  8225. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  8226. node.id = this.parseIdentifier();
  8227. if (!nested) {
  8228. this.checkLVal(node.id, "module or namespace declaration", BIND_TS_NAMESPACE);
  8229. }
  8230. if (this.eat(16)) {
  8231. const inner = this.startNode();
  8232. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  8233. node.body = inner;
  8234. } else {
  8235. this.scope.enter(SCOPE_TS_MODULE);
  8236. this.prodParam.enter(PARAM);
  8237. node.body = this.tsParseModuleBlock();
  8238. this.prodParam.exit();
  8239. this.scope.exit();
  8240. }
  8241. return this.finishNode(node, "TSModuleDeclaration");
  8242. }
  8243. tsParseAmbientExternalModuleDeclaration(node) {
  8244. if (this.isContextual(103)) {
  8245. node.global = true;
  8246. node.id = this.parseIdentifier();
  8247. } else if (this.match(123)) {
  8248. node.id = this.parseExprAtom();
  8249. } else {
  8250. this.unexpected();
  8251. }
  8252. if (this.match(5)) {
  8253. this.scope.enter(SCOPE_TS_MODULE);
  8254. this.prodParam.enter(PARAM);
  8255. node.body = this.tsParseModuleBlock();
  8256. this.prodParam.exit();
  8257. this.scope.exit();
  8258. } else {
  8259. this.semicolon();
  8260. }
  8261. return this.finishNode(node, "TSModuleDeclaration");
  8262. }
  8263. tsParseImportEqualsDeclaration(node, isExport) {
  8264. node.isExport = isExport || false;
  8265. node.id = this.parseIdentifier();
  8266. this.checkLVal(node.id, "import equals declaration", BIND_LEXICAL);
  8267. this.expect(27);
  8268. const moduleReference = this.tsParseModuleReference();
  8269. if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
  8270. this.raise(moduleReference.start, TSErrors.ImportAliasHasImportType);
  8271. }
  8272. node.moduleReference = moduleReference;
  8273. this.semicolon();
  8274. return this.finishNode(node, "TSImportEqualsDeclaration");
  8275. }
  8276. tsIsExternalModuleReference() {
  8277. return this.isContextual(110) && this.lookaheadCharCode() === 40;
  8278. }
  8279. tsParseModuleReference() {
  8280. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  8281. }
  8282. tsParseExternalModuleReference() {
  8283. const node = this.startNode();
  8284. this.expectContextual(110);
  8285. this.expect(10);
  8286. if (!this.match(123)) {
  8287. throw this.unexpected();
  8288. }
  8289. node.expression = this.parseExprAtom();
  8290. this.expect(11);
  8291. return this.finishNode(node, "TSExternalModuleReference");
  8292. }
  8293. tsLookAhead(f) {
  8294. const state = this.state.clone();
  8295. const res = f();
  8296. this.state = state;
  8297. return res;
  8298. }
  8299. tsTryParseAndCatch(f) {
  8300. const result = this.tryParse(abort => f() || abort());
  8301. if (result.aborted || !result.node) return undefined;
  8302. if (result.error) this.state = result.failState;
  8303. return result.node;
  8304. }
  8305. tsTryParse(f) {
  8306. const state = this.state.clone();
  8307. const result = f();
  8308. if (result !== undefined && result !== false) {
  8309. return result;
  8310. } else {
  8311. this.state = state;
  8312. return undefined;
  8313. }
  8314. }
  8315. tsTryParseDeclare(nany) {
  8316. if (this.isLineTerminator()) {
  8317. return;
  8318. }
  8319. let starttype = this.state.type;
  8320. let kind;
  8321. if (this.isContextual(93)) {
  8322. starttype = 68;
  8323. kind = "let";
  8324. }
  8325. return this.tsInAmbientContext(() => {
  8326. switch (starttype) {
  8327. case 62:
  8328. nany.declare = true;
  8329. return this.parseFunctionStatement(nany, false, true);
  8330. case 74:
  8331. nany.declare = true;
  8332. return this.parseClass(nany, true, false);
  8333. case 69:
  8334. if (this.match(69) && this.isLookaheadContextual("enum")) {
  8335. this.expect(69);
  8336. this.expectContextual(116);
  8337. return this.tsParseEnumDeclaration(nany, true);
  8338. }
  8339. case 68:
  8340. kind = kind || this.state.value;
  8341. return this.parseVarStatement(nany, kind);
  8342. case 103:
  8343. return this.tsParseAmbientExternalModuleDeclaration(nany);
  8344. default:
  8345. {
  8346. if (tokenIsIdentifier(starttype)) {
  8347. return this.tsParseDeclaration(nany, this.state.value, true);
  8348. }
  8349. }
  8350. }
  8351. });
  8352. }
  8353. tsTryParseExportDeclaration() {
  8354. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  8355. }
  8356. tsParseExpressionStatement(node, expr) {
  8357. switch (expr.name) {
  8358. case "declare":
  8359. {
  8360. const declaration = this.tsTryParseDeclare(node);
  8361. if (declaration) {
  8362. declaration.declare = true;
  8363. return declaration;
  8364. }
  8365. break;
  8366. }
  8367. case "global":
  8368. if (this.match(5)) {
  8369. this.scope.enter(SCOPE_TS_MODULE);
  8370. this.prodParam.enter(PARAM);
  8371. const mod = node;
  8372. mod.global = true;
  8373. mod.id = expr;
  8374. mod.body = this.tsParseModuleBlock();
  8375. this.scope.exit();
  8376. this.prodParam.exit();
  8377. return this.finishNode(mod, "TSModuleDeclaration");
  8378. }
  8379. break;
  8380. default:
  8381. return this.tsParseDeclaration(node, expr.name, false);
  8382. }
  8383. }
  8384. tsParseDeclaration(node, value, next) {
  8385. switch (value) {
  8386. case "abstract":
  8387. if (this.tsCheckLineTerminator(next) && (this.match(74) || tokenIsIdentifier(this.state.type))) {
  8388. return this.tsParseAbstractDeclaration(node);
  8389. }
  8390. break;
  8391. case "enum":
  8392. if (next || tokenIsIdentifier(this.state.type)) {
  8393. if (next) this.next();
  8394. return this.tsParseEnumDeclaration(node, false);
  8395. }
  8396. break;
  8397. case "interface":
  8398. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8399. return this.tsParseInterfaceDeclaration(node);
  8400. }
  8401. break;
  8402. case "module":
  8403. if (this.tsCheckLineTerminator(next)) {
  8404. if (this.match(123)) {
  8405. return this.tsParseAmbientExternalModuleDeclaration(node);
  8406. } else if (tokenIsIdentifier(this.state.type)) {
  8407. return this.tsParseModuleOrNamespaceDeclaration(node);
  8408. }
  8409. }
  8410. break;
  8411. case "namespace":
  8412. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8413. return this.tsParseModuleOrNamespaceDeclaration(node);
  8414. }
  8415. break;
  8416. case "type":
  8417. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8418. return this.tsParseTypeAliasDeclaration(node);
  8419. }
  8420. break;
  8421. }
  8422. }
  8423. tsCheckLineTerminator(next) {
  8424. if (next) {
  8425. if (this.hasFollowingLineBreak()) return false;
  8426. this.next();
  8427. return true;
  8428. }
  8429. return !this.isLineTerminator();
  8430. }
  8431. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  8432. if (!this.match(43)) {
  8433. return undefined;
  8434. }
  8435. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8436. this.state.maybeInArrowParameters = true;
  8437. const res = this.tsTryParseAndCatch(() => {
  8438. const node = this.startNodeAt(startPos, startLoc);
  8439. node.typeParameters = this.tsParseTypeParameters();
  8440. super.parseFunctionParams(node);
  8441. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  8442. this.expect(19);
  8443. return node;
  8444. });
  8445. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8446. if (!res) {
  8447. return undefined;
  8448. }
  8449. return this.parseArrowExpression(res, null, true);
  8450. }
  8451. tsParseTypeArguments() {
  8452. const node = this.startNode();
  8453. node.params = this.tsInType(() => this.tsInNoContext(() => {
  8454. this.expect(43);
  8455. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  8456. }));
  8457. if (node.params.length === 0) {
  8458. this.raise(node.start, TSErrors.EmptyTypeArguments);
  8459. }
  8460. this.expect(44);
  8461. return this.finishNode(node, "TSTypeParameterInstantiation");
  8462. }
  8463. tsIsDeclarationStart() {
  8464. return tokenIsTSDeclarationStart(this.state.type);
  8465. }
  8466. isExportDefaultSpecifier() {
  8467. if (this.tsIsDeclarationStart()) return false;
  8468. return super.isExportDefaultSpecifier();
  8469. }
  8470. parseAssignableListItem(allowModifiers, decorators) {
  8471. const startPos = this.state.start;
  8472. const startLoc = this.state.startLoc;
  8473. let accessibility;
  8474. let readonly = false;
  8475. let override = false;
  8476. if (allowModifiers !== undefined) {
  8477. const modified = {};
  8478. this.tsParseModifiers(modified, ["public", "private", "protected", "override", "readonly"]);
  8479. accessibility = modified.accessibility;
  8480. override = modified.override;
  8481. readonly = modified.readonly;
  8482. if (allowModifiers === false && (accessibility || readonly || override)) {
  8483. this.raise(startPos, TSErrors.UnexpectedParameterModifier);
  8484. }
  8485. }
  8486. const left = this.parseMaybeDefault();
  8487. this.parseAssignableListItemTypes(left);
  8488. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  8489. if (accessibility || readonly || override) {
  8490. const pp = this.startNodeAt(startPos, startLoc);
  8491. if (decorators.length) {
  8492. pp.decorators = decorators;
  8493. }
  8494. if (accessibility) pp.accessibility = accessibility;
  8495. if (readonly) pp.readonly = readonly;
  8496. if (override) pp.override = override;
  8497. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  8498. this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind);
  8499. }
  8500. pp.parameter = elt;
  8501. return this.finishNode(pp, "TSParameterProperty");
  8502. }
  8503. if (decorators.length) {
  8504. left.decorators = decorators;
  8505. }
  8506. return elt;
  8507. }
  8508. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  8509. if (this.match(14)) {
  8510. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  8511. }
  8512. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : undefined;
  8513. if (bodilessType && !this.match(5) && this.isLineTerminator()) {
  8514. this.finishNode(node, bodilessType);
  8515. return;
  8516. }
  8517. if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) {
  8518. this.raise(node.start, TSErrors.DeclareFunctionHasImplementation);
  8519. if (node.declare) {
  8520. super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  8521. return;
  8522. }
  8523. }
  8524. super.parseFunctionBodyAndFinish(node, type, isMethod);
  8525. }
  8526. registerFunctionStatementId(node) {
  8527. if (!node.body && node.id) {
  8528. this.checkLVal(node.id, "function name", BIND_TS_AMBIENT);
  8529. } else {
  8530. super.registerFunctionStatementId(...arguments);
  8531. }
  8532. }
  8533. tsCheckForInvalidTypeCasts(items) {
  8534. items.forEach(node => {
  8535. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  8536. this.raise(node.typeAnnotation.start, TSErrors.UnexpectedTypeAnnotation);
  8537. }
  8538. });
  8539. }
  8540. toReferencedList(exprList, isInParens) {
  8541. this.tsCheckForInvalidTypeCasts(exprList);
  8542. return exprList;
  8543. }
  8544. parseArrayLike(...args) {
  8545. const node = super.parseArrayLike(...args);
  8546. if (node.type === "ArrayExpression") {
  8547. this.tsCheckForInvalidTypeCasts(node.elements);
  8548. }
  8549. return node;
  8550. }
  8551. parseSubscript(base, startPos, startLoc, noCalls, state) {
  8552. if (!this.hasPrecedingLineBreak() && this.match(33)) {
  8553. this.state.canStartJSXElement = false;
  8554. this.next();
  8555. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  8556. nonNullExpression.expression = base;
  8557. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  8558. }
  8559. let isOptionalCall = false;
  8560. if (this.match(18) && this.lookaheadCharCode() === 60) {
  8561. if (noCalls) {
  8562. state.stop = true;
  8563. return base;
  8564. }
  8565. state.optionalChainMember = isOptionalCall = true;
  8566. this.next();
  8567. }
  8568. if (this.match(43)) {
  8569. let missingParenErrorPos;
  8570. const result = this.tsTryParseAndCatch(() => {
  8571. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  8572. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  8573. if (asyncArrowFn) {
  8574. return asyncArrowFn;
  8575. }
  8576. }
  8577. const node = this.startNodeAt(startPos, startLoc);
  8578. node.callee = base;
  8579. const typeArguments = this.tsParseTypeArguments();
  8580. if (typeArguments) {
  8581. if (isOptionalCall && !this.match(10)) {
  8582. missingParenErrorPos = this.state.pos;
  8583. this.unexpected();
  8584. }
  8585. if (!noCalls && this.eat(10)) {
  8586. node.arguments = this.parseCallExpressionArguments(11, false);
  8587. this.tsCheckForInvalidTypeCasts(node.arguments);
  8588. node.typeParameters = typeArguments;
  8589. if (state.optionalChainMember) {
  8590. node.optional = isOptionalCall;
  8591. }
  8592. return this.finishCallExpression(node, state.optionalChainMember);
  8593. } else if (this.match(22)) {
  8594. const result = this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  8595. result.typeParameters = typeArguments;
  8596. return result;
  8597. }
  8598. }
  8599. this.unexpected();
  8600. });
  8601. if (missingParenErrorPos) {
  8602. this.unexpected(missingParenErrorPos, 10);
  8603. }
  8604. if (result) return result;
  8605. }
  8606. return super.parseSubscript(base, startPos, startLoc, noCalls, state);
  8607. }
  8608. parseNewArguments(node) {
  8609. if (this.match(43)) {
  8610. const typeParameters = this.tsTryParseAndCatch(() => {
  8611. const args = this.tsParseTypeArguments();
  8612. if (!this.match(10)) this.unexpected();
  8613. return args;
  8614. });
  8615. if (typeParameters) {
  8616. node.typeParameters = typeParameters;
  8617. }
  8618. }
  8619. super.parseNewArguments(node);
  8620. }
  8621. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  8622. if (tokenOperatorPrecedence(52) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual(87)) {
  8623. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  8624. node.expression = left;
  8625. const _const = this.tsTryNextParseConstantContext();
  8626. if (_const) {
  8627. node.typeAnnotation = _const;
  8628. } else {
  8629. node.typeAnnotation = this.tsNextThenParseType();
  8630. }
  8631. this.finishNode(node, "TSAsExpression");
  8632. this.reScan_lt_gt();
  8633. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  8634. }
  8635. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec);
  8636. }
  8637. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  8638. checkDuplicateExports() {}
  8639. parseImport(node) {
  8640. node.importKind = "value";
  8641. if (tokenIsIdentifier(this.state.type) || this.match(49) || this.match(5)) {
  8642. let ahead = this.lookahead();
  8643. if (this.isContextual(120) && ahead.type !== 12 && ahead.type !== 91 && ahead.type !== 27) {
  8644. node.importKind = "type";
  8645. this.next();
  8646. ahead = this.lookahead();
  8647. }
  8648. if (tokenIsIdentifier(this.state.type) && ahead.type === 27) {
  8649. return this.tsParseImportEqualsDeclaration(node);
  8650. }
  8651. }
  8652. const importNode = super.parseImport(node);
  8653. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  8654. this.raise(importNode.start, TSErrors.TypeImportCannotSpecifyDefaultAndNamed);
  8655. }
  8656. return importNode;
  8657. }
  8658. parseExport(node) {
  8659. if (this.match(77)) {
  8660. this.next();
  8661. if (this.isContextual(120) && this.lookaheadCharCode() !== 61) {
  8662. node.importKind = "type";
  8663. this.next();
  8664. } else {
  8665. node.importKind = "value";
  8666. }
  8667. return this.tsParseImportEqualsDeclaration(node, true);
  8668. } else if (this.eat(27)) {
  8669. const assign = node;
  8670. assign.expression = this.parseExpression();
  8671. this.semicolon();
  8672. return this.finishNode(assign, "TSExportAssignment");
  8673. } else if (this.eatContextual(87)) {
  8674. const decl = node;
  8675. this.expectContextual(118);
  8676. decl.id = this.parseIdentifier();
  8677. this.semicolon();
  8678. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  8679. } else {
  8680. if (this.isContextual(120) && this.lookahead().type === 5) {
  8681. this.next();
  8682. node.exportKind = "type";
  8683. } else {
  8684. node.exportKind = "value";
  8685. }
  8686. return super.parseExport(node);
  8687. }
  8688. }
  8689. isAbstractClass() {
  8690. return this.isContextual(114) && this.lookahead().type === 74;
  8691. }
  8692. parseExportDefaultExpression() {
  8693. if (this.isAbstractClass()) {
  8694. const cls = this.startNode();
  8695. this.next();
  8696. cls.abstract = true;
  8697. this.parseClass(cls, true, true);
  8698. return cls;
  8699. }
  8700. if (this.match(119)) {
  8701. const interfaceNode = this.startNode();
  8702. this.next();
  8703. const result = this.tsParseInterfaceDeclaration(interfaceNode);
  8704. if (result) return result;
  8705. }
  8706. return super.parseExportDefaultExpression();
  8707. }
  8708. parseStatementContent(context, topLevel) {
  8709. if (this.state.type === 69) {
  8710. const ahead = this.lookahead();
  8711. if (ahead.type === 116) {
  8712. const node = this.startNode();
  8713. this.next();
  8714. this.expectContextual(116);
  8715. return this.tsParseEnumDeclaration(node, true);
  8716. }
  8717. }
  8718. return super.parseStatementContent(context, topLevel);
  8719. }
  8720. parseAccessModifier() {
  8721. return this.tsParseModifier(["public", "protected", "private"]);
  8722. }
  8723. tsHasSomeModifiers(member, modifiers) {
  8724. return modifiers.some(modifier => {
  8725. if (tsIsAccessModifier(modifier)) {
  8726. return member.accessibility === modifier;
  8727. }
  8728. return !!member[modifier];
  8729. });
  8730. }
  8731. tsIsStartOfStaticBlocks() {
  8732. return this.isContextual(98) && this.lookaheadCharCode() === 123;
  8733. }
  8734. parseClassMember(classBody, member, state) {
  8735. const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"];
  8736. this.tsParseModifiers(member, modifiers, undefined, undefined, true);
  8737. const callParseClassMemberWithIsStatic = () => {
  8738. if (this.tsIsStartOfStaticBlocks()) {
  8739. this.next();
  8740. this.next();
  8741. if (this.tsHasSomeModifiers(member, modifiers)) {
  8742. this.raise(this.state.pos, TSErrors.StaticBlockCannotHaveModifier);
  8743. }
  8744. this.parseClassStaticBlock(classBody, member);
  8745. } else {
  8746. this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static);
  8747. }
  8748. };
  8749. if (member.declare) {
  8750. this.tsInAmbientContext(callParseClassMemberWithIsStatic);
  8751. } else {
  8752. callParseClassMemberWithIsStatic();
  8753. }
  8754. }
  8755. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  8756. const idx = this.tsTryParseIndexSignature(member);
  8757. if (idx) {
  8758. classBody.body.push(idx);
  8759. if (member.abstract) {
  8760. this.raise(member.start, TSErrors.IndexSignatureHasAbstract);
  8761. }
  8762. if (member.accessibility) {
  8763. this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility);
  8764. }
  8765. if (member.declare) {
  8766. this.raise(member.start, TSErrors.IndexSignatureHasDeclare);
  8767. }
  8768. if (member.override) {
  8769. this.raise(member.start, TSErrors.IndexSignatureHasOverride);
  8770. }
  8771. return;
  8772. }
  8773. if (!this.state.inAbstractClass && member.abstract) {
  8774. this.raise(member.start, TSErrors.NonAbstractClassHasAbstractMethod);
  8775. }
  8776. if (member.override) {
  8777. if (!state.hadSuperClass) {
  8778. this.raise(member.start, TSErrors.OverrideNotInSubClass);
  8779. }
  8780. }
  8781. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  8782. }
  8783. parsePostMemberNameModifiers(methodOrProp) {
  8784. const optional = this.eat(17);
  8785. if (optional) methodOrProp.optional = true;
  8786. if (methodOrProp.readonly && this.match(10)) {
  8787. this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly);
  8788. }
  8789. if (methodOrProp.declare && this.match(10)) {
  8790. this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare);
  8791. }
  8792. }
  8793. parseExpressionStatement(node, expr) {
  8794. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  8795. return decl || super.parseExpressionStatement(node, expr);
  8796. }
  8797. shouldParseExportDeclaration() {
  8798. if (this.tsIsDeclarationStart()) return true;
  8799. return super.shouldParseExportDeclaration();
  8800. }
  8801. parseConditional(expr, startPos, startLoc, refExpressionErrors) {
  8802. if (!this.state.maybeInArrowParameters || !this.match(17)) {
  8803. return super.parseConditional(expr, startPos, startLoc, refExpressionErrors);
  8804. }
  8805. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  8806. if (!result.node) {
  8807. if (result.error) {
  8808. super.setOptionalParametersError(refExpressionErrors, result.error);
  8809. }
  8810. return expr;
  8811. }
  8812. if (result.error) this.state = result.failState;
  8813. return result.node;
  8814. }
  8815. parseParenItem(node, startPos, startLoc) {
  8816. node = super.parseParenItem(node, startPos, startLoc);
  8817. if (this.eat(17)) {
  8818. node.optional = true;
  8819. this.resetEndLocation(node);
  8820. }
  8821. if (this.match(14)) {
  8822. const typeCastNode = this.startNodeAt(startPos, startLoc);
  8823. typeCastNode.expression = node;
  8824. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  8825. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  8826. }
  8827. return node;
  8828. }
  8829. parseExportDeclaration(node) {
  8830. const startPos = this.state.start;
  8831. const startLoc = this.state.startLoc;
  8832. const isDeclare = this.eatContextual(115);
  8833. if (isDeclare && (this.isContextual(115) || !this.shouldParseExportDeclaration())) {
  8834. throw this.raise(this.state.start, TSErrors.ExpectedAmbientAfterExportDeclare);
  8835. }
  8836. let declaration;
  8837. if (tokenIsIdentifier(this.state.type)) {
  8838. declaration = this.tsTryParseExportDeclaration();
  8839. }
  8840. if (!declaration) {
  8841. declaration = super.parseExportDeclaration(node);
  8842. }
  8843. if (declaration && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) {
  8844. node.exportKind = "type";
  8845. }
  8846. if (declaration && isDeclare) {
  8847. this.resetStartLocation(declaration, startPos, startLoc);
  8848. declaration.declare = true;
  8849. }
  8850. return declaration;
  8851. }
  8852. parseClassId(node, isStatement, optionalId) {
  8853. if ((!isStatement || optionalId) && this.isContextual(104)) {
  8854. return;
  8855. }
  8856. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  8857. const typeParameters = this.tsTryParseTypeParameters();
  8858. if (typeParameters) node.typeParameters = typeParameters;
  8859. }
  8860. parseClassPropertyAnnotation(node) {
  8861. if (!node.optional && this.eat(33)) {
  8862. node.definite = true;
  8863. }
  8864. const type = this.tsTryParseTypeAnnotation();
  8865. if (type) node.typeAnnotation = type;
  8866. }
  8867. parseClassProperty(node) {
  8868. this.parseClassPropertyAnnotation(node);
  8869. if (this.state.isAmbientContext && this.match(27)) {
  8870. this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer);
  8871. }
  8872. if (node.abstract && this.match(27)) {
  8873. const {
  8874. key
  8875. } = node;
  8876. this.raise(this.state.start, TSErrors.AbstractPropertyHasInitializer, key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`);
  8877. }
  8878. return super.parseClassProperty(node);
  8879. }
  8880. parseClassPrivateProperty(node) {
  8881. if (node.abstract) {
  8882. this.raise(node.start, TSErrors.PrivateElementHasAbstract);
  8883. }
  8884. if (node.accessibility) {
  8885. this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility);
  8886. }
  8887. this.parseClassPropertyAnnotation(node);
  8888. return super.parseClassPrivateProperty(node);
  8889. }
  8890. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  8891. const typeParameters = this.tsTryParseTypeParameters();
  8892. if (typeParameters && isConstructor) {
  8893. this.raise(typeParameters.start, TSErrors.ConstructorHasTypeParameters);
  8894. }
  8895. if (method.declare && (method.kind === "get" || method.kind === "set")) {
  8896. this.raise(method.start, TSErrors.DeclareAccessor, method.kind);
  8897. }
  8898. if (typeParameters) method.typeParameters = typeParameters;
  8899. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  8900. }
  8901. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  8902. const typeParameters = this.tsTryParseTypeParameters();
  8903. if (typeParameters) method.typeParameters = typeParameters;
  8904. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  8905. }
  8906. declareClassPrivateMethodInScope(node, kind) {
  8907. if (node.type === "TSDeclareMethod") return;
  8908. if (node.type === "MethodDefinition" && !node.value.body) return;
  8909. super.declareClassPrivateMethodInScope(node, kind);
  8910. }
  8911. parseClassSuper(node) {
  8912. super.parseClassSuper(node);
  8913. if (node.superClass && this.match(43)) {
  8914. node.superTypeParameters = this.tsParseTypeArguments();
  8915. }
  8916. if (this.eatContextual(104)) {
  8917. node.implements = this.tsParseHeritageClause("implements");
  8918. }
  8919. }
  8920. parseObjPropValue(prop, ...args) {
  8921. const typeParameters = this.tsTryParseTypeParameters();
  8922. if (typeParameters) prop.typeParameters = typeParameters;
  8923. super.parseObjPropValue(prop, ...args);
  8924. }
  8925. parseFunctionParams(node, allowModifiers) {
  8926. const typeParameters = this.tsTryParseTypeParameters();
  8927. if (typeParameters) node.typeParameters = typeParameters;
  8928. super.parseFunctionParams(node, allowModifiers);
  8929. }
  8930. parseVarId(decl, kind) {
  8931. super.parseVarId(decl, kind);
  8932. if (decl.id.type === "Identifier" && this.eat(33)) {
  8933. decl.definite = true;
  8934. }
  8935. const type = this.tsTryParseTypeAnnotation();
  8936. if (type) {
  8937. decl.id.typeAnnotation = type;
  8938. this.resetEndLocation(decl.id);
  8939. }
  8940. }
  8941. parseAsyncArrowFromCallExpression(node, call) {
  8942. if (this.match(14)) {
  8943. node.returnType = this.tsParseTypeAnnotation();
  8944. }
  8945. return super.parseAsyncArrowFromCallExpression(node, call);
  8946. }
  8947. parseMaybeAssign(...args) {
  8948. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2, _jsx4, _typeCast3;
  8949. let state;
  8950. let jsx;
  8951. let typeCast;
  8952. if (this.hasPlugin("jsx") && (this.match(132) || this.match(43))) {
  8953. state = this.state.clone();
  8954. jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
  8955. if (!jsx.error) return jsx.node;
  8956. const {
  8957. context
  8958. } = this.state;
  8959. if (context[context.length - 1] === types$1.j_oTag) {
  8960. context.length -= 2;
  8961. } else if (context[context.length - 1] === types$1.j_expr) {
  8962. context.length -= 1;
  8963. }
  8964. }
  8965. if (!((_jsx = jsx) != null && _jsx.error) && !this.match(43)) {
  8966. return super.parseMaybeAssign(...args);
  8967. }
  8968. let typeParameters;
  8969. state = state || this.state.clone();
  8970. const arrow = this.tryParse(abort => {
  8971. var _expr$extra, _typeParameters;
  8972. typeParameters = this.tsParseTypeParameters();
  8973. const expr = super.parseMaybeAssign(...args);
  8974. if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  8975. abort();
  8976. }
  8977. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  8978. this.resetStartLocationFromNode(expr, typeParameters);
  8979. }
  8980. expr.typeParameters = typeParameters;
  8981. return expr;
  8982. }, state);
  8983. if (!arrow.error && !arrow.aborted) {
  8984. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  8985. return arrow.node;
  8986. }
  8987. if (!jsx) {
  8988. assert$1(!this.hasPlugin("jsx"));
  8989. typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
  8990. if (!typeCast.error) return typeCast.node;
  8991. }
  8992. if ((_jsx2 = jsx) != null && _jsx2.node) {
  8993. this.state = jsx.failState;
  8994. return jsx.node;
  8995. }
  8996. if (arrow.node) {
  8997. this.state = arrow.failState;
  8998. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  8999. return arrow.node;
  9000. }
  9001. if ((_typeCast = typeCast) != null && _typeCast.node) {
  9002. this.state = typeCast.failState;
  9003. return typeCast.node;
  9004. }
  9005. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  9006. if (arrow.thrown) throw arrow.error;
  9007. if ((_typeCast2 = typeCast) != null && _typeCast2.thrown) throw typeCast.error;
  9008. throw ((_jsx4 = jsx) == null ? void 0 : _jsx4.error) || arrow.error || ((_typeCast3 = typeCast) == null ? void 0 : _typeCast3.error);
  9009. }
  9010. reportReservedArrowTypeParam(node) {
  9011. var _node$extra;
  9012. if (node.params.length === 1 && !((_node$extra = node.extra) != null && _node$extra.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  9013. this.raise(node.start, TSErrors.ReservedArrowTypeParam);
  9014. }
  9015. }
  9016. parseMaybeUnary(refExpressionErrors) {
  9017. if (!this.hasPlugin("jsx") && this.match(43)) {
  9018. return this.tsParseTypeAssertion();
  9019. } else {
  9020. return super.parseMaybeUnary(refExpressionErrors);
  9021. }
  9022. }
  9023. parseArrow(node) {
  9024. if (this.match(14)) {
  9025. const result = this.tryParse(abort => {
  9026. const returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  9027. if (this.canInsertSemicolon() || !this.match(19)) abort();
  9028. return returnType;
  9029. });
  9030. if (result.aborted) return;
  9031. if (!result.thrown) {
  9032. if (result.error) this.state = result.failState;
  9033. node.returnType = result.node;
  9034. }
  9035. }
  9036. return super.parseArrow(node);
  9037. }
  9038. parseAssignableListItemTypes(param) {
  9039. if (this.eat(17)) {
  9040. if (param.type !== "Identifier" && !this.state.isAmbientContext && !this.state.inType) {
  9041. this.raise(param.start, TSErrors.PatternIsOptional);
  9042. }
  9043. param.optional = true;
  9044. }
  9045. const type = this.tsTryParseTypeAnnotation();
  9046. if (type) param.typeAnnotation = type;
  9047. this.resetEndLocation(param);
  9048. return param;
  9049. }
  9050. isAssignable(node, isBinding) {
  9051. switch (node.type) {
  9052. case "TSTypeCastExpression":
  9053. return this.isAssignable(node.expression, isBinding);
  9054. case "TSParameterProperty":
  9055. return true;
  9056. default:
  9057. return super.isAssignable(node, isBinding);
  9058. }
  9059. }
  9060. toAssignable(node, isLHS = false) {
  9061. switch (node.type) {
  9062. case "TSTypeCastExpression":
  9063. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  9064. case "TSParameterProperty":
  9065. return super.toAssignable(node, isLHS);
  9066. case "ParenthesizedExpression":
  9067. return this.toAssignableParenthesizedExpression(node, isLHS);
  9068. case "TSAsExpression":
  9069. case "TSNonNullExpression":
  9070. case "TSTypeAssertion":
  9071. node.expression = this.toAssignable(node.expression, isLHS);
  9072. return node;
  9073. default:
  9074. return super.toAssignable(node, isLHS);
  9075. }
  9076. }
  9077. toAssignableParenthesizedExpression(node, isLHS) {
  9078. switch (node.expression.type) {
  9079. case "TSAsExpression":
  9080. case "TSNonNullExpression":
  9081. case "TSTypeAssertion":
  9082. case "ParenthesizedExpression":
  9083. node.expression = this.toAssignable(node.expression, isLHS);
  9084. return node;
  9085. default:
  9086. return super.toAssignable(node, isLHS);
  9087. }
  9088. }
  9089. checkLVal(expr, contextDescription, ...args) {
  9090. var _expr$extra2;
  9091. switch (expr.type) {
  9092. case "TSTypeCastExpression":
  9093. return;
  9094. case "TSParameterProperty":
  9095. this.checkLVal(expr.parameter, "parameter property", ...args);
  9096. return;
  9097. case "TSAsExpression":
  9098. case "TSTypeAssertion":
  9099. if (!args[0] && contextDescription !== "parenthesized expression" && !((_expr$extra2 = expr.extra) != null && _expr$extra2.parenthesized)) {
  9100. this.raise(expr.start, ErrorMessages.InvalidLhs, contextDescription);
  9101. break;
  9102. }
  9103. this.checkLVal(expr.expression, "parenthesized expression", ...args);
  9104. return;
  9105. case "TSNonNullExpression":
  9106. this.checkLVal(expr.expression, contextDescription, ...args);
  9107. return;
  9108. default:
  9109. super.checkLVal(expr, contextDescription, ...args);
  9110. return;
  9111. }
  9112. }
  9113. parseBindingAtom() {
  9114. switch (this.state.type) {
  9115. case 72:
  9116. return this.parseIdentifier(true);
  9117. default:
  9118. return super.parseBindingAtom();
  9119. }
  9120. }
  9121. parseMaybeDecoratorArguments(expr) {
  9122. if (this.match(43)) {
  9123. const typeArguments = this.tsParseTypeArguments();
  9124. if (this.match(10)) {
  9125. const call = super.parseMaybeDecoratorArguments(expr);
  9126. call.typeParameters = typeArguments;
  9127. return call;
  9128. }
  9129. this.unexpected(this.state.start, 10);
  9130. }
  9131. return super.parseMaybeDecoratorArguments(expr);
  9132. }
  9133. checkCommaAfterRest(close) {
  9134. if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) {
  9135. this.next();
  9136. } else {
  9137. super.checkCommaAfterRest(close);
  9138. }
  9139. }
  9140. isClassMethod() {
  9141. return this.match(43) || super.isClassMethod();
  9142. }
  9143. isClassProperty() {
  9144. return this.match(33) || this.match(14) || super.isClassProperty();
  9145. }
  9146. parseMaybeDefault(...args) {
  9147. const node = super.parseMaybeDefault(...args);
  9148. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  9149. this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign);
  9150. }
  9151. return node;
  9152. }
  9153. getTokenFromCode(code) {
  9154. if (this.state.inType) {
  9155. if (code === 62) {
  9156. return this.finishOp(44, 1);
  9157. }
  9158. if (code === 60) {
  9159. return this.finishOp(43, 1);
  9160. }
  9161. }
  9162. return super.getTokenFromCode(code);
  9163. }
  9164. reScan_lt_gt() {
  9165. const {
  9166. type
  9167. } = this.state;
  9168. if (type === 43) {
  9169. this.state.pos -= 1;
  9170. this.readToken_lt();
  9171. } else if (type === 44) {
  9172. this.state.pos -= 1;
  9173. this.readToken_gt();
  9174. }
  9175. }
  9176. toAssignableList(exprList) {
  9177. for (let i = 0; i < exprList.length; i++) {
  9178. const expr = exprList[i];
  9179. if (!expr) continue;
  9180. switch (expr.type) {
  9181. case "TSTypeCastExpression":
  9182. exprList[i] = this.typeCastToParameter(expr);
  9183. break;
  9184. case "TSAsExpression":
  9185. case "TSTypeAssertion":
  9186. if (!this.state.maybeInArrowParameters) {
  9187. exprList[i] = this.typeCastToParameter(expr);
  9188. } else {
  9189. this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter);
  9190. }
  9191. break;
  9192. }
  9193. }
  9194. return super.toAssignableList(...arguments);
  9195. }
  9196. typeCastToParameter(node) {
  9197. node.expression.typeAnnotation = node.typeAnnotation;
  9198. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  9199. return node.expression;
  9200. }
  9201. shouldParseArrow(params) {
  9202. if (this.match(14)) {
  9203. return params.every(expr => this.isAssignable(expr, true));
  9204. }
  9205. return super.shouldParseArrow(params);
  9206. }
  9207. shouldParseAsyncArrow() {
  9208. return this.match(14) || super.shouldParseAsyncArrow();
  9209. }
  9210. canHaveLeadingDecorator() {
  9211. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  9212. }
  9213. jsxParseOpeningElementAfterName(node) {
  9214. if (this.match(43)) {
  9215. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  9216. if (typeArguments) node.typeParameters = typeArguments;
  9217. }
  9218. return super.jsxParseOpeningElementAfterName(node);
  9219. }
  9220. getGetterSetterExpectedParamCount(method) {
  9221. const baseCount = super.getGetterSetterExpectedParamCount(method);
  9222. const params = this.getObjectOrClassMethodParams(method);
  9223. const firstParam = params[0];
  9224. const hasContextParam = firstParam && this.isThisParam(firstParam);
  9225. return hasContextParam ? baseCount + 1 : baseCount;
  9226. }
  9227. parseCatchClauseParam() {
  9228. const param = super.parseCatchClauseParam();
  9229. const type = this.tsTryParseTypeAnnotation();
  9230. if (type) {
  9231. param.typeAnnotation = type;
  9232. this.resetEndLocation(param);
  9233. }
  9234. return param;
  9235. }
  9236. tsInAmbientContext(cb) {
  9237. const oldIsAmbientContext = this.state.isAmbientContext;
  9238. this.state.isAmbientContext = true;
  9239. try {
  9240. return cb();
  9241. } finally {
  9242. this.state.isAmbientContext = oldIsAmbientContext;
  9243. }
  9244. }
  9245. parseClass(node, ...args) {
  9246. const oldInAbstractClass = this.state.inAbstractClass;
  9247. this.state.inAbstractClass = !!node.abstract;
  9248. try {
  9249. return super.parseClass(node, ...args);
  9250. } finally {
  9251. this.state.inAbstractClass = oldInAbstractClass;
  9252. }
  9253. }
  9254. tsParseAbstractDeclaration(node) {
  9255. if (this.match(74)) {
  9256. node.abstract = true;
  9257. return this.parseClass(node, true, false);
  9258. } else if (this.isContextual(119)) {
  9259. if (!this.hasFollowingLineBreak()) {
  9260. node.abstract = true;
  9261. this.raise(node.start, TSErrors.NonClassMethodPropertyHasAbstractModifer);
  9262. this.next();
  9263. return this.tsParseInterfaceDeclaration(node);
  9264. }
  9265. } else {
  9266. this.unexpected(null, 74);
  9267. }
  9268. }
  9269. parseMethod(...args) {
  9270. const method = super.parseMethod(...args);
  9271. if (method.abstract) {
  9272. const hasBody = this.hasPlugin("estree") ? !!method.value.body : !!method.body;
  9273. if (hasBody) {
  9274. const {
  9275. key
  9276. } = method;
  9277. this.raise(method.start, TSErrors.AbstractMethodHasImplementation, key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`);
  9278. }
  9279. }
  9280. return method;
  9281. }
  9282. tsParseTypeParameterName() {
  9283. const typeName = this.parseIdentifier();
  9284. return typeName.name;
  9285. }
  9286. shouldParseAsAmbientContext() {
  9287. return !!this.getPluginOption("typescript", "dts");
  9288. }
  9289. parse() {
  9290. if (this.shouldParseAsAmbientContext()) {
  9291. this.state.isAmbientContext = true;
  9292. }
  9293. return super.parse();
  9294. }
  9295. getExpression() {
  9296. if (this.shouldParseAsAmbientContext()) {
  9297. this.state.isAmbientContext = true;
  9298. }
  9299. return super.getExpression();
  9300. }
  9301. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  9302. if (!isString && isMaybeTypeOnly) {
  9303. this.parseTypeOnlyImportExportSpecifier(node, false, isInTypeExport);
  9304. return this.finishNode(node, "ExportSpecifier");
  9305. }
  9306. node.exportKind = "value";
  9307. return super.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly);
  9308. }
  9309. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly) {
  9310. if (!importedIsString && isMaybeTypeOnly) {
  9311. this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport);
  9312. return this.finishNode(specifier, "ImportSpecifier");
  9313. }
  9314. specifier.importKind = "value";
  9315. return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly);
  9316. }
  9317. parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) {
  9318. const leftOfAsKey = isImport ? "imported" : "local";
  9319. const rightOfAsKey = isImport ? "local" : "exported";
  9320. let leftOfAs = node[leftOfAsKey];
  9321. let rightOfAs;
  9322. let hasTypeSpecifier = false;
  9323. let canParseAsKeyword = true;
  9324. const pos = leftOfAs.start;
  9325. if (this.isContextual(87)) {
  9326. const firstAs = this.parseIdentifier();
  9327. if (this.isContextual(87)) {
  9328. const secondAs = this.parseIdentifier();
  9329. if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9330. hasTypeSpecifier = true;
  9331. leftOfAs = firstAs;
  9332. rightOfAs = this.parseIdentifier();
  9333. canParseAsKeyword = false;
  9334. } else {
  9335. rightOfAs = secondAs;
  9336. canParseAsKeyword = false;
  9337. }
  9338. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9339. canParseAsKeyword = false;
  9340. rightOfAs = this.parseIdentifier();
  9341. } else {
  9342. hasTypeSpecifier = true;
  9343. leftOfAs = firstAs;
  9344. }
  9345. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9346. hasTypeSpecifier = true;
  9347. leftOfAs = this.parseIdentifier();
  9348. }
  9349. if (hasTypeSpecifier && isInTypeOnlyImportExport) {
  9350. this.raise(pos, isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports);
  9351. }
  9352. node[leftOfAsKey] = leftOfAs;
  9353. node[rightOfAsKey] = rightOfAs;
  9354. const kindKey = isImport ? "importKind" : "exportKind";
  9355. node[kindKey] = hasTypeSpecifier ? "type" : "value";
  9356. if (canParseAsKeyword && this.eatContextual(87)) {
  9357. node[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  9358. }
  9359. if (!node[rightOfAsKey]) {
  9360. node[rightOfAsKey] = cloneIdentifier(node[leftOfAsKey]);
  9361. }
  9362. if (isImport) {
  9363. this.checkLVal(node[rightOfAsKey], "import specifier", BIND_LEXICAL);
  9364. }
  9365. }
  9366. });
  9367. const PlaceHolderErrors = makeErrorTemplates({
  9368. ClassNameIsRequired: "A class name is required."
  9369. }, ErrorCodes.SyntaxError);
  9370. var placeholders = (superClass => class extends superClass {
  9371. parsePlaceholder(expectedNode) {
  9372. if (this.match(134)) {
  9373. const node = this.startNode();
  9374. this.next();
  9375. this.assertNoSpace("Unexpected space in placeholder.");
  9376. node.name = super.parseIdentifier(true);
  9377. this.assertNoSpace("Unexpected space in placeholder.");
  9378. this.expect(134);
  9379. return this.finishPlaceholder(node, expectedNode);
  9380. }
  9381. }
  9382. finishPlaceholder(node, expectedNode) {
  9383. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  9384. node.expectedNode = expectedNode;
  9385. return isFinished ? node : this.finishNode(node, "Placeholder");
  9386. }
  9387. getTokenFromCode(code) {
  9388. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  9389. return this.finishOp(134, 2);
  9390. }
  9391. return super.getTokenFromCode(...arguments);
  9392. }
  9393. parseExprAtom() {
  9394. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  9395. }
  9396. parseIdentifier() {
  9397. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  9398. }
  9399. checkReservedWord(word) {
  9400. if (word !== undefined) super.checkReservedWord(...arguments);
  9401. }
  9402. parseBindingAtom() {
  9403. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  9404. }
  9405. checkLVal(expr) {
  9406. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  9407. }
  9408. toAssignable(node) {
  9409. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  9410. node.expectedNode = "Pattern";
  9411. return node;
  9412. }
  9413. return super.toAssignable(...arguments);
  9414. }
  9415. isLet(context) {
  9416. if (super.isLet(context)) {
  9417. return true;
  9418. }
  9419. if (!this.isContextual(93)) {
  9420. return false;
  9421. }
  9422. if (context) return false;
  9423. const nextToken = this.lookahead();
  9424. if (nextToken.type === 134) {
  9425. return true;
  9426. }
  9427. return false;
  9428. }
  9429. verifyBreakContinue(node) {
  9430. if (node.label && node.label.type === "Placeholder") return;
  9431. super.verifyBreakContinue(...arguments);
  9432. }
  9433. parseExpressionStatement(node, expr) {
  9434. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  9435. return super.parseExpressionStatement(...arguments);
  9436. }
  9437. if (this.match(14)) {
  9438. const stmt = node;
  9439. stmt.label = this.finishPlaceholder(expr, "Identifier");
  9440. this.next();
  9441. stmt.body = this.parseStatement("label");
  9442. return this.finishNode(stmt, "LabeledStatement");
  9443. }
  9444. this.semicolon();
  9445. node.name = expr.name;
  9446. return this.finishPlaceholder(node, "Statement");
  9447. }
  9448. parseBlock() {
  9449. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  9450. }
  9451. parseFunctionId() {
  9452. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  9453. }
  9454. parseClass(node, isStatement, optionalId) {
  9455. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  9456. this.next();
  9457. this.takeDecorators(node);
  9458. const oldStrict = this.state.strict;
  9459. const placeholder = this.parsePlaceholder("Identifier");
  9460. if (placeholder) {
  9461. if (this.match(75) || this.match(134) || this.match(5)) {
  9462. node.id = placeholder;
  9463. } else if (optionalId || !isStatement) {
  9464. node.id = null;
  9465. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  9466. return this.finishNode(node, type);
  9467. } else {
  9468. this.unexpected(null, PlaceHolderErrors.ClassNameIsRequired);
  9469. }
  9470. } else {
  9471. this.parseClassId(node, isStatement, optionalId);
  9472. }
  9473. this.parseClassSuper(node);
  9474. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass, oldStrict);
  9475. return this.finishNode(node, type);
  9476. }
  9477. parseExport(node) {
  9478. const placeholder = this.parsePlaceholder("Identifier");
  9479. if (!placeholder) return super.parseExport(...arguments);
  9480. if (!this.isContextual(91) && !this.match(12)) {
  9481. node.specifiers = [];
  9482. node.source = null;
  9483. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  9484. return this.finishNode(node, "ExportNamedDeclaration");
  9485. }
  9486. this.expectPlugin("exportDefaultFrom");
  9487. const specifier = this.startNode();
  9488. specifier.exported = placeholder;
  9489. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  9490. return super.parseExport(node);
  9491. }
  9492. isExportDefaultSpecifier() {
  9493. if (this.match(59)) {
  9494. const next = this.nextTokenStart();
  9495. if (this.isUnparsedContextual(next, "from")) {
  9496. if (this.input.startsWith(tokenLabelName(134), this.nextTokenStartSince(next + 4))) {
  9497. return true;
  9498. }
  9499. }
  9500. }
  9501. return super.isExportDefaultSpecifier();
  9502. }
  9503. maybeParseExportDefaultSpecifier(node) {
  9504. if (node.specifiers && node.specifiers.length > 0) {
  9505. return true;
  9506. }
  9507. return super.maybeParseExportDefaultSpecifier(...arguments);
  9508. }
  9509. checkExport(node) {
  9510. const {
  9511. specifiers
  9512. } = node;
  9513. if (specifiers != null && specifiers.length) {
  9514. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  9515. }
  9516. super.checkExport(node);
  9517. node.specifiers = specifiers;
  9518. }
  9519. parseImport(node) {
  9520. const placeholder = this.parsePlaceholder("Identifier");
  9521. if (!placeholder) return super.parseImport(...arguments);
  9522. node.specifiers = [];
  9523. if (!this.isContextual(91) && !this.match(12)) {
  9524. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  9525. this.semicolon();
  9526. return this.finishNode(node, "ImportDeclaration");
  9527. }
  9528. const specifier = this.startNodeAtNode(placeholder);
  9529. specifier.local = placeholder;
  9530. this.finishNode(specifier, "ImportDefaultSpecifier");
  9531. node.specifiers.push(specifier);
  9532. if (this.eat(12)) {
  9533. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  9534. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  9535. }
  9536. this.expectContextual(91);
  9537. node.source = this.parseImportSource();
  9538. this.semicolon();
  9539. return this.finishNode(node, "ImportDeclaration");
  9540. }
  9541. parseImportSource() {
  9542. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  9543. }
  9544. });
  9545. var v8intrinsic = (superClass => class extends superClass {
  9546. parseV8Intrinsic() {
  9547. if (this.match(48)) {
  9548. const v8IntrinsicStart = this.state.start;
  9549. const node = this.startNode();
  9550. this.next();
  9551. if (tokenIsIdentifier(this.state.type)) {
  9552. const name = this.parseIdentifierName(this.state.start);
  9553. const identifier = this.createIdentifier(node, name);
  9554. identifier.type = "V8IntrinsicIdentifier";
  9555. if (this.match(10)) {
  9556. return identifier;
  9557. }
  9558. }
  9559. this.unexpected(v8IntrinsicStart);
  9560. }
  9561. }
  9562. parseExprAtom() {
  9563. return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
  9564. }
  9565. });
  9566. function hasPlugin(plugins, name) {
  9567. return plugins.some(plugin => {
  9568. if (Array.isArray(plugin)) {
  9569. return plugin[0] === name;
  9570. } else {
  9571. return plugin === name;
  9572. }
  9573. });
  9574. }
  9575. function getPluginOption(plugins, name, option) {
  9576. const plugin = plugins.find(plugin => {
  9577. if (Array.isArray(plugin)) {
  9578. return plugin[0] === name;
  9579. } else {
  9580. return plugin === name;
  9581. }
  9582. });
  9583. if (plugin && Array.isArray(plugin)) {
  9584. return plugin[1][option];
  9585. }
  9586. return null;
  9587. }
  9588. const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"];
  9589. const TOPIC_TOKENS = ["^", "%", "#"];
  9590. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  9591. function validatePlugins(plugins) {
  9592. if (hasPlugin(plugins, "decorators")) {
  9593. if (hasPlugin(plugins, "decorators-legacy")) {
  9594. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  9595. }
  9596. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  9597. if (decoratorsBeforeExport == null) {
  9598. throw new Error("The 'decorators' plugin requires a 'decoratorsBeforeExport' option," + " whose value must be a boolean. If you are migrating from" + " Babylon/Babel 6 or want to use the old decorators proposal, you" + " should use the 'decorators-legacy' plugin instead of 'decorators'.");
  9599. } else if (typeof decoratorsBeforeExport !== "boolean") {
  9600. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  9601. }
  9602. }
  9603. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  9604. throw new Error("Cannot combine flow and typescript plugins.");
  9605. }
  9606. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  9607. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  9608. }
  9609. if (hasPlugin(plugins, "pipelineOperator")) {
  9610. const proposal = getPluginOption(plugins, "pipelineOperator", "proposal");
  9611. if (!PIPELINE_PROPOSALS.includes(proposal)) {
  9612. const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", ");
  9613. throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`);
  9614. }
  9615. const tupleSyntaxIsHash = hasPlugin(plugins, "recordAndTuple") && getPluginOption(plugins, "recordAndTuple", "syntaxType") === "hash";
  9616. if (proposal === "hack") {
  9617. if (hasPlugin(plugins, "placeholders")) {
  9618. throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");
  9619. }
  9620. if (hasPlugin(plugins, "v8intrinsic")) {
  9621. throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");
  9622. }
  9623. const topicToken = getPluginOption(plugins, "pipelineOperator", "topicToken");
  9624. if (!TOPIC_TOKENS.includes(topicToken)) {
  9625. const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", ");
  9626. throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`);
  9627. }
  9628. if (topicToken === "#" && tupleSyntaxIsHash) {
  9629. throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "hack", topicToken: "#" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.');
  9630. }
  9631. } else if (proposal === "smart" && tupleSyntaxIsHash) {
  9632. throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "smart" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.');
  9633. }
  9634. }
  9635. if (hasPlugin(plugins, "moduleAttributes")) {
  9636. {
  9637. if (hasPlugin(plugins, "importAssertions")) {
  9638. throw new Error("Cannot combine importAssertions and moduleAttributes plugins.");
  9639. }
  9640. const moduleAttributesVerionPluginOption = getPluginOption(plugins, "moduleAttributes", "version");
  9641. if (moduleAttributesVerionPluginOption !== "may-2020") {
  9642. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  9643. }
  9644. }
  9645. }
  9646. if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
  9647. throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  9648. }
  9649. if (hasPlugin(plugins, "asyncDoExpressions") && !hasPlugin(plugins, "doExpressions")) {
  9650. const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");
  9651. error.missingPlugins = "doExpressions";
  9652. throw error;
  9653. }
  9654. }
  9655. const mixinPlugins = {
  9656. estree,
  9657. jsx,
  9658. flow,
  9659. typescript,
  9660. v8intrinsic,
  9661. placeholders
  9662. };
  9663. const mixinPluginNames = Object.keys(mixinPlugins);
  9664. const defaultOptions = {
  9665. sourceType: "script",
  9666. sourceFilename: undefined,
  9667. startColumn: 0,
  9668. startLine: 1,
  9669. allowAwaitOutsideFunction: false,
  9670. allowReturnOutsideFunction: false,
  9671. allowImportExportEverywhere: false,
  9672. allowSuperOutsideMethod: false,
  9673. allowUndeclaredExports: false,
  9674. plugins: [],
  9675. strictMode: null,
  9676. ranges: false,
  9677. tokens: false,
  9678. createParenthesizedExpressions: false,
  9679. errorRecovery: false,
  9680. attachComment: true
  9681. };
  9682. function getOptions(opts) {
  9683. const options = {};
  9684. for (const key of Object.keys(defaultOptions)) {
  9685. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  9686. }
  9687. return options;
  9688. }
  9689. const unwrapParenthesizedExpression = node => {
  9690. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  9691. };
  9692. class LValParser extends NodeUtils {
  9693. toAssignable(node, isLHS = false) {
  9694. var _node$extra, _node$extra3;
  9695. let parenthesized = undefined;
  9696. if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) {
  9697. parenthesized = unwrapParenthesizedExpression(node);
  9698. if (isLHS) {
  9699. if (parenthesized.type === "Identifier") {
  9700. this.expressionScope.recordParenthesizedIdentifierError(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  9701. } else if (parenthesized.type !== "MemberExpression") {
  9702. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  9703. }
  9704. } else {
  9705. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  9706. }
  9707. }
  9708. switch (node.type) {
  9709. case "Identifier":
  9710. case "ObjectPattern":
  9711. case "ArrayPattern":
  9712. case "AssignmentPattern":
  9713. case "RestElement":
  9714. break;
  9715. case "ObjectExpression":
  9716. node.type = "ObjectPattern";
  9717. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  9718. var _node$extra2;
  9719. const prop = node.properties[i];
  9720. const isLast = i === last;
  9721. this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  9722. if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingComma) {
  9723. this.raiseRestNotLast(node.extra.trailingComma);
  9724. }
  9725. }
  9726. break;
  9727. case "ObjectProperty":
  9728. this.toAssignable(node.value, isLHS);
  9729. break;
  9730. case "SpreadElement":
  9731. {
  9732. this.checkToRestConversion(node);
  9733. node.type = "RestElement";
  9734. const arg = node.argument;
  9735. this.toAssignable(arg, isLHS);
  9736. break;
  9737. }
  9738. case "ArrayExpression":
  9739. node.type = "ArrayPattern";
  9740. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma, isLHS);
  9741. break;
  9742. case "AssignmentExpression":
  9743. if (node.operator !== "=") {
  9744. this.raise(node.left.end, ErrorMessages.MissingEqInAssignment);
  9745. }
  9746. node.type = "AssignmentPattern";
  9747. delete node.operator;
  9748. this.toAssignable(node.left, isLHS);
  9749. break;
  9750. case "ParenthesizedExpression":
  9751. this.toAssignable(parenthesized, isLHS);
  9752. break;
  9753. }
  9754. return node;
  9755. }
  9756. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  9757. if (prop.type === "ObjectMethod") {
  9758. const error = prop.kind === "get" || prop.kind === "set" ? ErrorMessages.PatternHasAccessor : ErrorMessages.PatternHasMethod;
  9759. this.raise(prop.key.start, error);
  9760. } else if (prop.type === "SpreadElement" && !isLast) {
  9761. this.raiseRestNotLast(prop.start);
  9762. } else {
  9763. this.toAssignable(prop, isLHS);
  9764. }
  9765. }
  9766. toAssignableList(exprList, trailingCommaPos, isLHS) {
  9767. let end = exprList.length;
  9768. if (end) {
  9769. const last = exprList[end - 1];
  9770. if ((last == null ? void 0 : last.type) === "RestElement") {
  9771. --end;
  9772. } else if ((last == null ? void 0 : last.type) === "SpreadElement") {
  9773. last.type = "RestElement";
  9774. let arg = last.argument;
  9775. this.toAssignable(arg, isLHS);
  9776. arg = unwrapParenthesizedExpression(arg);
  9777. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  9778. this.unexpected(arg.start);
  9779. }
  9780. if (trailingCommaPos) {
  9781. this.raiseTrailingCommaAfterRest(trailingCommaPos);
  9782. }
  9783. --end;
  9784. }
  9785. }
  9786. for (let i = 0; i < end; i++) {
  9787. const elt = exprList[i];
  9788. if (elt) {
  9789. this.toAssignable(elt, isLHS);
  9790. if (elt.type === "RestElement") {
  9791. this.raiseRestNotLast(elt.start);
  9792. }
  9793. }
  9794. }
  9795. return exprList;
  9796. }
  9797. isAssignable(node, isBinding) {
  9798. switch (node.type) {
  9799. case "Identifier":
  9800. case "ObjectPattern":
  9801. case "ArrayPattern":
  9802. case "AssignmentPattern":
  9803. case "RestElement":
  9804. return true;
  9805. case "ObjectExpression":
  9806. {
  9807. const last = node.properties.length - 1;
  9808. return node.properties.every((prop, i) => {
  9809. return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop);
  9810. });
  9811. }
  9812. case "ObjectProperty":
  9813. return this.isAssignable(node.value);
  9814. case "SpreadElement":
  9815. return this.isAssignable(node.argument);
  9816. case "ArrayExpression":
  9817. return node.elements.every(element => element === null || this.isAssignable(element));
  9818. case "AssignmentExpression":
  9819. return node.operator === "=";
  9820. case "ParenthesizedExpression":
  9821. return this.isAssignable(node.expression);
  9822. case "MemberExpression":
  9823. case "OptionalMemberExpression":
  9824. return !isBinding;
  9825. default:
  9826. return false;
  9827. }
  9828. }
  9829. toReferencedList(exprList, isParenthesizedExpr) {
  9830. return exprList;
  9831. }
  9832. toReferencedListDeep(exprList, isParenthesizedExpr) {
  9833. this.toReferencedList(exprList, isParenthesizedExpr);
  9834. for (const expr of exprList) {
  9835. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  9836. this.toReferencedListDeep(expr.elements);
  9837. }
  9838. }
  9839. }
  9840. parseSpread(refExpressionErrors, refNeedsArrowPos) {
  9841. const node = this.startNode();
  9842. this.next();
  9843. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined, refNeedsArrowPos);
  9844. return this.finishNode(node, "SpreadElement");
  9845. }
  9846. parseRestBinding() {
  9847. const node = this.startNode();
  9848. this.next();
  9849. node.argument = this.parseBindingAtom();
  9850. return this.finishNode(node, "RestElement");
  9851. }
  9852. parseBindingAtom() {
  9853. switch (this.state.type) {
  9854. case 0:
  9855. {
  9856. const node = this.startNode();
  9857. this.next();
  9858. node.elements = this.parseBindingList(3, 93, true);
  9859. return this.finishNode(node, "ArrayPattern");
  9860. }
  9861. case 5:
  9862. return this.parseObjectLike(8, true);
  9863. }
  9864. return this.parseIdentifier();
  9865. }
  9866. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  9867. const elts = [];
  9868. let first = true;
  9869. while (!this.eat(close)) {
  9870. if (first) {
  9871. first = false;
  9872. } else {
  9873. this.expect(12);
  9874. }
  9875. if (allowEmpty && this.match(12)) {
  9876. elts.push(null);
  9877. } else if (this.eat(close)) {
  9878. break;
  9879. } else if (this.match(21)) {
  9880. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  9881. this.checkCommaAfterRest(closeCharCode);
  9882. this.expect(close);
  9883. break;
  9884. } else {
  9885. const decorators = [];
  9886. if (this.match(24) && this.hasPlugin("decorators")) {
  9887. this.raise(this.state.start, ErrorMessages.UnsupportedParameterDecorator);
  9888. }
  9889. while (this.match(24)) {
  9890. decorators.push(this.parseDecorator());
  9891. }
  9892. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  9893. }
  9894. }
  9895. return elts;
  9896. }
  9897. parseBindingRestProperty(prop) {
  9898. this.next();
  9899. prop.argument = this.parseIdentifier();
  9900. this.checkCommaAfterRest(125);
  9901. return this.finishNode(prop, "RestElement");
  9902. }
  9903. parseBindingProperty() {
  9904. const prop = this.startNode();
  9905. const {
  9906. type,
  9907. start: startPos,
  9908. startLoc
  9909. } = this.state;
  9910. if (type === 21) {
  9911. return this.parseBindingRestProperty(prop);
  9912. } else {
  9913. this.parsePropertyName(prop);
  9914. }
  9915. prop.method = false;
  9916. this.parseObjPropValue(prop, startPos, startLoc, false, false, true, false);
  9917. return prop;
  9918. }
  9919. parseAssignableListItem(allowModifiers, decorators) {
  9920. const left = this.parseMaybeDefault();
  9921. this.parseAssignableListItemTypes(left);
  9922. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  9923. if (decorators.length) {
  9924. left.decorators = decorators;
  9925. }
  9926. return elt;
  9927. }
  9928. parseAssignableListItemTypes(param) {
  9929. return param;
  9930. }
  9931. parseMaybeDefault(startPos, startLoc, left) {
  9932. var _startLoc, _startPos, _left;
  9933. startLoc = (_startLoc = startLoc) != null ? _startLoc : this.state.startLoc;
  9934. startPos = (_startPos = startPos) != null ? _startPos : this.state.start;
  9935. left = (_left = left) != null ? _left : this.parseBindingAtom();
  9936. if (!this.eat(27)) return left;
  9937. const node = this.startNodeAt(startPos, startLoc);
  9938. node.left = left;
  9939. node.right = this.parseMaybeAssignAllowIn();
  9940. return this.finishNode(node, "AssignmentPattern");
  9941. }
  9942. checkLVal(expr, contextDescription, bindingType = BIND_NONE, checkClashes, disallowLetBinding, strictModeChanged = false) {
  9943. switch (expr.type) {
  9944. case "Identifier":
  9945. {
  9946. const {
  9947. name
  9948. } = expr;
  9949. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(name, this.inModule) : isStrictBindOnlyReservedWord(name))) {
  9950. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.StrictEvalArguments : ErrorMessages.StrictEvalArgumentsBinding, name);
  9951. }
  9952. if (checkClashes) {
  9953. if (checkClashes.has(name)) {
  9954. this.raise(expr.start, ErrorMessages.ParamDupe);
  9955. } else {
  9956. checkClashes.add(name);
  9957. }
  9958. }
  9959. if (disallowLetBinding && name === "let") {
  9960. this.raise(expr.start, ErrorMessages.LetInLexicalBinding);
  9961. }
  9962. if (!(bindingType & BIND_NONE)) {
  9963. this.scope.declareName(name, bindingType, expr.start);
  9964. }
  9965. break;
  9966. }
  9967. case "MemberExpression":
  9968. if (bindingType !== BIND_NONE) {
  9969. this.raise(expr.start, ErrorMessages.InvalidPropertyBindingPattern);
  9970. }
  9971. break;
  9972. case "ObjectPattern":
  9973. for (let prop of expr.properties) {
  9974. if (this.isObjectProperty(prop)) prop = prop.value;else if (this.isObjectMethod(prop)) continue;
  9975. this.checkLVal(prop, "object destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  9976. }
  9977. break;
  9978. case "ArrayPattern":
  9979. for (const elem of expr.elements) {
  9980. if (elem) {
  9981. this.checkLVal(elem, "array destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  9982. }
  9983. }
  9984. break;
  9985. case "AssignmentPattern":
  9986. this.checkLVal(expr.left, "assignment pattern", bindingType, checkClashes);
  9987. break;
  9988. case "RestElement":
  9989. this.checkLVal(expr.argument, "rest element", bindingType, checkClashes);
  9990. break;
  9991. case "ParenthesizedExpression":
  9992. this.checkLVal(expr.expression, "parenthesized expression", bindingType, checkClashes);
  9993. break;
  9994. default:
  9995. {
  9996. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.InvalidLhs : ErrorMessages.InvalidLhsBinding, contextDescription);
  9997. }
  9998. }
  9999. }
  10000. checkToRestConversion(node) {
  10001. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  10002. this.raise(node.argument.start, ErrorMessages.InvalidRestAssignmentPattern);
  10003. }
  10004. }
  10005. checkCommaAfterRest(close) {
  10006. if (this.match(12)) {
  10007. if (this.lookaheadCharCode() === close) {
  10008. this.raiseTrailingCommaAfterRest(this.state.start);
  10009. } else {
  10010. this.raiseRestNotLast(this.state.start);
  10011. }
  10012. }
  10013. }
  10014. raiseRestNotLast(pos) {
  10015. throw this.raise(pos, ErrorMessages.ElementAfterRest);
  10016. }
  10017. raiseTrailingCommaAfterRest(pos) {
  10018. this.raise(pos, ErrorMessages.RestTrailingComma);
  10019. }
  10020. }
  10021. const invalidHackPipeBodies = new Map([["ArrowFunctionExpression", "arrow function"], ["AssignmentExpression", "assignment"], ["ConditionalExpression", "conditional"], ["YieldExpression", "yield"]]);
  10022. class ExpressionParser extends LValParser {
  10023. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  10024. if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) {
  10025. return;
  10026. }
  10027. const key = prop.key;
  10028. const name = key.type === "Identifier" ? key.name : key.value;
  10029. if (name === "__proto__") {
  10030. if (isRecord) {
  10031. this.raise(key.start, ErrorMessages.RecordNoProto);
  10032. return;
  10033. }
  10034. if (protoRef.used) {
  10035. if (refExpressionErrors) {
  10036. if (refExpressionErrors.doubleProto === -1) {
  10037. refExpressionErrors.doubleProto = key.start;
  10038. }
  10039. } else {
  10040. this.raise(key.start, ErrorMessages.DuplicateProto);
  10041. }
  10042. }
  10043. protoRef.used = true;
  10044. }
  10045. }
  10046. shouldExitDescending(expr, potentialArrowAt) {
  10047. return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt;
  10048. }
  10049. getExpression() {
  10050. this.enterInitialScopes();
  10051. this.nextToken();
  10052. const expr = this.parseExpression();
  10053. if (!this.match(129)) {
  10054. this.unexpected();
  10055. }
  10056. this.finalizeRemainingComments();
  10057. expr.comments = this.state.comments;
  10058. expr.errors = this.state.errors;
  10059. if (this.options.tokens) {
  10060. expr.tokens = this.tokens;
  10061. }
  10062. return expr;
  10063. }
  10064. parseExpression(disallowIn, refExpressionErrors) {
  10065. if (disallowIn) {
  10066. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  10067. }
  10068. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  10069. }
  10070. parseExpressionBase(refExpressionErrors) {
  10071. const startPos = this.state.start;
  10072. const startLoc = this.state.startLoc;
  10073. const expr = this.parseMaybeAssign(refExpressionErrors);
  10074. if (this.match(12)) {
  10075. const node = this.startNodeAt(startPos, startLoc);
  10076. node.expressions = [expr];
  10077. while (this.eat(12)) {
  10078. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  10079. }
  10080. this.toReferencedList(node.expressions);
  10081. return this.finishNode(node, "SequenceExpression");
  10082. }
  10083. return expr;
  10084. }
  10085. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) {
  10086. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  10087. }
  10088. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) {
  10089. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  10090. }
  10091. setOptionalParametersError(refExpressionErrors, resultError) {
  10092. var _resultError$pos;
  10093. refExpressionErrors.optionalParameters = (_resultError$pos = resultError == null ? void 0 : resultError.pos) != null ? _resultError$pos : this.state.start;
  10094. }
  10095. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  10096. const startPos = this.state.start;
  10097. const startLoc = this.state.startLoc;
  10098. if (this.isContextual(99)) {
  10099. if (this.prodParam.hasYield) {
  10100. let left = this.parseYield();
  10101. if (afterLeftParse) {
  10102. left = afterLeftParse.call(this, left, startPos, startLoc);
  10103. }
  10104. return left;
  10105. }
  10106. }
  10107. let ownExpressionErrors;
  10108. if (refExpressionErrors) {
  10109. ownExpressionErrors = false;
  10110. } else {
  10111. refExpressionErrors = new ExpressionErrors();
  10112. ownExpressionErrors = true;
  10113. }
  10114. const {
  10115. type
  10116. } = this.state;
  10117. if (type === 10 || tokenIsIdentifier(type)) {
  10118. this.state.potentialArrowAt = this.state.start;
  10119. }
  10120. let left = this.parseMaybeConditional(refExpressionErrors);
  10121. if (afterLeftParse) {
  10122. left = afterLeftParse.call(this, left, startPos, startLoc);
  10123. }
  10124. if (tokenIsAssignment(this.state.type)) {
  10125. const node = this.startNodeAt(startPos, startLoc);
  10126. const operator = this.state.value;
  10127. node.operator = operator;
  10128. if (this.match(27)) {
  10129. node.left = this.toAssignable(left, true);
  10130. if (refExpressionErrors.doubleProto >= startPos) {
  10131. refExpressionErrors.doubleProto = -1;
  10132. }
  10133. if (refExpressionErrors.shorthandAssign >= startPos) {
  10134. refExpressionErrors.shorthandAssign = -1;
  10135. }
  10136. } else {
  10137. node.left = left;
  10138. }
  10139. this.checkLVal(left, "assignment expression");
  10140. this.next();
  10141. node.right = this.parseMaybeAssign();
  10142. return this.finishNode(node, "AssignmentExpression");
  10143. } else if (ownExpressionErrors) {
  10144. this.checkExpressionErrors(refExpressionErrors, true);
  10145. }
  10146. return left;
  10147. }
  10148. parseMaybeConditional(refExpressionErrors) {
  10149. const startPos = this.state.start;
  10150. const startLoc = this.state.startLoc;
  10151. const potentialArrowAt = this.state.potentialArrowAt;
  10152. const expr = this.parseExprOps(refExpressionErrors);
  10153. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10154. return expr;
  10155. }
  10156. return this.parseConditional(expr, startPos, startLoc, refExpressionErrors);
  10157. }
  10158. parseConditional(expr, startPos, startLoc, refExpressionErrors) {
  10159. if (this.eat(17)) {
  10160. const node = this.startNodeAt(startPos, startLoc);
  10161. node.test = expr;
  10162. node.consequent = this.parseMaybeAssignAllowIn();
  10163. this.expect(14);
  10164. node.alternate = this.parseMaybeAssign();
  10165. return this.finishNode(node, "ConditionalExpression");
  10166. }
  10167. return expr;
  10168. }
  10169. parseMaybeUnaryOrPrivate(refExpressionErrors) {
  10170. return this.match(128) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors);
  10171. }
  10172. parseExprOps(refExpressionErrors) {
  10173. const startPos = this.state.start;
  10174. const startLoc = this.state.startLoc;
  10175. const potentialArrowAt = this.state.potentialArrowAt;
  10176. const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors);
  10177. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10178. return expr;
  10179. }
  10180. return this.parseExprOp(expr, startPos, startLoc, -1);
  10181. }
  10182. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  10183. if (this.isPrivateName(left)) {
  10184. const value = this.getPrivateNameSV(left);
  10185. const {
  10186. start
  10187. } = left;
  10188. if (minPrec >= tokenOperatorPrecedence(52) || !this.prodParam.hasIn || !this.match(52)) {
  10189. this.raise(start, ErrorMessages.PrivateInExpectedIn, value);
  10190. }
  10191. this.classScope.usePrivateName(value, start);
  10192. }
  10193. const op = this.state.type;
  10194. if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(52))) {
  10195. let prec = tokenOperatorPrecedence(op);
  10196. if (prec > minPrec) {
  10197. if (op === 35) {
  10198. this.expectPlugin("pipelineOperator");
  10199. if (this.state.inFSharpPipelineDirectBody) {
  10200. return left;
  10201. }
  10202. this.checkPipelineAtInfixOperator(left, leftStartPos);
  10203. }
  10204. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  10205. node.left = left;
  10206. node.operator = this.state.value;
  10207. const logical = op === 37 || op === 38;
  10208. const coalesce = op === 36;
  10209. if (coalesce) {
  10210. prec = tokenOperatorPrecedence(38);
  10211. }
  10212. this.next();
  10213. if (op === 35 && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  10214. if (this.state.type === 90 && this.prodParam.hasAwait) {
  10215. throw this.raise(this.state.start, ErrorMessages.UnexpectedAwaitAfterPipelineBody);
  10216. }
  10217. }
  10218. node.right = this.parseExprOpRightExpr(op, prec);
  10219. this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  10220. const nextOp = this.state.type;
  10221. if (coalesce && (nextOp === 37 || nextOp === 38) || logical && nextOp === 36) {
  10222. throw this.raise(this.state.start, ErrorMessages.MixingCoalesceWithLogical);
  10223. }
  10224. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  10225. }
  10226. }
  10227. return left;
  10228. }
  10229. parseExprOpRightExpr(op, prec) {
  10230. const startPos = this.state.start;
  10231. const startLoc = this.state.startLoc;
  10232. switch (op) {
  10233. case 35:
  10234. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  10235. case "hack":
  10236. return this.withTopicBindingContext(() => {
  10237. return this.parseHackPipeBody();
  10238. });
  10239. case "smart":
  10240. return this.withTopicBindingContext(() => {
  10241. if (this.prodParam.hasYield && this.isContextual(99)) {
  10242. throw this.raise(this.state.start, ErrorMessages.PipeBodyIsTighter, this.state.value);
  10243. }
  10244. return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startPos, startLoc);
  10245. });
  10246. case "fsharp":
  10247. return this.withSoloAwaitPermittingContext(() => {
  10248. return this.parseFSharpPipelineBody(prec);
  10249. });
  10250. }
  10251. default:
  10252. return this.parseExprOpBaseRightExpr(op, prec);
  10253. }
  10254. }
  10255. parseExprOpBaseRightExpr(op, prec) {
  10256. const startPos = this.state.start;
  10257. const startLoc = this.state.startLoc;
  10258. return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startPos, startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec);
  10259. }
  10260. parseHackPipeBody() {
  10261. var _body$extra;
  10262. const {
  10263. start
  10264. } = this.state;
  10265. const body = this.parseMaybeAssign();
  10266. if (invalidHackPipeBodies.has(body.type) && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) {
  10267. this.raise(start, ErrorMessages.PipeUnparenthesizedBody, invalidHackPipeBodies.get(body.type));
  10268. }
  10269. if (!this.topicReferenceWasUsedInCurrentContext()) {
  10270. this.raise(start, ErrorMessages.PipeTopicUnused);
  10271. }
  10272. return body;
  10273. }
  10274. checkExponentialAfterUnary(node) {
  10275. if (this.match(51)) {
  10276. this.raise(node.argument.start, ErrorMessages.UnexpectedTokenUnaryExponentiation);
  10277. }
  10278. }
  10279. parseMaybeUnary(refExpressionErrors, sawUnary) {
  10280. const startPos = this.state.start;
  10281. const startLoc = this.state.startLoc;
  10282. const isAwait = this.isContextual(90);
  10283. if (isAwait && this.isAwaitAllowed()) {
  10284. this.next();
  10285. const expr = this.parseAwait(startPos, startLoc);
  10286. if (!sawUnary) this.checkExponentialAfterUnary(expr);
  10287. return expr;
  10288. }
  10289. const update = this.match(32);
  10290. const node = this.startNode();
  10291. if (tokenIsPrefix(this.state.type)) {
  10292. node.operator = this.state.value;
  10293. node.prefix = true;
  10294. if (this.match(66)) {
  10295. this.expectPlugin("throwExpressions");
  10296. }
  10297. const isDelete = this.match(83);
  10298. this.next();
  10299. node.argument = this.parseMaybeUnary(null, true);
  10300. this.checkExpressionErrors(refExpressionErrors, true);
  10301. if (this.state.strict && isDelete) {
  10302. const arg = node.argument;
  10303. if (arg.type === "Identifier") {
  10304. this.raise(node.start, ErrorMessages.StrictDelete);
  10305. } else if (this.hasPropertyAsPrivateName(arg)) {
  10306. this.raise(node.start, ErrorMessages.DeletePrivateField);
  10307. }
  10308. }
  10309. if (!update) {
  10310. if (!sawUnary) this.checkExponentialAfterUnary(node);
  10311. return this.finishNode(node, "UnaryExpression");
  10312. }
  10313. }
  10314. const expr = this.parseUpdate(node, update, refExpressionErrors);
  10315. if (isAwait) {
  10316. const {
  10317. type
  10318. } = this.state;
  10319. const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(48);
  10320. if (startsExpr && !this.isAmbiguousAwait()) {
  10321. this.raiseOverwrite(startPos, ErrorMessages.AwaitNotInAsyncContext);
  10322. return this.parseAwait(startPos, startLoc);
  10323. }
  10324. }
  10325. return expr;
  10326. }
  10327. parseUpdate(node, update, refExpressionErrors) {
  10328. if (update) {
  10329. this.checkLVal(node.argument, "prefix operation");
  10330. return this.finishNode(node, "UpdateExpression");
  10331. }
  10332. const startPos = this.state.start;
  10333. const startLoc = this.state.startLoc;
  10334. let expr = this.parseExprSubscripts(refExpressionErrors);
  10335. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  10336. while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) {
  10337. const node = this.startNodeAt(startPos, startLoc);
  10338. node.operator = this.state.value;
  10339. node.prefix = false;
  10340. node.argument = expr;
  10341. this.checkLVal(expr, "postfix operation");
  10342. this.next();
  10343. expr = this.finishNode(node, "UpdateExpression");
  10344. }
  10345. return expr;
  10346. }
  10347. parseExprSubscripts(refExpressionErrors) {
  10348. const startPos = this.state.start;
  10349. const startLoc = this.state.startLoc;
  10350. const potentialArrowAt = this.state.potentialArrowAt;
  10351. const expr = this.parseExprAtom(refExpressionErrors);
  10352. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10353. return expr;
  10354. }
  10355. return this.parseSubscripts(expr, startPos, startLoc);
  10356. }
  10357. parseSubscripts(base, startPos, startLoc, noCalls) {
  10358. const state = {
  10359. optionalChainMember: false,
  10360. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  10361. stop: false
  10362. };
  10363. do {
  10364. base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
  10365. state.maybeAsyncArrow = false;
  10366. } while (!state.stop);
  10367. return base;
  10368. }
  10369. parseSubscript(base, startPos, startLoc, noCalls, state) {
  10370. if (!noCalls && this.eat(15)) {
  10371. return this.parseBind(base, startPos, startLoc, noCalls, state);
  10372. } else if (this.match(22)) {
  10373. return this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  10374. }
  10375. let optional = false;
  10376. if (this.match(18)) {
  10377. if (noCalls && this.lookaheadCharCode() === 40) {
  10378. state.stop = true;
  10379. return base;
  10380. }
  10381. state.optionalChainMember = optional = true;
  10382. this.next();
  10383. }
  10384. if (!noCalls && this.match(10)) {
  10385. return this.parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional);
  10386. } else {
  10387. const computed = this.eat(0);
  10388. if (computed || optional || this.eat(16)) {
  10389. return this.parseMember(base, startPos, startLoc, state, computed, optional);
  10390. } else {
  10391. state.stop = true;
  10392. return base;
  10393. }
  10394. }
  10395. }
  10396. parseMember(base, startPos, startLoc, state, computed, optional) {
  10397. const node = this.startNodeAt(startPos, startLoc);
  10398. node.object = base;
  10399. node.computed = computed;
  10400. const privateName = !computed && this.match(128) && this.state.value;
  10401. const property = computed ? this.parseExpression() : privateName ? this.parsePrivateName() : this.parseIdentifier(true);
  10402. if (privateName !== false) {
  10403. if (node.object.type === "Super") {
  10404. this.raise(startPos, ErrorMessages.SuperPrivateField);
  10405. }
  10406. this.classScope.usePrivateName(privateName, property.start);
  10407. }
  10408. node.property = property;
  10409. if (computed) {
  10410. this.expect(3);
  10411. }
  10412. if (state.optionalChainMember) {
  10413. node.optional = optional;
  10414. return this.finishNode(node, "OptionalMemberExpression");
  10415. } else {
  10416. return this.finishNode(node, "MemberExpression");
  10417. }
  10418. }
  10419. parseBind(base, startPos, startLoc, noCalls, state) {
  10420. const node = this.startNodeAt(startPos, startLoc);
  10421. node.object = base;
  10422. node.callee = this.parseNoCallExpr();
  10423. state.stop = true;
  10424. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  10425. }
  10426. parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional) {
  10427. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10428. let refExpressionErrors = null;
  10429. this.state.maybeInArrowParameters = true;
  10430. this.next();
  10431. let node = this.startNodeAt(startPos, startLoc);
  10432. node.callee = base;
  10433. if (state.maybeAsyncArrow) {
  10434. this.expressionScope.enter(newAsyncArrowScope());
  10435. refExpressionErrors = new ExpressionErrors();
  10436. }
  10437. if (state.optionalChainMember) {
  10438. node.optional = optional;
  10439. }
  10440. if (optional) {
  10441. node.arguments = this.parseCallExpressionArguments(11);
  10442. } else {
  10443. node.arguments = this.parseCallExpressionArguments(11, base.type === "Import", base.type !== "Super", node, refExpressionErrors);
  10444. }
  10445. this.finishCallExpression(node, state.optionalChainMember);
  10446. if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  10447. state.stop = true;
  10448. this.expressionScope.validateAsPattern();
  10449. this.expressionScope.exit();
  10450. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  10451. } else {
  10452. if (state.maybeAsyncArrow) {
  10453. this.checkExpressionErrors(refExpressionErrors, true);
  10454. this.expressionScope.exit();
  10455. }
  10456. this.toReferencedArguments(node);
  10457. }
  10458. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10459. return node;
  10460. }
  10461. toReferencedArguments(node, isParenthesizedExpr) {
  10462. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  10463. }
  10464. parseTaggedTemplateExpression(base, startPos, startLoc, state) {
  10465. const node = this.startNodeAt(startPos, startLoc);
  10466. node.tag = base;
  10467. node.quasi = this.parseTemplate(true);
  10468. if (state.optionalChainMember) {
  10469. this.raise(startPos, ErrorMessages.OptionalChainingNoTemplate);
  10470. }
  10471. return this.finishNode(node, "TaggedTemplateExpression");
  10472. }
  10473. atPossibleAsyncArrow(base) {
  10474. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
  10475. }
  10476. finishCallExpression(node, optional) {
  10477. if (node.callee.type === "Import") {
  10478. if (node.arguments.length === 2) {
  10479. {
  10480. if (!this.hasPlugin("moduleAttributes")) {
  10481. this.expectPlugin("importAssertions");
  10482. }
  10483. }
  10484. }
  10485. if (node.arguments.length === 0 || node.arguments.length > 2) {
  10486. this.raise(node.start, ErrorMessages.ImportCallArity, this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? "one or two arguments" : "one argument");
  10487. } else {
  10488. for (const arg of node.arguments) {
  10489. if (arg.type === "SpreadElement") {
  10490. this.raise(arg.start, ErrorMessages.ImportCallSpreadArgument);
  10491. }
  10492. }
  10493. }
  10494. }
  10495. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  10496. }
  10497. parseCallExpressionArguments(close, dynamicImport, allowPlaceholder, nodeForExtra, refExpressionErrors) {
  10498. const elts = [];
  10499. let first = true;
  10500. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  10501. this.state.inFSharpPipelineDirectBody = false;
  10502. while (!this.eat(close)) {
  10503. if (first) {
  10504. first = false;
  10505. } else {
  10506. this.expect(12);
  10507. if (this.match(close)) {
  10508. if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) {
  10509. this.raise(this.state.lastTokStart, ErrorMessages.ImportCallArgumentTrailingComma);
  10510. }
  10511. if (nodeForExtra) {
  10512. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  10513. }
  10514. this.next();
  10515. break;
  10516. }
  10517. }
  10518. elts.push(this.parseExprListItem(false, refExpressionErrors, allowPlaceholder));
  10519. }
  10520. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  10521. return elts;
  10522. }
  10523. shouldParseAsyncArrow() {
  10524. return this.match(19) && !this.canInsertSemicolon();
  10525. }
  10526. parseAsyncArrowFromCallExpression(node, call) {
  10527. var _call$extra;
  10528. this.resetPreviousNodeTrailingComments(call);
  10529. this.expect(19);
  10530. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
  10531. if (call.innerComments) {
  10532. setInnerComments(node, call.innerComments);
  10533. }
  10534. if (call.callee.trailingComments) {
  10535. setInnerComments(node, call.callee.trailingComments);
  10536. }
  10537. return node;
  10538. }
  10539. parseNoCallExpr() {
  10540. const startPos = this.state.start;
  10541. const startLoc = this.state.startLoc;
  10542. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  10543. }
  10544. parseExprAtom(refExpressionErrors) {
  10545. let node;
  10546. const {
  10547. type
  10548. } = this.state;
  10549. switch (type) {
  10550. case 73:
  10551. return this.parseSuper();
  10552. case 77:
  10553. node = this.startNode();
  10554. this.next();
  10555. if (this.match(16)) {
  10556. return this.parseImportMetaProperty(node);
  10557. }
  10558. if (!this.match(10)) {
  10559. this.raise(this.state.lastTokStart, ErrorMessages.UnsupportedImport);
  10560. }
  10561. return this.finishNode(node, "Import");
  10562. case 72:
  10563. node = this.startNode();
  10564. this.next();
  10565. return this.finishNode(node, "ThisExpression");
  10566. case 84:
  10567. {
  10568. return this.parseDo(this.startNode(), false);
  10569. }
  10570. case 50:
  10571. case 29:
  10572. {
  10573. this.readRegexp();
  10574. return this.parseRegExpLiteral(this.state.value);
  10575. }
  10576. case 124:
  10577. return this.parseNumericLiteral(this.state.value);
  10578. case 125:
  10579. return this.parseBigIntLiteral(this.state.value);
  10580. case 126:
  10581. return this.parseDecimalLiteral(this.state.value);
  10582. case 123:
  10583. return this.parseStringLiteral(this.state.value);
  10584. case 78:
  10585. return this.parseNullLiteral();
  10586. case 79:
  10587. return this.parseBooleanLiteral(true);
  10588. case 80:
  10589. return this.parseBooleanLiteral(false);
  10590. case 10:
  10591. {
  10592. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  10593. return this.parseParenAndDistinguishExpression(canBeArrow);
  10594. }
  10595. case 2:
  10596. case 1:
  10597. {
  10598. return this.parseArrayLike(this.state.type === 2 ? 4 : 3, false, true);
  10599. }
  10600. case 0:
  10601. {
  10602. return this.parseArrayLike(3, true, false, refExpressionErrors);
  10603. }
  10604. case 6:
  10605. case 7:
  10606. {
  10607. return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true);
  10608. }
  10609. case 5:
  10610. {
  10611. return this.parseObjectLike(8, false, false, refExpressionErrors);
  10612. }
  10613. case 62:
  10614. return this.parseFunctionOrFunctionSent();
  10615. case 24:
  10616. this.parseDecorators();
  10617. case 74:
  10618. node = this.startNode();
  10619. this.takeDecorators(node);
  10620. return this.parseClass(node, false);
  10621. case 71:
  10622. return this.parseNewOrNewTarget();
  10623. case 22:
  10624. return this.parseTemplate(false);
  10625. case 15:
  10626. {
  10627. node = this.startNode();
  10628. this.next();
  10629. node.object = null;
  10630. const callee = node.callee = this.parseNoCallExpr();
  10631. if (callee.type === "MemberExpression") {
  10632. return this.finishNode(node, "BindExpression");
  10633. } else {
  10634. throw this.raise(callee.start, ErrorMessages.UnsupportedBind);
  10635. }
  10636. }
  10637. case 128:
  10638. {
  10639. this.raise(this.state.start, ErrorMessages.PrivateInExpectedIn, this.state.value);
  10640. return this.parsePrivateName();
  10641. }
  10642. case 31:
  10643. {
  10644. return this.parseTopicReferenceThenEqualsSign(48, "%");
  10645. }
  10646. case 30:
  10647. {
  10648. return this.parseTopicReferenceThenEqualsSign(40, "^");
  10649. }
  10650. case 40:
  10651. case 48:
  10652. case 25:
  10653. {
  10654. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  10655. if (pipeProposal) {
  10656. return this.parseTopicReference(pipeProposal);
  10657. } else {
  10658. throw this.unexpected();
  10659. }
  10660. }
  10661. case 43:
  10662. {
  10663. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  10664. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  10665. this.expectOnePlugin(["jsx", "flow", "typescript"]);
  10666. break;
  10667. } else {
  10668. throw this.unexpected();
  10669. }
  10670. }
  10671. default:
  10672. if (tokenIsIdentifier(type)) {
  10673. if (this.isContextual(117) && this.lookaheadCharCode() === 123 && !this.hasFollowingLineBreak()) {
  10674. return this.parseModuleExpression();
  10675. }
  10676. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  10677. const containsEsc = this.state.containsEsc;
  10678. const id = this.parseIdentifier();
  10679. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  10680. const {
  10681. type
  10682. } = this.state;
  10683. if (type === 62) {
  10684. this.resetPreviousNodeTrailingComments(id);
  10685. this.next();
  10686. return this.parseFunction(this.startNodeAtNode(id), undefined, true);
  10687. } else if (tokenIsIdentifier(type)) {
  10688. if (this.lookaheadCharCode() === 61) {
  10689. return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id));
  10690. } else {
  10691. return id;
  10692. }
  10693. } else if (type === 84) {
  10694. this.resetPreviousNodeTrailingComments(id);
  10695. return this.parseDo(this.startNodeAtNode(id), true);
  10696. }
  10697. }
  10698. if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) {
  10699. this.next();
  10700. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  10701. }
  10702. return id;
  10703. } else {
  10704. throw this.unexpected();
  10705. }
  10706. }
  10707. }
  10708. parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) {
  10709. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  10710. if (pipeProposal) {
  10711. this.state.type = topicTokenType;
  10712. this.state.value = topicTokenValue;
  10713. this.state.pos--;
  10714. this.state.end--;
  10715. this.state.endLoc.column--;
  10716. return this.parseTopicReference(pipeProposal);
  10717. } else {
  10718. throw this.unexpected();
  10719. }
  10720. }
  10721. parseTopicReference(pipeProposal) {
  10722. const node = this.startNode();
  10723. const start = this.state.start;
  10724. const tokenType = this.state.type;
  10725. this.next();
  10726. return this.finishTopicReference(node, start, pipeProposal, tokenType);
  10727. }
  10728. finishTopicReference(node, start, pipeProposal, tokenType) {
  10729. if (this.testTopicReferenceConfiguration(pipeProposal, start, tokenType)) {
  10730. let nodeType;
  10731. if (pipeProposal === "smart") {
  10732. nodeType = "PipelinePrimaryTopicReference";
  10733. } else {
  10734. nodeType = "TopicReference";
  10735. }
  10736. if (!this.topicReferenceIsAllowedInCurrentContext()) {
  10737. if (pipeProposal === "smart") {
  10738. this.raise(start, ErrorMessages.PrimaryTopicNotAllowed);
  10739. } else {
  10740. this.raise(start, ErrorMessages.PipeTopicUnbound);
  10741. }
  10742. }
  10743. this.registerTopicReference();
  10744. return this.finishNode(node, nodeType);
  10745. } else {
  10746. throw this.raise(start, ErrorMessages.PipeTopicUnconfiguredToken, tokenLabelName(tokenType));
  10747. }
  10748. }
  10749. testTopicReferenceConfiguration(pipeProposal, start, tokenType) {
  10750. switch (pipeProposal) {
  10751. case "hack":
  10752. {
  10753. const pluginTopicToken = this.getPluginOption("pipelineOperator", "topicToken");
  10754. return tokenLabelName(tokenType) === pluginTopicToken;
  10755. }
  10756. case "smart":
  10757. return tokenType === 25;
  10758. default:
  10759. throw this.raise(start, ErrorMessages.PipeTopicRequiresHackPipes);
  10760. }
  10761. }
  10762. parseAsyncArrowUnaryFunction(node) {
  10763. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  10764. const params = [this.parseIdentifier()];
  10765. this.prodParam.exit();
  10766. if (this.hasPrecedingLineBreak()) {
  10767. this.raise(this.state.pos, ErrorMessages.LineTerminatorBeforeArrow);
  10768. }
  10769. this.expect(19);
  10770. this.parseArrowExpression(node, params, true);
  10771. return node;
  10772. }
  10773. parseDo(node, isAsync) {
  10774. this.expectPlugin("doExpressions");
  10775. if (isAsync) {
  10776. this.expectPlugin("asyncDoExpressions");
  10777. }
  10778. node.async = isAsync;
  10779. this.next();
  10780. const oldLabels = this.state.labels;
  10781. this.state.labels = [];
  10782. if (isAsync) {
  10783. this.prodParam.enter(PARAM_AWAIT);
  10784. node.body = this.parseBlock();
  10785. this.prodParam.exit();
  10786. } else {
  10787. node.body = this.parseBlock();
  10788. }
  10789. this.state.labels = oldLabels;
  10790. return this.finishNode(node, "DoExpression");
  10791. }
  10792. parseSuper() {
  10793. const node = this.startNode();
  10794. this.next();
  10795. if (this.match(10) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  10796. this.raise(node.start, ErrorMessages.SuperNotAllowed);
  10797. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  10798. this.raise(node.start, ErrorMessages.UnexpectedSuper);
  10799. }
  10800. if (!this.match(10) && !this.match(0) && !this.match(16)) {
  10801. this.raise(node.start, ErrorMessages.UnsupportedSuper);
  10802. }
  10803. return this.finishNode(node, "Super");
  10804. }
  10805. parsePrivateName() {
  10806. const node = this.startNode();
  10807. const id = this.startNodeAt(this.state.start + 1, new Position(this.state.curLine, this.state.start + 1 - this.state.lineStart));
  10808. const name = this.state.value;
  10809. this.next();
  10810. node.id = this.createIdentifier(id, name);
  10811. return this.finishNode(node, "PrivateName");
  10812. }
  10813. parseFunctionOrFunctionSent() {
  10814. const node = this.startNode();
  10815. this.next();
  10816. if (this.prodParam.hasYield && this.match(16)) {
  10817. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  10818. this.next();
  10819. if (this.match(96)) {
  10820. this.expectPlugin("functionSent");
  10821. } else if (!this.hasPlugin("functionSent")) {
  10822. this.unexpected();
  10823. }
  10824. return this.parseMetaProperty(node, meta, "sent");
  10825. }
  10826. return this.parseFunction(node);
  10827. }
  10828. parseMetaProperty(node, meta, propertyName) {
  10829. node.meta = meta;
  10830. const containsEsc = this.state.containsEsc;
  10831. node.property = this.parseIdentifier(true);
  10832. if (node.property.name !== propertyName || containsEsc) {
  10833. this.raise(node.property.start, ErrorMessages.UnsupportedMetaProperty, meta.name, propertyName);
  10834. }
  10835. return this.finishNode(node, "MetaProperty");
  10836. }
  10837. parseImportMetaProperty(node) {
  10838. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  10839. this.next();
  10840. if (this.isContextual(94)) {
  10841. if (!this.inModule) {
  10842. this.raise(id.start, SourceTypeModuleErrorMessages.ImportMetaOutsideModule);
  10843. }
  10844. this.sawUnambiguousESM = true;
  10845. }
  10846. return this.parseMetaProperty(node, id, "meta");
  10847. }
  10848. parseLiteralAtNode(value, type, node) {
  10849. this.addExtra(node, "rawValue", value);
  10850. this.addExtra(node, "raw", this.input.slice(node.start, this.state.end));
  10851. node.value = value;
  10852. this.next();
  10853. return this.finishNode(node, type);
  10854. }
  10855. parseLiteral(value, type) {
  10856. const node = this.startNode();
  10857. return this.parseLiteralAtNode(value, type, node);
  10858. }
  10859. parseStringLiteral(value) {
  10860. return this.parseLiteral(value, "StringLiteral");
  10861. }
  10862. parseNumericLiteral(value) {
  10863. return this.parseLiteral(value, "NumericLiteral");
  10864. }
  10865. parseBigIntLiteral(value) {
  10866. return this.parseLiteral(value, "BigIntLiteral");
  10867. }
  10868. parseDecimalLiteral(value) {
  10869. return this.parseLiteral(value, "DecimalLiteral");
  10870. }
  10871. parseRegExpLiteral(value) {
  10872. const node = this.parseLiteral(value.value, "RegExpLiteral");
  10873. node.pattern = value.pattern;
  10874. node.flags = value.flags;
  10875. return node;
  10876. }
  10877. parseBooleanLiteral(value) {
  10878. const node = this.startNode();
  10879. node.value = value;
  10880. this.next();
  10881. return this.finishNode(node, "BooleanLiteral");
  10882. }
  10883. parseNullLiteral() {
  10884. const node = this.startNode();
  10885. this.next();
  10886. return this.finishNode(node, "NullLiteral");
  10887. }
  10888. parseParenAndDistinguishExpression(canBeArrow) {
  10889. const startPos = this.state.start;
  10890. const startLoc = this.state.startLoc;
  10891. let val;
  10892. this.next();
  10893. this.expressionScope.enter(newArrowHeadScope());
  10894. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10895. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  10896. this.state.maybeInArrowParameters = true;
  10897. this.state.inFSharpPipelineDirectBody = false;
  10898. const innerStartPos = this.state.start;
  10899. const innerStartLoc = this.state.startLoc;
  10900. const exprList = [];
  10901. const refExpressionErrors = new ExpressionErrors();
  10902. let first = true;
  10903. let spreadStart;
  10904. let optionalCommaStart;
  10905. while (!this.match(11)) {
  10906. if (first) {
  10907. first = false;
  10908. } else {
  10909. this.expect(12, refExpressionErrors.optionalParameters === -1 ? null : refExpressionErrors.optionalParameters);
  10910. if (this.match(11)) {
  10911. optionalCommaStart = this.state.start;
  10912. break;
  10913. }
  10914. }
  10915. if (this.match(21)) {
  10916. const spreadNodeStartPos = this.state.start;
  10917. const spreadNodeStartLoc = this.state.startLoc;
  10918. spreadStart = this.state.start;
  10919. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  10920. this.checkCommaAfterRest(41);
  10921. break;
  10922. } else {
  10923. exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem));
  10924. }
  10925. }
  10926. const innerEndPos = this.state.lastTokEnd;
  10927. const innerEndLoc = this.state.lastTokEndLoc;
  10928. this.expect(11);
  10929. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10930. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  10931. let arrowNode = this.startNodeAt(startPos, startLoc);
  10932. if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) {
  10933. this.expressionScope.validateAsPattern();
  10934. this.expressionScope.exit();
  10935. this.parseArrowExpression(arrowNode, exprList, false);
  10936. return arrowNode;
  10937. }
  10938. this.expressionScope.exit();
  10939. if (!exprList.length) {
  10940. this.unexpected(this.state.lastTokStart);
  10941. }
  10942. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  10943. if (spreadStart) this.unexpected(spreadStart);
  10944. this.checkExpressionErrors(refExpressionErrors, true);
  10945. this.toReferencedListDeep(exprList, true);
  10946. if (exprList.length > 1) {
  10947. val = this.startNodeAt(innerStartPos, innerStartLoc);
  10948. val.expressions = exprList;
  10949. this.finishNode(val, "SequenceExpression");
  10950. this.resetEndLocation(val, innerEndPos, innerEndLoc);
  10951. } else {
  10952. val = exprList[0];
  10953. }
  10954. if (!this.options.createParenthesizedExpressions) {
  10955. this.addExtra(val, "parenthesized", true);
  10956. this.addExtra(val, "parenStart", startPos);
  10957. this.takeSurroundingComments(val, startPos, this.state.lastTokEnd);
  10958. return val;
  10959. }
  10960. const parenExpression = this.startNodeAt(startPos, startLoc);
  10961. parenExpression.expression = val;
  10962. this.finishNode(parenExpression, "ParenthesizedExpression");
  10963. return parenExpression;
  10964. }
  10965. shouldParseArrow(params) {
  10966. return !this.canInsertSemicolon();
  10967. }
  10968. parseArrow(node) {
  10969. if (this.eat(19)) {
  10970. return node;
  10971. }
  10972. }
  10973. parseParenItem(node, startPos, startLoc) {
  10974. return node;
  10975. }
  10976. parseNewOrNewTarget() {
  10977. const node = this.startNode();
  10978. this.next();
  10979. if (this.match(16)) {
  10980. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  10981. this.next();
  10982. const metaProp = this.parseMetaProperty(node, meta, "target");
  10983. if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
  10984. this.raise(metaProp.start, ErrorMessages.UnexpectedNewTarget);
  10985. }
  10986. return metaProp;
  10987. }
  10988. return this.parseNew(node);
  10989. }
  10990. parseNew(node) {
  10991. node.callee = this.parseNoCallExpr();
  10992. if (node.callee.type === "Import") {
  10993. this.raise(node.callee.start, ErrorMessages.ImportCallNotNewExpression);
  10994. } else if (this.isOptionalChain(node.callee)) {
  10995. this.raise(this.state.lastTokEnd, ErrorMessages.OptionalChainingNoNew);
  10996. } else if (this.eat(18)) {
  10997. this.raise(this.state.start, ErrorMessages.OptionalChainingNoNew);
  10998. }
  10999. this.parseNewArguments(node);
  11000. return this.finishNode(node, "NewExpression");
  11001. }
  11002. parseNewArguments(node) {
  11003. if (this.eat(10)) {
  11004. const args = this.parseExprList(11);
  11005. this.toReferencedList(args);
  11006. node.arguments = args;
  11007. } else {
  11008. node.arguments = [];
  11009. }
  11010. }
  11011. parseTemplateElement(isTagged) {
  11012. const elem = this.startNode();
  11013. if (this.state.value === null) {
  11014. if (!isTagged) {
  11015. this.raise(this.state.start + 1, ErrorMessages.InvalidEscapeSequenceTemplate);
  11016. }
  11017. }
  11018. elem.value = {
  11019. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  11020. cooked: this.state.value
  11021. };
  11022. this.next();
  11023. elem.tail = this.match(22);
  11024. return this.finishNode(elem, "TemplateElement");
  11025. }
  11026. parseTemplate(isTagged) {
  11027. const node = this.startNode();
  11028. this.next();
  11029. node.expressions = [];
  11030. let curElt = this.parseTemplateElement(isTagged);
  11031. node.quasis = [curElt];
  11032. while (!curElt.tail) {
  11033. this.expect(23);
  11034. node.expressions.push(this.parseTemplateSubstitution());
  11035. this.expect(8);
  11036. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  11037. }
  11038. this.next();
  11039. return this.finishNode(node, "TemplateLiteral");
  11040. }
  11041. parseTemplateSubstitution() {
  11042. return this.parseExpression();
  11043. }
  11044. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  11045. if (isRecord) {
  11046. this.expectPlugin("recordAndTuple");
  11047. }
  11048. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11049. this.state.inFSharpPipelineDirectBody = false;
  11050. const propHash = Object.create(null);
  11051. let first = true;
  11052. const node = this.startNode();
  11053. node.properties = [];
  11054. this.next();
  11055. while (!this.match(close)) {
  11056. if (first) {
  11057. first = false;
  11058. } else {
  11059. this.expect(12);
  11060. if (this.match(close)) {
  11061. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  11062. break;
  11063. }
  11064. }
  11065. let prop;
  11066. if (isPattern) {
  11067. prop = this.parseBindingProperty();
  11068. } else {
  11069. prop = this.parsePropertyDefinition(refExpressionErrors);
  11070. this.checkProto(prop, isRecord, propHash, refExpressionErrors);
  11071. }
  11072. if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") {
  11073. this.raise(prop.start, ErrorMessages.InvalidRecordProperty);
  11074. }
  11075. if (prop.shorthand) {
  11076. this.addExtra(prop, "shorthand", true);
  11077. }
  11078. node.properties.push(prop);
  11079. }
  11080. this.next();
  11081. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11082. let type = "ObjectExpression";
  11083. if (isPattern) {
  11084. type = "ObjectPattern";
  11085. } else if (isRecord) {
  11086. type = "RecordExpression";
  11087. }
  11088. return this.finishNode(node, type);
  11089. }
  11090. maybeAsyncOrAccessorProp(prop) {
  11091. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(49));
  11092. }
  11093. parsePropertyDefinition(refExpressionErrors) {
  11094. let decorators = [];
  11095. if (this.match(24)) {
  11096. if (this.hasPlugin("decorators")) {
  11097. this.raise(this.state.start, ErrorMessages.UnsupportedPropertyDecorator);
  11098. }
  11099. while (this.match(24)) {
  11100. decorators.push(this.parseDecorator());
  11101. }
  11102. }
  11103. const prop = this.startNode();
  11104. let isAsync = false;
  11105. let isAccessor = false;
  11106. let startPos;
  11107. let startLoc;
  11108. if (this.match(21)) {
  11109. if (decorators.length) this.unexpected();
  11110. return this.parseSpread();
  11111. }
  11112. if (decorators.length) {
  11113. prop.decorators = decorators;
  11114. decorators = [];
  11115. }
  11116. prop.method = false;
  11117. if (refExpressionErrors) {
  11118. startPos = this.state.start;
  11119. startLoc = this.state.startLoc;
  11120. }
  11121. let isGenerator = this.eat(49);
  11122. this.parsePropertyNamePrefixOperator(prop);
  11123. const containsEsc = this.state.containsEsc;
  11124. const key = this.parsePropertyName(prop);
  11125. if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  11126. const keyName = key.name;
  11127. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  11128. isAsync = true;
  11129. this.resetPreviousNodeTrailingComments(key);
  11130. isGenerator = this.eat(49);
  11131. this.parsePropertyName(prop);
  11132. }
  11133. if (keyName === "get" || keyName === "set") {
  11134. isAccessor = true;
  11135. this.resetPreviousNodeTrailingComments(key);
  11136. prop.kind = keyName;
  11137. if (this.match(49)) {
  11138. isGenerator = true;
  11139. this.raise(this.state.pos, ErrorMessages.AccessorIsGenerator, keyName);
  11140. this.next();
  11141. }
  11142. this.parsePropertyName(prop);
  11143. }
  11144. }
  11145. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors);
  11146. return prop;
  11147. }
  11148. getGetterSetterExpectedParamCount(method) {
  11149. return method.kind === "get" ? 0 : 1;
  11150. }
  11151. getObjectOrClassMethodParams(method) {
  11152. return method.params;
  11153. }
  11154. checkGetterSetterParams(method) {
  11155. var _params;
  11156. const paramCount = this.getGetterSetterExpectedParamCount(method);
  11157. const params = this.getObjectOrClassMethodParams(method);
  11158. const start = method.start;
  11159. if (params.length !== paramCount) {
  11160. if (method.kind === "get") {
  11161. this.raise(start, ErrorMessages.BadGetterArity);
  11162. } else {
  11163. this.raise(start, ErrorMessages.BadSetterArity);
  11164. }
  11165. }
  11166. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  11167. this.raise(start, ErrorMessages.BadSetterRestParameter);
  11168. }
  11169. }
  11170. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  11171. if (isAccessor) {
  11172. this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  11173. this.checkGetterSetterParams(prop);
  11174. return prop;
  11175. }
  11176. if (isAsync || isGenerator || this.match(10)) {
  11177. if (isPattern) this.unexpected();
  11178. prop.kind = "method";
  11179. prop.method = true;
  11180. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  11181. }
  11182. }
  11183. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  11184. prop.shorthand = false;
  11185. if (this.eat(14)) {
  11186. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
  11187. return this.finishNode(prop, "ObjectProperty");
  11188. }
  11189. if (!prop.computed && prop.key.type === "Identifier") {
  11190. this.checkReservedWord(prop.key.name, prop.key.start, true, false);
  11191. if (isPattern) {
  11192. prop.value = this.parseMaybeDefault(startPos, startLoc, cloneIdentifier(prop.key));
  11193. } else if (this.match(27) && refExpressionErrors) {
  11194. if (refExpressionErrors.shorthandAssign === -1) {
  11195. refExpressionErrors.shorthandAssign = this.state.start;
  11196. }
  11197. prop.value = this.parseMaybeDefault(startPos, startLoc, cloneIdentifier(prop.key));
  11198. } else {
  11199. prop.value = cloneIdentifier(prop.key);
  11200. }
  11201. prop.shorthand = true;
  11202. return this.finishNode(prop, "ObjectProperty");
  11203. }
  11204. }
  11205. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  11206. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  11207. if (!node) this.unexpected();
  11208. return node;
  11209. }
  11210. parsePropertyName(prop) {
  11211. if (this.eat(0)) {
  11212. prop.computed = true;
  11213. prop.key = this.parseMaybeAssignAllowIn();
  11214. this.expect(3);
  11215. } else {
  11216. const {
  11217. type,
  11218. value
  11219. } = this.state;
  11220. let key;
  11221. if (tokenIsKeywordOrIdentifier(type)) {
  11222. key = this.parseIdentifier(true);
  11223. } else {
  11224. switch (type) {
  11225. case 124:
  11226. key = this.parseNumericLiteral(value);
  11227. break;
  11228. case 123:
  11229. key = this.parseStringLiteral(value);
  11230. break;
  11231. case 125:
  11232. key = this.parseBigIntLiteral(value);
  11233. break;
  11234. case 126:
  11235. key = this.parseDecimalLiteral(value);
  11236. break;
  11237. case 128:
  11238. {
  11239. const privateKeyPos = this.state.start + 1;
  11240. this.raise(privateKeyPos, ErrorMessages.UnexpectedPrivateField);
  11241. key = this.parsePrivateName();
  11242. break;
  11243. }
  11244. default:
  11245. throw this.unexpected();
  11246. }
  11247. }
  11248. prop.key = key;
  11249. if (type !== 128) {
  11250. prop.computed = false;
  11251. }
  11252. }
  11253. return prop.key;
  11254. }
  11255. initFunction(node, isAsync) {
  11256. node.id = null;
  11257. node.generator = false;
  11258. node.async = !!isAsync;
  11259. }
  11260. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  11261. this.initFunction(node, isAsync);
  11262. node.generator = !!isGenerator;
  11263. const allowModifiers = isConstructor;
  11264. this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  11265. this.prodParam.enter(functionFlags(isAsync, node.generator));
  11266. this.parseFunctionParams(node, allowModifiers);
  11267. this.parseFunctionBodyAndFinish(node, type, true);
  11268. this.prodParam.exit();
  11269. this.scope.exit();
  11270. return node;
  11271. }
  11272. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  11273. if (isTuple) {
  11274. this.expectPlugin("recordAndTuple");
  11275. }
  11276. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11277. this.state.inFSharpPipelineDirectBody = false;
  11278. const node = this.startNode();
  11279. this.next();
  11280. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  11281. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11282. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  11283. }
  11284. parseArrowExpression(node, params, isAsync, trailingCommaPos) {
  11285. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  11286. let flags = functionFlags(isAsync, false);
  11287. if (!this.match(0) && this.prodParam.hasIn) {
  11288. flags |= PARAM_IN;
  11289. }
  11290. this.prodParam.enter(flags);
  11291. this.initFunction(node, isAsync);
  11292. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  11293. if (params) {
  11294. this.state.maybeInArrowParameters = true;
  11295. this.setArrowFunctionParameters(node, params, trailingCommaPos);
  11296. }
  11297. this.state.maybeInArrowParameters = false;
  11298. this.parseFunctionBody(node, true);
  11299. this.prodParam.exit();
  11300. this.scope.exit();
  11301. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  11302. return this.finishNode(node, "ArrowFunctionExpression");
  11303. }
  11304. setArrowFunctionParameters(node, params, trailingCommaPos) {
  11305. node.params = this.toAssignableList(params, trailingCommaPos, false);
  11306. }
  11307. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  11308. this.parseFunctionBody(node, false, isMethod);
  11309. this.finishNode(node, type);
  11310. }
  11311. parseFunctionBody(node, allowExpression, isMethod = false) {
  11312. const isExpression = allowExpression && !this.match(5);
  11313. this.expressionScope.enter(newExpressionScope());
  11314. if (isExpression) {
  11315. node.body = this.parseMaybeAssign();
  11316. this.checkParams(node, false, allowExpression, false);
  11317. } else {
  11318. const oldStrict = this.state.strict;
  11319. const oldLabels = this.state.labels;
  11320. this.state.labels = [];
  11321. this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
  11322. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  11323. const nonSimple = !this.isSimpleParamList(node.params);
  11324. if (hasStrictModeDirective && nonSimple) {
  11325. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  11326. this.raise(errorPos, ErrorMessages.IllegalLanguageModeDirective);
  11327. }
  11328. const strictModeChanged = !oldStrict && this.state.strict;
  11329. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  11330. if (this.state.strict && node.id) {
  11331. this.checkLVal(node.id, "function name", BIND_OUTSIDE, undefined, undefined, strictModeChanged);
  11332. }
  11333. });
  11334. this.prodParam.exit();
  11335. this.state.labels = oldLabels;
  11336. }
  11337. this.expressionScope.exit();
  11338. }
  11339. isSimpleParamList(params) {
  11340. for (let i = 0, len = params.length; i < len; i++) {
  11341. if (params[i].type !== "Identifier") return false;
  11342. }
  11343. return true;
  11344. }
  11345. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  11346. const checkClashes = new Set();
  11347. for (const param of node.params) {
  11348. this.checkLVal(param, "function parameter list", BIND_VAR, allowDuplicates ? null : checkClashes, undefined, strictModeChanged);
  11349. }
  11350. }
  11351. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  11352. const elts = [];
  11353. let first = true;
  11354. while (!this.eat(close)) {
  11355. if (first) {
  11356. first = false;
  11357. } else {
  11358. this.expect(12);
  11359. if (this.match(close)) {
  11360. if (nodeForExtra) {
  11361. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  11362. }
  11363. this.next();
  11364. break;
  11365. }
  11366. }
  11367. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  11368. }
  11369. return elts;
  11370. }
  11371. parseExprListItem(allowEmpty, refExpressionErrors, allowPlaceholder) {
  11372. let elt;
  11373. if (this.match(12)) {
  11374. if (!allowEmpty) {
  11375. this.raise(this.state.pos, ErrorMessages.UnexpectedToken, ",");
  11376. }
  11377. elt = null;
  11378. } else if (this.match(21)) {
  11379. const spreadNodeStartPos = this.state.start;
  11380. const spreadNodeStartLoc = this.state.startLoc;
  11381. elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartPos, spreadNodeStartLoc);
  11382. } else if (this.match(17)) {
  11383. this.expectPlugin("partialApplication");
  11384. if (!allowPlaceholder) {
  11385. this.raise(this.state.start, ErrorMessages.UnexpectedArgumentPlaceholder);
  11386. }
  11387. const node = this.startNode();
  11388. this.next();
  11389. elt = this.finishNode(node, "ArgumentPlaceholder");
  11390. } else {
  11391. elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem);
  11392. }
  11393. return elt;
  11394. }
  11395. parseIdentifier(liberal) {
  11396. const node = this.startNode();
  11397. const name = this.parseIdentifierName(node.start, liberal);
  11398. return this.createIdentifier(node, name);
  11399. }
  11400. createIdentifier(node, name) {
  11401. node.name = name;
  11402. node.loc.identifierName = name;
  11403. return this.finishNode(node, "Identifier");
  11404. }
  11405. parseIdentifierName(pos, liberal) {
  11406. let name;
  11407. const {
  11408. start,
  11409. type
  11410. } = this.state;
  11411. if (tokenIsKeywordOrIdentifier(type)) {
  11412. name = this.state.value;
  11413. } else {
  11414. throw this.unexpected();
  11415. }
  11416. const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type);
  11417. if (liberal) {
  11418. if (tokenIsKeyword) {
  11419. this.replaceToken(122);
  11420. }
  11421. } else {
  11422. this.checkReservedWord(name, start, tokenIsKeyword, false);
  11423. }
  11424. this.next();
  11425. return name;
  11426. }
  11427. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  11428. if (word.length > 10) {
  11429. return;
  11430. }
  11431. if (!canBeReservedWord(word)) {
  11432. return;
  11433. }
  11434. if (word === "yield") {
  11435. if (this.prodParam.hasYield) {
  11436. this.raise(startLoc, ErrorMessages.YieldBindingIdentifier);
  11437. return;
  11438. }
  11439. } else if (word === "await") {
  11440. if (this.prodParam.hasAwait) {
  11441. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifier);
  11442. return;
  11443. } else if (this.scope.inStaticBlock) {
  11444. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifierInStaticBlock);
  11445. return;
  11446. } else {
  11447. this.expressionScope.recordAsyncArrowParametersError(startLoc, ErrorMessages.AwaitBindingIdentifier);
  11448. }
  11449. } else if (word === "arguments") {
  11450. if (this.scope.inClassAndNotInNonArrowFunction) {
  11451. this.raise(startLoc, ErrorMessages.ArgumentsInClass);
  11452. return;
  11453. }
  11454. }
  11455. if (checkKeywords && isKeyword(word)) {
  11456. this.raise(startLoc, ErrorMessages.UnexpectedKeyword, word);
  11457. return;
  11458. }
  11459. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  11460. if (reservedTest(word, this.inModule)) {
  11461. this.raise(startLoc, ErrorMessages.UnexpectedReservedWord, word);
  11462. }
  11463. }
  11464. isAwaitAllowed() {
  11465. if (this.prodParam.hasAwait) return true;
  11466. if (this.options.allowAwaitOutsideFunction && !this.scope.inFunction) {
  11467. return true;
  11468. }
  11469. return false;
  11470. }
  11471. parseAwait(startPos, startLoc) {
  11472. const node = this.startNodeAt(startPos, startLoc);
  11473. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.AwaitExpressionFormalParameter);
  11474. if (this.eat(49)) {
  11475. this.raise(node.start, ErrorMessages.ObsoleteAwaitStar);
  11476. }
  11477. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  11478. if (this.isAmbiguousAwait()) {
  11479. this.ambiguousScriptDifferentAst = true;
  11480. } else {
  11481. this.sawUnambiguousESM = true;
  11482. }
  11483. }
  11484. if (!this.state.soloAwait) {
  11485. node.argument = this.parseMaybeUnary(null, true);
  11486. }
  11487. return this.finishNode(node, "AwaitExpression");
  11488. }
  11489. isAmbiguousAwait() {
  11490. return this.hasPrecedingLineBreak() || this.match(47) || this.match(10) || this.match(0) || this.match(22) || this.match(127) || this.match(50) || this.hasPlugin("v8intrinsic") && this.match(48);
  11491. }
  11492. parseYield() {
  11493. const node = this.startNode();
  11494. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.YieldInParameter);
  11495. this.next();
  11496. let delegating = false;
  11497. let argument = null;
  11498. if (!this.hasPrecedingLineBreak()) {
  11499. delegating = this.eat(49);
  11500. switch (this.state.type) {
  11501. case 13:
  11502. case 129:
  11503. case 8:
  11504. case 11:
  11505. case 3:
  11506. case 9:
  11507. case 14:
  11508. case 12:
  11509. if (!delegating) break;
  11510. default:
  11511. argument = this.parseMaybeAssign();
  11512. }
  11513. }
  11514. node.delegate = delegating;
  11515. node.argument = argument;
  11516. return this.finishNode(node, "YieldExpression");
  11517. }
  11518. checkPipelineAtInfixOperator(left, leftStartPos) {
  11519. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  11520. if (left.type === "SequenceExpression") {
  11521. this.raise(leftStartPos, ErrorMessages.PipelineHeadSequenceExpression);
  11522. }
  11523. }
  11524. }
  11525. checkHackPipeBodyEarlyErrors(startPos) {
  11526. if (!this.topicReferenceWasUsedInCurrentContext()) {
  11527. this.raise(startPos, ErrorMessages.PipeTopicUnused);
  11528. }
  11529. }
  11530. parseSmartPipelineBodyInStyle(childExpr, startPos, startLoc) {
  11531. const bodyNode = this.startNodeAt(startPos, startLoc);
  11532. if (this.isSimpleReference(childExpr)) {
  11533. bodyNode.callee = childExpr;
  11534. return this.finishNode(bodyNode, "PipelineBareFunction");
  11535. } else {
  11536. this.checkSmartPipeTopicBodyEarlyErrors(startPos);
  11537. bodyNode.expression = childExpr;
  11538. return this.finishNode(bodyNode, "PipelineTopicExpression");
  11539. }
  11540. }
  11541. isSimpleReference(expression) {
  11542. switch (expression.type) {
  11543. case "MemberExpression":
  11544. return !expression.computed && this.isSimpleReference(expression.object);
  11545. case "Identifier":
  11546. return true;
  11547. default:
  11548. return false;
  11549. }
  11550. }
  11551. checkSmartPipeTopicBodyEarlyErrors(startPos) {
  11552. if (this.match(19)) {
  11553. throw this.raise(this.state.start, ErrorMessages.PipelineBodyNoArrow);
  11554. } else if (!this.topicReferenceWasUsedInCurrentContext()) {
  11555. this.raise(startPos, ErrorMessages.PipelineTopicUnused);
  11556. }
  11557. }
  11558. withTopicBindingContext(callback) {
  11559. const outerContextTopicState = this.state.topicContext;
  11560. this.state.topicContext = {
  11561. maxNumOfResolvableTopics: 1,
  11562. maxTopicIndex: null
  11563. };
  11564. try {
  11565. return callback();
  11566. } finally {
  11567. this.state.topicContext = outerContextTopicState;
  11568. }
  11569. }
  11570. withSmartMixTopicForbiddingContext(callback) {
  11571. const proposal = this.getPluginOption("pipelineOperator", "proposal");
  11572. if (proposal === "smart") {
  11573. const outerContextTopicState = this.state.topicContext;
  11574. this.state.topicContext = {
  11575. maxNumOfResolvableTopics: 0,
  11576. maxTopicIndex: null
  11577. };
  11578. try {
  11579. return callback();
  11580. } finally {
  11581. this.state.topicContext = outerContextTopicState;
  11582. }
  11583. } else {
  11584. return callback();
  11585. }
  11586. }
  11587. withSoloAwaitPermittingContext(callback) {
  11588. const outerContextSoloAwaitState = this.state.soloAwait;
  11589. this.state.soloAwait = true;
  11590. try {
  11591. return callback();
  11592. } finally {
  11593. this.state.soloAwait = outerContextSoloAwaitState;
  11594. }
  11595. }
  11596. allowInAnd(callback) {
  11597. const flags = this.prodParam.currentFlags();
  11598. const prodParamToSet = PARAM_IN & ~flags;
  11599. if (prodParamToSet) {
  11600. this.prodParam.enter(flags | PARAM_IN);
  11601. try {
  11602. return callback();
  11603. } finally {
  11604. this.prodParam.exit();
  11605. }
  11606. }
  11607. return callback();
  11608. }
  11609. disallowInAnd(callback) {
  11610. const flags = this.prodParam.currentFlags();
  11611. const prodParamToClear = PARAM_IN & flags;
  11612. if (prodParamToClear) {
  11613. this.prodParam.enter(flags & ~PARAM_IN);
  11614. try {
  11615. return callback();
  11616. } finally {
  11617. this.prodParam.exit();
  11618. }
  11619. }
  11620. return callback();
  11621. }
  11622. registerTopicReference() {
  11623. this.state.topicContext.maxTopicIndex = 0;
  11624. }
  11625. topicReferenceIsAllowedInCurrentContext() {
  11626. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  11627. }
  11628. topicReferenceWasUsedInCurrentContext() {
  11629. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  11630. }
  11631. parseFSharpPipelineBody(prec) {
  11632. const startPos = this.state.start;
  11633. const startLoc = this.state.startLoc;
  11634. this.state.potentialArrowAt = this.state.start;
  11635. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11636. this.state.inFSharpPipelineDirectBody = true;
  11637. const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startPos, startLoc, prec);
  11638. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11639. return ret;
  11640. }
  11641. parseModuleExpression() {
  11642. this.expectPlugin("moduleBlocks");
  11643. const node = this.startNode();
  11644. this.next();
  11645. this.eat(5);
  11646. const revertScopes = this.initializeScopes(true);
  11647. this.enterInitialScopes();
  11648. const program = this.startNode();
  11649. try {
  11650. node.body = this.parseProgram(program, 8, "module");
  11651. } finally {
  11652. revertScopes();
  11653. }
  11654. this.eat(8);
  11655. return this.finishNode(node, "ModuleExpression");
  11656. }
  11657. parsePropertyNamePrefixOperator(prop) {}
  11658. }
  11659. const loopLabel = {
  11660. kind: "loop"
  11661. },
  11662. switchLabel = {
  11663. kind: "switch"
  11664. };
  11665. const FUNC_NO_FLAGS = 0b000,
  11666. FUNC_STATEMENT = 0b001,
  11667. FUNC_HANGING_STATEMENT = 0b010,
  11668. FUNC_NULLABLE_ID = 0b100;
  11669. const loneSurrogate = /[\uD800-\uDFFF]/u;
  11670. const keywordRelationalOperator = /in(?:stanceof)?/y;
  11671. function babel7CompatTokens(tokens) {
  11672. for (let i = 0; i < tokens.length; i++) {
  11673. const token = tokens[i];
  11674. const {
  11675. type
  11676. } = token;
  11677. if (type === 128) {
  11678. {
  11679. const {
  11680. loc,
  11681. start,
  11682. value,
  11683. end
  11684. } = token;
  11685. const hashEndPos = start + 1;
  11686. const hashEndLoc = new Position(loc.start.line, loc.start.column + 1);
  11687. tokens.splice(i, 1, new Token({
  11688. type: getExportedToken(25),
  11689. value: "#",
  11690. start: start,
  11691. end: hashEndPos,
  11692. startLoc: loc.start,
  11693. endLoc: hashEndLoc
  11694. }), new Token({
  11695. type: getExportedToken(122),
  11696. value: value,
  11697. start: hashEndPos,
  11698. end: end,
  11699. startLoc: hashEndLoc,
  11700. endLoc: loc.end
  11701. }));
  11702. i++;
  11703. continue;
  11704. }
  11705. }
  11706. if (typeof type === "number") {
  11707. token.type = getExportedToken(type);
  11708. }
  11709. }
  11710. return tokens;
  11711. }
  11712. class StatementParser extends ExpressionParser {
  11713. parseTopLevel(file, program) {
  11714. file.program = this.parseProgram(program);
  11715. file.comments = this.state.comments;
  11716. if (this.options.tokens) file.tokens = babel7CompatTokens(this.tokens);
  11717. return this.finishNode(file, "File");
  11718. }
  11719. parseProgram(program, end = 129, sourceType = this.options.sourceType) {
  11720. program.sourceType = sourceType;
  11721. program.interpreter = this.parseInterpreterDirective();
  11722. this.parseBlockBody(program, true, true, end);
  11723. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  11724. for (const [name] of Array.from(this.scope.undefinedExports)) {
  11725. const pos = this.scope.undefinedExports.get(name);
  11726. this.raise(pos, ErrorMessages.ModuleExportUndefined, name);
  11727. }
  11728. }
  11729. return this.finishNode(program, "Program");
  11730. }
  11731. stmtToDirective(stmt) {
  11732. const directive = stmt;
  11733. directive.type = "Directive";
  11734. directive.value = directive.expression;
  11735. delete directive.expression;
  11736. const directiveLiteral = directive.value;
  11737. const expressionValue = directiveLiteral.value;
  11738. const raw = this.input.slice(directiveLiteral.start, directiveLiteral.end);
  11739. const val = directiveLiteral.value = raw.slice(1, -1);
  11740. this.addExtra(directiveLiteral, "raw", raw);
  11741. this.addExtra(directiveLiteral, "rawValue", val);
  11742. this.addExtra(directiveLiteral, "expressionValue", expressionValue);
  11743. directiveLiteral.type = "DirectiveLiteral";
  11744. return directive;
  11745. }
  11746. parseInterpreterDirective() {
  11747. if (!this.match(26)) {
  11748. return null;
  11749. }
  11750. const node = this.startNode();
  11751. node.value = this.state.value;
  11752. this.next();
  11753. return this.finishNode(node, "InterpreterDirective");
  11754. }
  11755. isLet(context) {
  11756. if (!this.isContextual(93)) {
  11757. return false;
  11758. }
  11759. return this.isLetKeyword(context);
  11760. }
  11761. isLetKeyword(context) {
  11762. const next = this.nextTokenStart();
  11763. const nextCh = this.codePointAtPos(next);
  11764. if (nextCh === 92 || nextCh === 91) {
  11765. return true;
  11766. }
  11767. if (context) return false;
  11768. if (nextCh === 123) return true;
  11769. if (isIdentifierStart(nextCh)) {
  11770. keywordRelationalOperator.lastIndex = next;
  11771. if (keywordRelationalOperator.test(this.input)) {
  11772. const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex);
  11773. if (!isIdentifierChar(endCh) && endCh !== 92) {
  11774. return false;
  11775. }
  11776. }
  11777. return true;
  11778. }
  11779. return false;
  11780. }
  11781. parseStatement(context, topLevel) {
  11782. if (this.match(24)) {
  11783. this.parseDecorators(true);
  11784. }
  11785. return this.parseStatementContent(context, topLevel);
  11786. }
  11787. parseStatementContent(context, topLevel) {
  11788. let starttype = this.state.type;
  11789. const node = this.startNode();
  11790. let kind;
  11791. if (this.isLet(context)) {
  11792. starttype = 68;
  11793. kind = "let";
  11794. }
  11795. switch (starttype) {
  11796. case 54:
  11797. return this.parseBreakContinueStatement(node, true);
  11798. case 57:
  11799. return this.parseBreakContinueStatement(node, false);
  11800. case 58:
  11801. return this.parseDebuggerStatement(node);
  11802. case 84:
  11803. return this.parseDoStatement(node);
  11804. case 85:
  11805. return this.parseForStatement(node);
  11806. case 62:
  11807. if (this.lookaheadCharCode() === 46) break;
  11808. if (context) {
  11809. if (this.state.strict) {
  11810. this.raise(this.state.start, ErrorMessages.StrictFunction);
  11811. } else if (context !== "if" && context !== "label") {
  11812. this.raise(this.state.start, ErrorMessages.SloppyFunction);
  11813. }
  11814. }
  11815. return this.parseFunctionStatement(node, false, !context);
  11816. case 74:
  11817. if (context) this.unexpected();
  11818. return this.parseClass(node, true);
  11819. case 63:
  11820. return this.parseIfStatement(node);
  11821. case 64:
  11822. return this.parseReturnStatement(node);
  11823. case 65:
  11824. return this.parseSwitchStatement(node);
  11825. case 66:
  11826. return this.parseThrowStatement(node);
  11827. case 67:
  11828. return this.parseTryStatement(node);
  11829. case 69:
  11830. case 68:
  11831. kind = kind || this.state.value;
  11832. if (context && kind !== "var") {
  11833. this.raise(this.state.start, ErrorMessages.UnexpectedLexicalDeclaration);
  11834. }
  11835. return this.parseVarStatement(node, kind);
  11836. case 86:
  11837. return this.parseWhileStatement(node);
  11838. case 70:
  11839. return this.parseWithStatement(node);
  11840. case 5:
  11841. return this.parseBlock();
  11842. case 13:
  11843. return this.parseEmptyStatement(node);
  11844. case 77:
  11845. {
  11846. const nextTokenCharCode = this.lookaheadCharCode();
  11847. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  11848. break;
  11849. }
  11850. }
  11851. case 76:
  11852. {
  11853. if (!this.options.allowImportExportEverywhere && !topLevel) {
  11854. this.raise(this.state.start, ErrorMessages.UnexpectedImportExport);
  11855. }
  11856. this.next();
  11857. let result;
  11858. if (starttype === 77) {
  11859. result = this.parseImport(node);
  11860. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  11861. this.sawUnambiguousESM = true;
  11862. }
  11863. } else {
  11864. result = this.parseExport(node);
  11865. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  11866. this.sawUnambiguousESM = true;
  11867. }
  11868. }
  11869. this.assertModuleNodeAllowed(node);
  11870. return result;
  11871. }
  11872. default:
  11873. {
  11874. if (this.isAsyncFunction()) {
  11875. if (context) {
  11876. this.raise(this.state.start, ErrorMessages.AsyncFunctionInSingleStatementContext);
  11877. }
  11878. this.next();
  11879. return this.parseFunctionStatement(node, true, !context);
  11880. }
  11881. }
  11882. }
  11883. const maybeName = this.state.value;
  11884. const expr = this.parseExpression();
  11885. if (tokenIsIdentifier(starttype) && expr.type === "Identifier" && this.eat(14)) {
  11886. return this.parseLabeledStatement(node, maybeName, expr, context);
  11887. } else {
  11888. return this.parseExpressionStatement(node, expr);
  11889. }
  11890. }
  11891. assertModuleNodeAllowed(node) {
  11892. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  11893. this.raise(node.start, SourceTypeModuleErrorMessages.ImportOutsideModule);
  11894. }
  11895. }
  11896. takeDecorators(node) {
  11897. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  11898. if (decorators.length) {
  11899. node.decorators = decorators;
  11900. this.resetStartLocationFromNode(node, decorators[0]);
  11901. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  11902. }
  11903. }
  11904. canHaveLeadingDecorator() {
  11905. return this.match(74);
  11906. }
  11907. parseDecorators(allowExport) {
  11908. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  11909. while (this.match(24)) {
  11910. const decorator = this.parseDecorator();
  11911. currentContextDecorators.push(decorator);
  11912. }
  11913. if (this.match(76)) {
  11914. if (!allowExport) {
  11915. this.unexpected();
  11916. }
  11917. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  11918. this.raise(this.state.start, ErrorMessages.DecoratorExportClass);
  11919. }
  11920. } else if (!this.canHaveLeadingDecorator()) {
  11921. throw this.raise(this.state.start, ErrorMessages.UnexpectedLeadingDecorator);
  11922. }
  11923. }
  11924. parseDecorator() {
  11925. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  11926. const node = this.startNode();
  11927. this.next();
  11928. if (this.hasPlugin("decorators")) {
  11929. this.state.decoratorStack.push([]);
  11930. const startPos = this.state.start;
  11931. const startLoc = this.state.startLoc;
  11932. let expr;
  11933. if (this.eat(10)) {
  11934. expr = this.parseExpression();
  11935. this.expect(11);
  11936. } else {
  11937. expr = this.parseIdentifier(false);
  11938. while (this.eat(16)) {
  11939. const node = this.startNodeAt(startPos, startLoc);
  11940. node.object = expr;
  11941. node.property = this.parseIdentifier(true);
  11942. node.computed = false;
  11943. expr = this.finishNode(node, "MemberExpression");
  11944. }
  11945. }
  11946. node.expression = this.parseMaybeDecoratorArguments(expr);
  11947. this.state.decoratorStack.pop();
  11948. } else {
  11949. node.expression = this.parseExprSubscripts();
  11950. }
  11951. return this.finishNode(node, "Decorator");
  11952. }
  11953. parseMaybeDecoratorArguments(expr) {
  11954. if (this.eat(10)) {
  11955. const node = this.startNodeAtNode(expr);
  11956. node.callee = expr;
  11957. node.arguments = this.parseCallExpressionArguments(11, false);
  11958. this.toReferencedList(node.arguments);
  11959. return this.finishNode(node, "CallExpression");
  11960. }
  11961. return expr;
  11962. }
  11963. parseBreakContinueStatement(node, isBreak) {
  11964. this.next();
  11965. if (this.isLineTerminator()) {
  11966. node.label = null;
  11967. } else {
  11968. node.label = this.parseIdentifier();
  11969. this.semicolon();
  11970. }
  11971. this.verifyBreakContinue(node, isBreak);
  11972. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  11973. }
  11974. verifyBreakContinue(node, isBreak) {
  11975. let i;
  11976. for (i = 0; i < this.state.labels.length; ++i) {
  11977. const lab = this.state.labels[i];
  11978. if (node.label == null || lab.name === node.label.name) {
  11979. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  11980. if (node.label && isBreak) break;
  11981. }
  11982. }
  11983. if (i === this.state.labels.length) {
  11984. this.raise(node.start, ErrorMessages.IllegalBreakContinue, isBreak ? "break" : "continue");
  11985. }
  11986. }
  11987. parseDebuggerStatement(node) {
  11988. this.next();
  11989. this.semicolon();
  11990. return this.finishNode(node, "DebuggerStatement");
  11991. }
  11992. parseHeaderExpression() {
  11993. this.expect(10);
  11994. const val = this.parseExpression();
  11995. this.expect(11);
  11996. return val;
  11997. }
  11998. parseDoStatement(node) {
  11999. this.next();
  12000. this.state.labels.push(loopLabel);
  12001. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("do"));
  12002. this.state.labels.pop();
  12003. this.expect(86);
  12004. node.test = this.parseHeaderExpression();
  12005. this.eat(13);
  12006. return this.finishNode(node, "DoWhileStatement");
  12007. }
  12008. parseForStatement(node) {
  12009. this.next();
  12010. this.state.labels.push(loopLabel);
  12011. let awaitAt = -1;
  12012. if (this.isAwaitAllowed() && this.eatContextual(90)) {
  12013. awaitAt = this.state.lastTokStart;
  12014. }
  12015. this.scope.enter(SCOPE_OTHER);
  12016. this.expect(10);
  12017. if (this.match(13)) {
  12018. if (awaitAt > -1) {
  12019. this.unexpected(awaitAt);
  12020. }
  12021. return this.parseFor(node, null);
  12022. }
  12023. const startsWithLet = this.isContextual(93);
  12024. const isLet = startsWithLet && this.isLetKeyword();
  12025. if (this.match(68) || this.match(69) || isLet) {
  12026. const init = this.startNode();
  12027. const kind = isLet ? "let" : this.state.value;
  12028. this.next();
  12029. this.parseVar(init, true, kind);
  12030. this.finishNode(init, "VariableDeclaration");
  12031. if ((this.match(52) || this.isContextual(95)) && init.declarations.length === 1) {
  12032. return this.parseForIn(node, init, awaitAt);
  12033. }
  12034. if (awaitAt > -1) {
  12035. this.unexpected(awaitAt);
  12036. }
  12037. return this.parseFor(node, init);
  12038. }
  12039. const startsWithAsync = this.isContextual(89);
  12040. const refExpressionErrors = new ExpressionErrors();
  12041. const init = this.parseExpression(true, refExpressionErrors);
  12042. const isForOf = this.isContextual(95);
  12043. if (isForOf) {
  12044. if (startsWithLet) {
  12045. this.raise(init.start, ErrorMessages.ForOfLet);
  12046. } else if (awaitAt === -1 && startsWithAsync && init.type === "Identifier") {
  12047. this.raise(init.start, ErrorMessages.ForOfAsync);
  12048. }
  12049. }
  12050. if (isForOf || this.match(52)) {
  12051. this.toAssignable(init, true);
  12052. const description = isForOf ? "for-of statement" : "for-in statement";
  12053. this.checkLVal(init, description);
  12054. return this.parseForIn(node, init, awaitAt);
  12055. } else {
  12056. this.checkExpressionErrors(refExpressionErrors, true);
  12057. }
  12058. if (awaitAt > -1) {
  12059. this.unexpected(awaitAt);
  12060. }
  12061. return this.parseFor(node, init);
  12062. }
  12063. parseFunctionStatement(node, isAsync, declarationPosition) {
  12064. this.next();
  12065. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  12066. }
  12067. parseIfStatement(node) {
  12068. this.next();
  12069. node.test = this.parseHeaderExpression();
  12070. node.consequent = this.parseStatement("if");
  12071. node.alternate = this.eat(60) ? this.parseStatement("if") : null;
  12072. return this.finishNode(node, "IfStatement");
  12073. }
  12074. parseReturnStatement(node) {
  12075. if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
  12076. this.raise(this.state.start, ErrorMessages.IllegalReturn);
  12077. }
  12078. this.next();
  12079. if (this.isLineTerminator()) {
  12080. node.argument = null;
  12081. } else {
  12082. node.argument = this.parseExpression();
  12083. this.semicolon();
  12084. }
  12085. return this.finishNode(node, "ReturnStatement");
  12086. }
  12087. parseSwitchStatement(node) {
  12088. this.next();
  12089. node.discriminant = this.parseHeaderExpression();
  12090. const cases = node.cases = [];
  12091. this.expect(5);
  12092. this.state.labels.push(switchLabel);
  12093. this.scope.enter(SCOPE_OTHER);
  12094. let cur;
  12095. for (let sawDefault; !this.match(8);) {
  12096. if (this.match(55) || this.match(59)) {
  12097. const isCase = this.match(55);
  12098. if (cur) this.finishNode(cur, "SwitchCase");
  12099. cases.push(cur = this.startNode());
  12100. cur.consequent = [];
  12101. this.next();
  12102. if (isCase) {
  12103. cur.test = this.parseExpression();
  12104. } else {
  12105. if (sawDefault) {
  12106. this.raise(this.state.lastTokStart, ErrorMessages.MultipleDefaultsInSwitch);
  12107. }
  12108. sawDefault = true;
  12109. cur.test = null;
  12110. }
  12111. this.expect(14);
  12112. } else {
  12113. if (cur) {
  12114. cur.consequent.push(this.parseStatement(null));
  12115. } else {
  12116. this.unexpected();
  12117. }
  12118. }
  12119. }
  12120. this.scope.exit();
  12121. if (cur) this.finishNode(cur, "SwitchCase");
  12122. this.next();
  12123. this.state.labels.pop();
  12124. return this.finishNode(node, "SwitchStatement");
  12125. }
  12126. parseThrowStatement(node) {
  12127. this.next();
  12128. if (this.hasPrecedingLineBreak()) {
  12129. this.raise(this.state.lastTokEnd, ErrorMessages.NewlineAfterThrow);
  12130. }
  12131. node.argument = this.parseExpression();
  12132. this.semicolon();
  12133. return this.finishNode(node, "ThrowStatement");
  12134. }
  12135. parseCatchClauseParam() {
  12136. const param = this.parseBindingAtom();
  12137. const simple = param.type === "Identifier";
  12138. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  12139. this.checkLVal(param, "catch clause", BIND_LEXICAL);
  12140. return param;
  12141. }
  12142. parseTryStatement(node) {
  12143. this.next();
  12144. node.block = this.parseBlock();
  12145. node.handler = null;
  12146. if (this.match(56)) {
  12147. const clause = this.startNode();
  12148. this.next();
  12149. if (this.match(10)) {
  12150. this.expect(10);
  12151. clause.param = this.parseCatchClauseParam();
  12152. this.expect(11);
  12153. } else {
  12154. clause.param = null;
  12155. this.scope.enter(SCOPE_OTHER);
  12156. }
  12157. clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false));
  12158. this.scope.exit();
  12159. node.handler = this.finishNode(clause, "CatchClause");
  12160. }
  12161. node.finalizer = this.eat(61) ? this.parseBlock() : null;
  12162. if (!node.handler && !node.finalizer) {
  12163. this.raise(node.start, ErrorMessages.NoCatchOrFinally);
  12164. }
  12165. return this.finishNode(node, "TryStatement");
  12166. }
  12167. parseVarStatement(node, kind) {
  12168. this.next();
  12169. this.parseVar(node, false, kind);
  12170. this.semicolon();
  12171. return this.finishNode(node, "VariableDeclaration");
  12172. }
  12173. parseWhileStatement(node) {
  12174. this.next();
  12175. node.test = this.parseHeaderExpression();
  12176. this.state.labels.push(loopLabel);
  12177. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("while"));
  12178. this.state.labels.pop();
  12179. return this.finishNode(node, "WhileStatement");
  12180. }
  12181. parseWithStatement(node) {
  12182. if (this.state.strict) {
  12183. this.raise(this.state.start, ErrorMessages.StrictWith);
  12184. }
  12185. this.next();
  12186. node.object = this.parseHeaderExpression();
  12187. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("with"));
  12188. return this.finishNode(node, "WithStatement");
  12189. }
  12190. parseEmptyStatement(node) {
  12191. this.next();
  12192. return this.finishNode(node, "EmptyStatement");
  12193. }
  12194. parseLabeledStatement(node, maybeName, expr, context) {
  12195. for (const label of this.state.labels) {
  12196. if (label.name === maybeName) {
  12197. this.raise(expr.start, ErrorMessages.LabelRedeclaration, maybeName);
  12198. }
  12199. }
  12200. const kind = tokenIsLoop(this.state.type) ? "loop" : this.match(65) ? "switch" : null;
  12201. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  12202. const label = this.state.labels[i];
  12203. if (label.statementStart === node.start) {
  12204. label.statementStart = this.state.start;
  12205. label.kind = kind;
  12206. } else {
  12207. break;
  12208. }
  12209. }
  12210. this.state.labels.push({
  12211. name: maybeName,
  12212. kind: kind,
  12213. statementStart: this.state.start
  12214. });
  12215. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  12216. this.state.labels.pop();
  12217. node.label = expr;
  12218. return this.finishNode(node, "LabeledStatement");
  12219. }
  12220. parseExpressionStatement(node, expr) {
  12221. node.expression = expr;
  12222. this.semicolon();
  12223. return this.finishNode(node, "ExpressionStatement");
  12224. }
  12225. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  12226. const node = this.startNode();
  12227. if (allowDirectives) {
  12228. this.state.strictErrors.clear();
  12229. }
  12230. this.expect(5);
  12231. if (createNewLexicalScope) {
  12232. this.scope.enter(SCOPE_OTHER);
  12233. }
  12234. this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse);
  12235. if (createNewLexicalScope) {
  12236. this.scope.exit();
  12237. }
  12238. return this.finishNode(node, "BlockStatement");
  12239. }
  12240. isValidDirective(stmt) {
  12241. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  12242. }
  12243. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  12244. const body = node.body = [];
  12245. const directives = node.directives = [];
  12246. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  12247. }
  12248. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  12249. const oldStrict = this.state.strict;
  12250. let hasStrictModeDirective = false;
  12251. let parsedNonDirective = false;
  12252. while (!this.match(end)) {
  12253. const stmt = this.parseStatement(null, topLevel);
  12254. if (directives && !parsedNonDirective) {
  12255. if (this.isValidDirective(stmt)) {
  12256. const directive = this.stmtToDirective(stmt);
  12257. directives.push(directive);
  12258. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  12259. hasStrictModeDirective = true;
  12260. this.setStrict(true);
  12261. }
  12262. continue;
  12263. }
  12264. parsedNonDirective = true;
  12265. this.state.strictErrors.clear();
  12266. }
  12267. body.push(stmt);
  12268. }
  12269. if (afterBlockParse) {
  12270. afterBlockParse.call(this, hasStrictModeDirective);
  12271. }
  12272. if (!oldStrict) {
  12273. this.setStrict(false);
  12274. }
  12275. this.next();
  12276. }
  12277. parseFor(node, init) {
  12278. node.init = init;
  12279. this.semicolon(false);
  12280. node.test = this.match(13) ? null : this.parseExpression();
  12281. this.semicolon(false);
  12282. node.update = this.match(11) ? null : this.parseExpression();
  12283. this.expect(11);
  12284. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("for"));
  12285. this.scope.exit();
  12286. this.state.labels.pop();
  12287. return this.finishNode(node, "ForStatement");
  12288. }
  12289. parseForIn(node, init, awaitAt) {
  12290. const isForIn = this.match(52);
  12291. this.next();
  12292. if (isForIn) {
  12293. if (awaitAt > -1) this.unexpected(awaitAt);
  12294. } else {
  12295. node.await = awaitAt > -1;
  12296. }
  12297. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  12298. this.raise(init.start, ErrorMessages.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of");
  12299. } else if (init.type === "AssignmentPattern") {
  12300. this.raise(init.start, ErrorMessages.InvalidLhs, "for-loop");
  12301. }
  12302. node.left = init;
  12303. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  12304. this.expect(11);
  12305. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("for"));
  12306. this.scope.exit();
  12307. this.state.labels.pop();
  12308. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  12309. }
  12310. parseVar(node, isFor, kind) {
  12311. const declarations = node.declarations = [];
  12312. const isTypescript = this.hasPlugin("typescript");
  12313. node.kind = kind;
  12314. for (;;) {
  12315. const decl = this.startNode();
  12316. this.parseVarId(decl, kind);
  12317. if (this.eat(27)) {
  12318. decl.init = isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  12319. } else {
  12320. if (kind === "const" && !(this.match(52) || this.isContextual(95))) {
  12321. if (!isTypescript) {
  12322. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Const declarations");
  12323. }
  12324. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(52) || this.isContextual(95)))) {
  12325. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Complex binding patterns");
  12326. }
  12327. decl.init = null;
  12328. }
  12329. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  12330. if (!this.eat(12)) break;
  12331. }
  12332. return node;
  12333. }
  12334. parseVarId(decl, kind) {
  12335. decl.id = this.parseBindingAtom();
  12336. this.checkLVal(decl.id, "variable declaration", kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, kind !== "var");
  12337. }
  12338. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  12339. const isStatement = statement & FUNC_STATEMENT;
  12340. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  12341. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  12342. this.initFunction(node, isAsync);
  12343. if (this.match(49) && isHangingStatement) {
  12344. this.raise(this.state.start, ErrorMessages.GeneratorInSingleStatementContext);
  12345. }
  12346. node.generator = this.eat(49);
  12347. if (isStatement) {
  12348. node.id = this.parseFunctionId(requireId);
  12349. }
  12350. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  12351. this.state.maybeInArrowParameters = false;
  12352. this.scope.enter(SCOPE_FUNCTION);
  12353. this.prodParam.enter(functionFlags(isAsync, node.generator));
  12354. if (!isStatement) {
  12355. node.id = this.parseFunctionId();
  12356. }
  12357. this.parseFunctionParams(node, false);
  12358. this.withSmartMixTopicForbiddingContext(() => {
  12359. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  12360. });
  12361. this.prodParam.exit();
  12362. this.scope.exit();
  12363. if (isStatement && !isHangingStatement) {
  12364. this.registerFunctionStatementId(node);
  12365. }
  12366. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  12367. return node;
  12368. }
  12369. parseFunctionId(requireId) {
  12370. return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null;
  12371. }
  12372. parseFunctionParams(node, allowModifiers) {
  12373. this.expect(10);
  12374. this.expressionScope.enter(newParameterDeclarationScope());
  12375. node.params = this.parseBindingList(11, 41, false, allowModifiers);
  12376. this.expressionScope.exit();
  12377. }
  12378. registerFunctionStatementId(node) {
  12379. if (!node.id) return;
  12380. this.scope.declareName(node.id.name, this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, node.id.start);
  12381. }
  12382. parseClass(node, isStatement, optionalId) {
  12383. this.next();
  12384. this.takeDecorators(node);
  12385. const oldStrict = this.state.strict;
  12386. this.state.strict = true;
  12387. this.parseClassId(node, isStatement, optionalId);
  12388. this.parseClassSuper(node);
  12389. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  12390. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  12391. }
  12392. isClassProperty() {
  12393. return this.match(27) || this.match(13) || this.match(8);
  12394. }
  12395. isClassMethod() {
  12396. return this.match(10);
  12397. }
  12398. isNonstaticConstructor(method) {
  12399. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  12400. }
  12401. parseClassBody(hadSuperClass, oldStrict) {
  12402. this.classScope.enter();
  12403. const state = {
  12404. hadConstructor: false,
  12405. hadSuperClass
  12406. };
  12407. let decorators = [];
  12408. const classBody = this.startNode();
  12409. classBody.body = [];
  12410. this.expect(5);
  12411. this.withSmartMixTopicForbiddingContext(() => {
  12412. while (!this.match(8)) {
  12413. if (this.eat(13)) {
  12414. if (decorators.length > 0) {
  12415. throw this.raise(this.state.lastTokEnd, ErrorMessages.DecoratorSemicolon);
  12416. }
  12417. continue;
  12418. }
  12419. if (this.match(24)) {
  12420. decorators.push(this.parseDecorator());
  12421. continue;
  12422. }
  12423. const member = this.startNode();
  12424. if (decorators.length) {
  12425. member.decorators = decorators;
  12426. this.resetStartLocationFromNode(member, decorators[0]);
  12427. decorators = [];
  12428. }
  12429. this.parseClassMember(classBody, member, state);
  12430. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  12431. this.raise(member.start, ErrorMessages.DecoratorConstructor);
  12432. }
  12433. }
  12434. });
  12435. this.state.strict = oldStrict;
  12436. this.next();
  12437. if (decorators.length) {
  12438. throw this.raise(this.state.start, ErrorMessages.TrailingDecorator);
  12439. }
  12440. this.classScope.exit();
  12441. return this.finishNode(classBody, "ClassBody");
  12442. }
  12443. parseClassMemberFromModifier(classBody, member) {
  12444. const key = this.parseIdentifier(true);
  12445. if (this.isClassMethod()) {
  12446. const method = member;
  12447. method.kind = "method";
  12448. method.computed = false;
  12449. method.key = key;
  12450. method.static = false;
  12451. this.pushClassMethod(classBody, method, false, false, false, false);
  12452. return true;
  12453. } else if (this.isClassProperty()) {
  12454. const prop = member;
  12455. prop.computed = false;
  12456. prop.key = key;
  12457. prop.static = false;
  12458. classBody.body.push(this.parseClassProperty(prop));
  12459. return true;
  12460. }
  12461. this.resetPreviousNodeTrailingComments(key);
  12462. return false;
  12463. }
  12464. parseClassMember(classBody, member, state) {
  12465. const isStatic = this.isContextual(98);
  12466. if (isStatic) {
  12467. if (this.parseClassMemberFromModifier(classBody, member)) {
  12468. return;
  12469. }
  12470. if (this.eat(5)) {
  12471. this.parseClassStaticBlock(classBody, member);
  12472. return;
  12473. }
  12474. }
  12475. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  12476. }
  12477. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  12478. const publicMethod = member;
  12479. const privateMethod = member;
  12480. const publicProp = member;
  12481. const privateProp = member;
  12482. const method = publicMethod;
  12483. const publicMember = publicMethod;
  12484. member.static = isStatic;
  12485. this.parsePropertyNamePrefixOperator(member);
  12486. if (this.eat(49)) {
  12487. method.kind = "method";
  12488. const isPrivateName = this.match(128);
  12489. this.parseClassElementName(method);
  12490. if (isPrivateName) {
  12491. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  12492. return;
  12493. }
  12494. if (this.isNonstaticConstructor(publicMethod)) {
  12495. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsGenerator);
  12496. }
  12497. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  12498. return;
  12499. }
  12500. const isContextual = tokenIsIdentifier(this.state.type) && !this.state.containsEsc;
  12501. const isPrivate = this.match(128);
  12502. const key = this.parseClassElementName(member);
  12503. const maybeQuestionTokenStart = this.state.start;
  12504. this.parsePostMemberNameModifiers(publicMember);
  12505. if (this.isClassMethod()) {
  12506. method.kind = "method";
  12507. if (isPrivate) {
  12508. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  12509. return;
  12510. }
  12511. const isConstructor = this.isNonstaticConstructor(publicMethod);
  12512. let allowsDirectSuper = false;
  12513. if (isConstructor) {
  12514. publicMethod.kind = "constructor";
  12515. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  12516. this.raise(key.start, ErrorMessages.DuplicateConstructor);
  12517. }
  12518. if (isConstructor && this.hasPlugin("typescript") && member.override) {
  12519. this.raise(key.start, ErrorMessages.OverrideOnConstructor);
  12520. }
  12521. state.hadConstructor = true;
  12522. allowsDirectSuper = state.hadSuperClass;
  12523. }
  12524. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  12525. } else if (this.isClassProperty()) {
  12526. if (isPrivate) {
  12527. this.pushClassPrivateProperty(classBody, privateProp);
  12528. } else {
  12529. this.pushClassProperty(classBody, publicProp);
  12530. }
  12531. } else if (isContextual && key.name === "async" && !this.isLineTerminator()) {
  12532. this.resetPreviousNodeTrailingComments(key);
  12533. const isGenerator = this.eat(49);
  12534. if (publicMember.optional) {
  12535. this.unexpected(maybeQuestionTokenStart);
  12536. }
  12537. method.kind = "method";
  12538. const isPrivate = this.match(128);
  12539. this.parseClassElementName(method);
  12540. this.parsePostMemberNameModifiers(publicMember);
  12541. if (isPrivate) {
  12542. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  12543. } else {
  12544. if (this.isNonstaticConstructor(publicMethod)) {
  12545. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAsync);
  12546. }
  12547. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  12548. }
  12549. } else if (isContextual && (key.name === "get" || key.name === "set") && !(this.match(49) && this.isLineTerminator())) {
  12550. this.resetPreviousNodeTrailingComments(key);
  12551. method.kind = key.name;
  12552. const isPrivate = this.match(128);
  12553. this.parseClassElementName(publicMethod);
  12554. if (isPrivate) {
  12555. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  12556. } else {
  12557. if (this.isNonstaticConstructor(publicMethod)) {
  12558. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAccessor);
  12559. }
  12560. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  12561. }
  12562. this.checkGetterSetterParams(publicMethod);
  12563. } else if (this.isLineTerminator()) {
  12564. if (isPrivate) {
  12565. this.pushClassPrivateProperty(classBody, privateProp);
  12566. } else {
  12567. this.pushClassProperty(classBody, publicProp);
  12568. }
  12569. } else {
  12570. this.unexpected();
  12571. }
  12572. }
  12573. parseClassElementName(member) {
  12574. const {
  12575. type,
  12576. value,
  12577. start
  12578. } = this.state;
  12579. if ((type === 122 || type === 123) && member.static && value === "prototype") {
  12580. this.raise(start, ErrorMessages.StaticPrototype);
  12581. }
  12582. if (type === 128) {
  12583. if (value === "constructor") {
  12584. this.raise(start, ErrorMessages.ConstructorClassPrivateField);
  12585. }
  12586. const key = this.parsePrivateName();
  12587. member.key = key;
  12588. return key;
  12589. }
  12590. return this.parsePropertyName(member);
  12591. }
  12592. parseClassStaticBlock(classBody, member) {
  12593. var _member$decorators;
  12594. this.scope.enter(SCOPE_CLASS | SCOPE_STATIC_BLOCK | SCOPE_SUPER);
  12595. const oldLabels = this.state.labels;
  12596. this.state.labels = [];
  12597. this.prodParam.enter(PARAM);
  12598. const body = member.body = [];
  12599. this.parseBlockOrModuleBlockBody(body, undefined, false, 8);
  12600. this.prodParam.exit();
  12601. this.scope.exit();
  12602. this.state.labels = oldLabels;
  12603. classBody.body.push(this.finishNode(member, "StaticBlock"));
  12604. if ((_member$decorators = member.decorators) != null && _member$decorators.length) {
  12605. this.raise(member.start, ErrorMessages.DecoratorStaticBlock);
  12606. }
  12607. }
  12608. pushClassProperty(classBody, prop) {
  12609. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  12610. this.raise(prop.key.start, ErrorMessages.ConstructorClassField);
  12611. }
  12612. classBody.body.push(this.parseClassProperty(prop));
  12613. }
  12614. pushClassPrivateProperty(classBody, prop) {
  12615. const node = this.parseClassPrivateProperty(prop);
  12616. classBody.body.push(node);
  12617. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), CLASS_ELEMENT_OTHER, node.key.start);
  12618. }
  12619. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  12620. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  12621. }
  12622. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  12623. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  12624. classBody.body.push(node);
  12625. const kind = node.kind === "get" ? node.static ? CLASS_ELEMENT_STATIC_GETTER : CLASS_ELEMENT_INSTANCE_GETTER : node.kind === "set" ? node.static ? CLASS_ELEMENT_STATIC_SETTER : CLASS_ELEMENT_INSTANCE_SETTER : CLASS_ELEMENT_OTHER;
  12626. this.declareClassPrivateMethodInScope(node, kind);
  12627. }
  12628. declareClassPrivateMethodInScope(node, kind) {
  12629. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.start);
  12630. }
  12631. parsePostMemberNameModifiers(methodOrProp) {}
  12632. parseClassPrivateProperty(node) {
  12633. this.parseInitializer(node);
  12634. this.semicolon();
  12635. return this.finishNode(node, "ClassPrivateProperty");
  12636. }
  12637. parseClassProperty(node) {
  12638. this.parseInitializer(node);
  12639. this.semicolon();
  12640. return this.finishNode(node, "ClassProperty");
  12641. }
  12642. parseInitializer(node) {
  12643. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  12644. this.expressionScope.enter(newExpressionScope());
  12645. this.prodParam.enter(PARAM);
  12646. node.value = this.eat(27) ? this.parseMaybeAssignAllowIn() : null;
  12647. this.expressionScope.exit();
  12648. this.prodParam.exit();
  12649. this.scope.exit();
  12650. }
  12651. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  12652. if (tokenIsIdentifier(this.state.type)) {
  12653. node.id = this.parseIdentifier();
  12654. if (isStatement) {
  12655. this.checkLVal(node.id, "class name", bindingType);
  12656. }
  12657. } else {
  12658. if (optionalId || !isStatement) {
  12659. node.id = null;
  12660. } else {
  12661. this.unexpected(null, ErrorMessages.MissingClassName);
  12662. }
  12663. }
  12664. }
  12665. parseClassSuper(node) {
  12666. node.superClass = this.eat(75) ? this.parseExprSubscripts() : null;
  12667. }
  12668. parseExport(node) {
  12669. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  12670. const parseAfterDefault = !hasDefault || this.eat(12);
  12671. const hasStar = parseAfterDefault && this.eatExportStar(node);
  12672. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  12673. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12));
  12674. const isFromRequired = hasDefault || hasStar;
  12675. if (hasStar && !hasNamespace) {
  12676. if (hasDefault) this.unexpected();
  12677. this.parseExportFrom(node, true);
  12678. return this.finishNode(node, "ExportAllDeclaration");
  12679. }
  12680. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  12681. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  12682. throw this.unexpected(null, 5);
  12683. }
  12684. let hasDeclaration;
  12685. if (isFromRequired || hasSpecifiers) {
  12686. hasDeclaration = false;
  12687. this.parseExportFrom(node, isFromRequired);
  12688. } else {
  12689. hasDeclaration = this.maybeParseExportDeclaration(node);
  12690. }
  12691. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  12692. this.checkExport(node, true, false, !!node.source);
  12693. return this.finishNode(node, "ExportNamedDeclaration");
  12694. }
  12695. if (this.eat(59)) {
  12696. node.declaration = this.parseExportDefaultExpression();
  12697. this.checkExport(node, true, true);
  12698. return this.finishNode(node, "ExportDefaultDeclaration");
  12699. }
  12700. throw this.unexpected(null, 5);
  12701. }
  12702. eatExportStar(node) {
  12703. return this.eat(49);
  12704. }
  12705. maybeParseExportDefaultSpecifier(node) {
  12706. if (this.isExportDefaultSpecifier()) {
  12707. this.expectPlugin("exportDefaultFrom");
  12708. const specifier = this.startNode();
  12709. specifier.exported = this.parseIdentifier(true);
  12710. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  12711. return true;
  12712. }
  12713. return false;
  12714. }
  12715. maybeParseExportNamespaceSpecifier(node) {
  12716. if (this.isContextual(87)) {
  12717. if (!node.specifiers) node.specifiers = [];
  12718. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  12719. this.next();
  12720. specifier.exported = this.parseModuleExportName();
  12721. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  12722. return true;
  12723. }
  12724. return false;
  12725. }
  12726. maybeParseExportNamedSpecifiers(node) {
  12727. if (this.match(5)) {
  12728. if (!node.specifiers) node.specifiers = [];
  12729. const isTypeExport = node.exportKind === "type";
  12730. node.specifiers.push(...this.parseExportSpecifiers(isTypeExport));
  12731. node.source = null;
  12732. node.declaration = null;
  12733. if (this.hasPlugin("importAssertions")) {
  12734. node.assertions = [];
  12735. }
  12736. return true;
  12737. }
  12738. return false;
  12739. }
  12740. maybeParseExportDeclaration(node) {
  12741. if (this.shouldParseExportDeclaration()) {
  12742. node.specifiers = [];
  12743. node.source = null;
  12744. if (this.hasPlugin("importAssertions")) {
  12745. node.assertions = [];
  12746. }
  12747. node.declaration = this.parseExportDeclaration(node);
  12748. return true;
  12749. }
  12750. return false;
  12751. }
  12752. isAsyncFunction() {
  12753. if (!this.isContextual(89)) return false;
  12754. const next = this.nextTokenStart();
  12755. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  12756. }
  12757. parseExportDefaultExpression() {
  12758. const expr = this.startNode();
  12759. const isAsync = this.isAsyncFunction();
  12760. if (this.match(62) || isAsync) {
  12761. this.next();
  12762. if (isAsync) {
  12763. this.next();
  12764. }
  12765. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  12766. } else if (this.match(74)) {
  12767. return this.parseClass(expr, true, true);
  12768. } else if (this.match(24)) {
  12769. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  12770. this.raise(this.state.start, ErrorMessages.DecoratorBeforeExport);
  12771. }
  12772. this.parseDecorators(false);
  12773. return this.parseClass(expr, true, true);
  12774. } else if (this.match(69) || this.match(68) || this.isLet()) {
  12775. throw this.raise(this.state.start, ErrorMessages.UnsupportedDefaultExport);
  12776. } else {
  12777. const res = this.parseMaybeAssignAllowIn();
  12778. this.semicolon();
  12779. return res;
  12780. }
  12781. }
  12782. parseExportDeclaration(node) {
  12783. return this.parseStatement(null);
  12784. }
  12785. isExportDefaultSpecifier() {
  12786. const {
  12787. type
  12788. } = this.state;
  12789. if (tokenIsIdentifier(type)) {
  12790. if (type === 89 && !this.state.containsEsc || type === 93) {
  12791. return false;
  12792. }
  12793. if ((type === 120 || type === 119) && !this.state.containsEsc) {
  12794. const {
  12795. type: nextType
  12796. } = this.lookahead();
  12797. if (tokenIsIdentifier(nextType) && nextType !== 91 || nextType === 5) {
  12798. this.expectOnePlugin(["flow", "typescript"]);
  12799. return false;
  12800. }
  12801. }
  12802. } else if (!this.match(59)) {
  12803. return false;
  12804. }
  12805. const next = this.nextTokenStart();
  12806. const hasFrom = this.isUnparsedContextual(next, "from");
  12807. if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) {
  12808. return true;
  12809. }
  12810. if (this.match(59) && hasFrom) {
  12811. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  12812. return nextAfterFrom === 34 || nextAfterFrom === 39;
  12813. }
  12814. return false;
  12815. }
  12816. parseExportFrom(node, expect) {
  12817. if (this.eatContextual(91)) {
  12818. node.source = this.parseImportSource();
  12819. this.checkExport(node);
  12820. const assertions = this.maybeParseImportAssertions();
  12821. if (assertions) {
  12822. node.assertions = assertions;
  12823. }
  12824. } else if (expect) {
  12825. this.unexpected();
  12826. }
  12827. this.semicolon();
  12828. }
  12829. shouldParseExportDeclaration() {
  12830. const {
  12831. type
  12832. } = this.state;
  12833. if (type === 24) {
  12834. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  12835. if (this.hasPlugin("decorators")) {
  12836. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  12837. this.unexpected(this.state.start, ErrorMessages.DecoratorBeforeExport);
  12838. } else {
  12839. return true;
  12840. }
  12841. }
  12842. }
  12843. return type === 68 || type === 69 || type === 62 || type === 74 || this.isLet() || this.isAsyncFunction();
  12844. }
  12845. checkExport(node, checkNames, isDefault, isFrom) {
  12846. if (checkNames) {
  12847. if (isDefault) {
  12848. this.checkDuplicateExports(node, "default");
  12849. if (this.hasPlugin("exportDefaultFrom")) {
  12850. var _declaration$extra;
  12851. const declaration = node.declaration;
  12852. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) {
  12853. this.raise(declaration.start, ErrorMessages.ExportDefaultFromAsIdentifier);
  12854. }
  12855. }
  12856. } else if (node.specifiers && node.specifiers.length) {
  12857. for (const specifier of node.specifiers) {
  12858. const {
  12859. exported
  12860. } = specifier;
  12861. const exportedName = exported.type === "Identifier" ? exported.name : exported.value;
  12862. this.checkDuplicateExports(specifier, exportedName);
  12863. if (!isFrom && specifier.local) {
  12864. const {
  12865. local
  12866. } = specifier;
  12867. if (local.type !== "Identifier") {
  12868. this.raise(specifier.start, ErrorMessages.ExportBindingIsString, local.value, exportedName);
  12869. } else {
  12870. this.checkReservedWord(local.name, local.start, true, false);
  12871. this.scope.checkLocalExport(local);
  12872. }
  12873. }
  12874. }
  12875. } else if (node.declaration) {
  12876. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  12877. const id = node.declaration.id;
  12878. if (!id) throw new Error("Assertion failure");
  12879. this.checkDuplicateExports(node, id.name);
  12880. } else if (node.declaration.type === "VariableDeclaration") {
  12881. for (const declaration of node.declaration.declarations) {
  12882. this.checkDeclaration(declaration.id);
  12883. }
  12884. }
  12885. }
  12886. }
  12887. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  12888. if (currentContextDecorators.length) {
  12889. throw this.raise(node.start, ErrorMessages.UnsupportedDecoratorExport);
  12890. }
  12891. }
  12892. checkDeclaration(node) {
  12893. if (node.type === "Identifier") {
  12894. this.checkDuplicateExports(node, node.name);
  12895. } else if (node.type === "ObjectPattern") {
  12896. for (const prop of node.properties) {
  12897. this.checkDeclaration(prop);
  12898. }
  12899. } else if (node.type === "ArrayPattern") {
  12900. for (const elem of node.elements) {
  12901. if (elem) {
  12902. this.checkDeclaration(elem);
  12903. }
  12904. }
  12905. } else if (node.type === "ObjectProperty") {
  12906. this.checkDeclaration(node.value);
  12907. } else if (node.type === "RestElement") {
  12908. this.checkDeclaration(node.argument);
  12909. } else if (node.type === "AssignmentPattern") {
  12910. this.checkDeclaration(node.left);
  12911. }
  12912. }
  12913. checkDuplicateExports(node, name) {
  12914. if (this.exportedIdentifiers.has(name)) {
  12915. this.raise(node.start, name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, name);
  12916. }
  12917. this.exportedIdentifiers.add(name);
  12918. }
  12919. parseExportSpecifiers(isInTypeExport) {
  12920. const nodes = [];
  12921. let first = true;
  12922. this.expect(5);
  12923. while (!this.eat(8)) {
  12924. if (first) {
  12925. first = false;
  12926. } else {
  12927. this.expect(12);
  12928. if (this.eat(8)) break;
  12929. }
  12930. const isMaybeTypeOnly = this.isContextual(120);
  12931. const isString = this.match(123);
  12932. const node = this.startNode();
  12933. node.local = this.parseModuleExportName();
  12934. nodes.push(this.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly));
  12935. }
  12936. return nodes;
  12937. }
  12938. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  12939. if (this.eatContextual(87)) {
  12940. node.exported = this.parseModuleExportName();
  12941. } else if (isString) {
  12942. node.exported = cloneStringLiteral(node.local);
  12943. } else if (!node.exported) {
  12944. node.exported = cloneIdentifier(node.local);
  12945. }
  12946. return this.finishNode(node, "ExportSpecifier");
  12947. }
  12948. parseModuleExportName() {
  12949. if (this.match(123)) {
  12950. const result = this.parseStringLiteral(this.state.value);
  12951. const surrogate = result.value.match(loneSurrogate);
  12952. if (surrogate) {
  12953. this.raise(result.start, ErrorMessages.ModuleExportNameHasLoneSurrogate, surrogate[0].charCodeAt(0).toString(16));
  12954. }
  12955. return result;
  12956. }
  12957. return this.parseIdentifier(true);
  12958. }
  12959. parseImport(node) {
  12960. node.specifiers = [];
  12961. if (!this.match(123)) {
  12962. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  12963. const parseNext = !hasDefault || this.eat(12);
  12964. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  12965. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  12966. this.expectContextual(91);
  12967. }
  12968. node.source = this.parseImportSource();
  12969. const assertions = this.maybeParseImportAssertions();
  12970. if (assertions) {
  12971. node.assertions = assertions;
  12972. } else {
  12973. const attributes = this.maybeParseModuleAttributes();
  12974. if (attributes) {
  12975. node.attributes = attributes;
  12976. }
  12977. }
  12978. this.semicolon();
  12979. return this.finishNode(node, "ImportDeclaration");
  12980. }
  12981. parseImportSource() {
  12982. if (!this.match(123)) this.unexpected();
  12983. return this.parseExprAtom();
  12984. }
  12985. shouldParseDefaultImport(node) {
  12986. return tokenIsIdentifier(this.state.type);
  12987. }
  12988. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  12989. specifier.local = this.parseIdentifier();
  12990. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  12991. node.specifiers.push(this.finishNode(specifier, type));
  12992. }
  12993. parseAssertEntries() {
  12994. const attrs = [];
  12995. const attrNames = new Set();
  12996. do {
  12997. if (this.match(8)) {
  12998. break;
  12999. }
  13000. const node = this.startNode();
  13001. const keyName = this.state.value;
  13002. if (attrNames.has(keyName)) {
  13003. this.raise(this.state.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, keyName);
  13004. }
  13005. attrNames.add(keyName);
  13006. if (this.match(123)) {
  13007. node.key = this.parseStringLiteral(keyName);
  13008. } else {
  13009. node.key = this.parseIdentifier(true);
  13010. }
  13011. this.expect(14);
  13012. if (!this.match(123)) {
  13013. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  13014. }
  13015. node.value = this.parseStringLiteral(this.state.value);
  13016. this.finishNode(node, "ImportAttribute");
  13017. attrs.push(node);
  13018. } while (this.eat(12));
  13019. return attrs;
  13020. }
  13021. maybeParseModuleAttributes() {
  13022. if (this.match(70) && !this.hasPrecedingLineBreak()) {
  13023. this.expectPlugin("moduleAttributes");
  13024. this.next();
  13025. } else {
  13026. if (this.hasPlugin("moduleAttributes")) return [];
  13027. return null;
  13028. }
  13029. const attrs = [];
  13030. const attributes = new Set();
  13031. do {
  13032. const node = this.startNode();
  13033. node.key = this.parseIdentifier(true);
  13034. if (node.key.name !== "type") {
  13035. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, node.key.name);
  13036. }
  13037. if (attributes.has(node.key.name)) {
  13038. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, node.key.name);
  13039. }
  13040. attributes.add(node.key.name);
  13041. this.expect(14);
  13042. if (!this.match(123)) {
  13043. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  13044. }
  13045. node.value = this.parseStringLiteral(this.state.value);
  13046. this.finishNode(node, "ImportAttribute");
  13047. attrs.push(node);
  13048. } while (this.eat(12));
  13049. return attrs;
  13050. }
  13051. maybeParseImportAssertions() {
  13052. if (this.isContextual(88) && !this.hasPrecedingLineBreak()) {
  13053. this.expectPlugin("importAssertions");
  13054. this.next();
  13055. } else {
  13056. if (this.hasPlugin("importAssertions")) return [];
  13057. return null;
  13058. }
  13059. this.eat(5);
  13060. const attrs = this.parseAssertEntries();
  13061. this.eat(8);
  13062. return attrs;
  13063. }
  13064. maybeParseDefaultImportSpecifier(node) {
  13065. if (this.shouldParseDefaultImport(node)) {
  13066. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  13067. return true;
  13068. }
  13069. return false;
  13070. }
  13071. maybeParseStarImportSpecifier(node) {
  13072. if (this.match(49)) {
  13073. const specifier = this.startNode();
  13074. this.next();
  13075. this.expectContextual(87);
  13076. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  13077. return true;
  13078. }
  13079. return false;
  13080. }
  13081. parseNamedImportSpecifiers(node) {
  13082. let first = true;
  13083. this.expect(5);
  13084. while (!this.eat(8)) {
  13085. if (first) {
  13086. first = false;
  13087. } else {
  13088. if (this.eat(14)) {
  13089. throw this.raise(this.state.start, ErrorMessages.DestructureNamedImport);
  13090. }
  13091. this.expect(12);
  13092. if (this.eat(8)) break;
  13093. }
  13094. const specifier = this.startNode();
  13095. const importedIsString = this.match(123);
  13096. const isMaybeTypeOnly = this.isContextual(120);
  13097. specifier.imported = this.parseModuleExportName();
  13098. const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly);
  13099. node.specifiers.push(importSpecifier);
  13100. }
  13101. }
  13102. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly) {
  13103. if (this.eatContextual(87)) {
  13104. specifier.local = this.parseIdentifier();
  13105. } else {
  13106. const {
  13107. imported
  13108. } = specifier;
  13109. if (importedIsString) {
  13110. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, imported.value);
  13111. }
  13112. this.checkReservedWord(imported.name, specifier.start, true, true);
  13113. if (!specifier.local) {
  13114. specifier.local = cloneIdentifier(imported);
  13115. }
  13116. }
  13117. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  13118. return this.finishNode(specifier, "ImportSpecifier");
  13119. }
  13120. isThisParam(param) {
  13121. return param.type === "Identifier" && param.name === "this";
  13122. }
  13123. }
  13124. let Parser$2 = class Parser extends StatementParser {
  13125. constructor(options, input) {
  13126. options = getOptions(options);
  13127. super(options, input);
  13128. this.options = options;
  13129. this.initializeScopes();
  13130. this.plugins = pluginsMap(this.options.plugins);
  13131. this.filename = options.sourceFilename;
  13132. }
  13133. getScopeHandler() {
  13134. return ScopeHandler;
  13135. }
  13136. parse() {
  13137. this.enterInitialScopes();
  13138. const file = this.startNode();
  13139. const program = this.startNode();
  13140. this.nextToken();
  13141. file.errors = null;
  13142. this.parseTopLevel(file, program);
  13143. file.errors = this.state.errors;
  13144. return file;
  13145. }
  13146. };
  13147. function pluginsMap(plugins) {
  13148. const pluginMap = new Map();
  13149. for (const plugin of plugins) {
  13150. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  13151. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  13152. }
  13153. return pluginMap;
  13154. }
  13155. function parse$9(input, options) {
  13156. var _options;
  13157. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  13158. options = Object.assign({}, options);
  13159. try {
  13160. options.sourceType = "module";
  13161. const parser = getParser(options, input);
  13162. const ast = parser.parse();
  13163. if (parser.sawUnambiguousESM) {
  13164. return ast;
  13165. }
  13166. if (parser.ambiguousScriptDifferentAst) {
  13167. try {
  13168. options.sourceType = "script";
  13169. return getParser(options, input).parse();
  13170. } catch (_unused) {}
  13171. } else {
  13172. ast.program.sourceType = "script";
  13173. }
  13174. return ast;
  13175. } catch (moduleError) {
  13176. try {
  13177. options.sourceType = "script";
  13178. return getParser(options, input).parse();
  13179. } catch (_unused2) {}
  13180. throw moduleError;
  13181. }
  13182. } else {
  13183. return getParser(options, input).parse();
  13184. }
  13185. }
  13186. function parseExpression(input, options) {
  13187. const parser = getParser(options, input);
  13188. if (parser.options.strictMode) {
  13189. parser.state.strict = true;
  13190. }
  13191. return parser.getExpression();
  13192. }
  13193. function generateExportedTokenTypes(internalTokenTypes) {
  13194. const tokenTypes = {};
  13195. for (const typeName of Object.keys(internalTokenTypes)) {
  13196. tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]);
  13197. }
  13198. return tokenTypes;
  13199. }
  13200. const tokTypes = generateExportedTokenTypes(tt);
  13201. function getParser(options, input) {
  13202. let cls = Parser$2;
  13203. if (options != null && options.plugins) {
  13204. validatePlugins(options.plugins);
  13205. cls = getParserClass(options.plugins);
  13206. }
  13207. return new cls(options, input);
  13208. }
  13209. const parserClassCache = {};
  13210. function getParserClass(pluginsFromOptions) {
  13211. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  13212. const key = pluginList.join("/");
  13213. let cls = parserClassCache[key];
  13214. if (!cls) {
  13215. cls = Parser$2;
  13216. for (const plugin of pluginList) {
  13217. cls = mixinPlugins[plugin](cls);
  13218. }
  13219. parserClassCache[key] = cls;
  13220. }
  13221. return cls;
  13222. }
  13223. var parse_1$1 = lib.parse = parse$9;
  13224. var parseExpression_1 = lib.parseExpression = parseExpression;
  13225. lib.tokTypes = tokTypes;
  13226. const isStaticExp = (p) => p.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && p.isStatic;
  13227. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  13228. function isCoreComponent(tag) {
  13229. if (isBuiltInType(tag, 'Teleport')) {
  13230. return TELEPORT;
  13231. }
  13232. else if (isBuiltInType(tag, 'Suspense')) {
  13233. return SUSPENSE;
  13234. }
  13235. else if (isBuiltInType(tag, 'KeepAlive')) {
  13236. return KEEP_ALIVE;
  13237. }
  13238. else if (isBuiltInType(tag, 'BaseTransition')) {
  13239. return BASE_TRANSITION;
  13240. }
  13241. }
  13242. const nonIdentifierRE = /^\d|[^\$\w]/;
  13243. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  13244. const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
  13245. const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
  13246. const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
  13247. /**
  13248. * Simple lexer to check if an expression is a member expression. This is
  13249. * lax and only checks validity at the root level (i.e. does not validate exps
  13250. * inside square brackets), but it's ok since these are only used on template
  13251. * expressions and false positives are invalid expressions in the first place.
  13252. */
  13253. const isMemberExpressionBrowser = (path) => {
  13254. // remove whitespaces around . or [ first
  13255. path = path.trim().replace(whitespaceRE, s => s.trim());
  13256. let state = 0 /* MemberExpLexState.inMemberExp */;
  13257. let stateStack = [];
  13258. let currentOpenBracketCount = 0;
  13259. let currentOpenParensCount = 0;
  13260. let currentStringType = null;
  13261. for (let i = 0; i < path.length; i++) {
  13262. const char = path.charAt(i);
  13263. switch (state) {
  13264. case 0 /* MemberExpLexState.inMemberExp */:
  13265. if (char === '[') {
  13266. stateStack.push(state);
  13267. state = 1 /* MemberExpLexState.inBrackets */;
  13268. currentOpenBracketCount++;
  13269. }
  13270. else if (char === '(') {
  13271. stateStack.push(state);
  13272. state = 2 /* MemberExpLexState.inParens */;
  13273. currentOpenParensCount++;
  13274. }
  13275. else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
  13276. return false;
  13277. }
  13278. break;
  13279. case 1 /* MemberExpLexState.inBrackets */:
  13280. if (char === `'` || char === `"` || char === '`') {
  13281. stateStack.push(state);
  13282. state = 3 /* MemberExpLexState.inString */;
  13283. currentStringType = char;
  13284. }
  13285. else if (char === `[`) {
  13286. currentOpenBracketCount++;
  13287. }
  13288. else if (char === `]`) {
  13289. if (!--currentOpenBracketCount) {
  13290. state = stateStack.pop();
  13291. }
  13292. }
  13293. break;
  13294. case 2 /* MemberExpLexState.inParens */:
  13295. if (char === `'` || char === `"` || char === '`') {
  13296. stateStack.push(state);
  13297. state = 3 /* MemberExpLexState.inString */;
  13298. currentStringType = char;
  13299. }
  13300. else if (char === `(`) {
  13301. currentOpenParensCount++;
  13302. }
  13303. else if (char === `)`) {
  13304. // if the exp ends as a call then it should not be considered valid
  13305. if (i === path.length - 1) {
  13306. return false;
  13307. }
  13308. if (!--currentOpenParensCount) {
  13309. state = stateStack.pop();
  13310. }
  13311. }
  13312. break;
  13313. case 3 /* MemberExpLexState.inString */:
  13314. if (char === currentStringType) {
  13315. state = stateStack.pop();
  13316. currentStringType = null;
  13317. }
  13318. break;
  13319. }
  13320. }
  13321. return !currentOpenBracketCount && !currentOpenParensCount;
  13322. };
  13323. const isMemberExpressionNode = (path, context) => {
  13324. try {
  13325. let ret = parseExpression_1(path, {
  13326. plugins: context.expressionPlugins
  13327. });
  13328. if (ret.type === 'TSAsExpression' || ret.type === 'TSTypeAssertion') {
  13329. ret = ret.expression;
  13330. }
  13331. return (ret.type === 'MemberExpression' ||
  13332. ret.type === 'OptionalMemberExpression' ||
  13333. ret.type === 'Identifier');
  13334. }
  13335. catch (e) {
  13336. return false;
  13337. }
  13338. };
  13339. const isMemberExpression = isMemberExpressionNode;
  13340. function getInnerRange(loc, offset, length) {
  13341. const source = loc.source.slice(offset, offset + length);
  13342. const newLoc = {
  13343. source,
  13344. start: advancePositionWithClone(loc.start, loc.source, offset),
  13345. end: loc.end
  13346. };
  13347. if (length != null) {
  13348. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  13349. }
  13350. return newLoc;
  13351. }
  13352. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  13353. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  13354. }
  13355. // advance by mutation without cloning (for performance reasons), since this
  13356. // gets called a lot in the parser
  13357. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  13358. let linesCount = 0;
  13359. let lastNewLinePos = -1;
  13360. for (let i = 0; i < numberOfCharacters; i++) {
  13361. if (source.charCodeAt(i) === 10 /* newline char code */) {
  13362. linesCount++;
  13363. lastNewLinePos = i;
  13364. }
  13365. }
  13366. pos.offset += numberOfCharacters;
  13367. pos.line += linesCount;
  13368. pos.column =
  13369. lastNewLinePos === -1
  13370. ? pos.column + numberOfCharacters
  13371. : numberOfCharacters - lastNewLinePos;
  13372. return pos;
  13373. }
  13374. function assert(condition, msg) {
  13375. /* istanbul ignore if */
  13376. if (!condition) {
  13377. throw new Error(msg || `unexpected compiler condition`);
  13378. }
  13379. }
  13380. function findDir(node, name, allowEmpty = false) {
  13381. for (let i = 0; i < node.props.length; i++) {
  13382. const p = node.props[i];
  13383. if (p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  13384. (allowEmpty || p.exp) &&
  13385. (isString$2(name) ? p.name === name : name.test(p.name))) {
  13386. return p;
  13387. }
  13388. }
  13389. }
  13390. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  13391. for (let i = 0; i < node.props.length; i++) {
  13392. const p = node.props[i];
  13393. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  13394. if (dynamicOnly)
  13395. continue;
  13396. if (p.name === name && (p.value || allowEmpty)) {
  13397. return p;
  13398. }
  13399. }
  13400. else if (p.name === 'bind' &&
  13401. (p.exp || allowEmpty) &&
  13402. isStaticArgOf(p.arg, name)) {
  13403. return p;
  13404. }
  13405. }
  13406. }
  13407. function isStaticArgOf(arg, name) {
  13408. return !!(arg && isStaticExp(arg) && arg.content === name);
  13409. }
  13410. function hasDynamicKeyVBind(node) {
  13411. return node.props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  13412. p.name === 'bind' &&
  13413. (!p.arg || // v-bind="obj"
  13414. p.arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  13415. !p.arg.isStatic) // v-bind:[foo]
  13416. );
  13417. }
  13418. function isText$1(node) {
  13419. return node.type === 5 /* NodeTypes.INTERPOLATION */ || node.type === 2 /* NodeTypes.TEXT */;
  13420. }
  13421. function isVSlot(p) {
  13422. return p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'slot';
  13423. }
  13424. function isTemplateNode(node) {
  13425. return (node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 3 /* ElementTypes.TEMPLATE */);
  13426. }
  13427. function isSlotOutlet(node) {
  13428. return node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 2 /* ElementTypes.SLOT */;
  13429. }
  13430. function getVNodeHelper(ssr, isComponent) {
  13431. return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
  13432. }
  13433. function getVNodeBlockHelper(ssr, isComponent) {
  13434. return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
  13435. }
  13436. const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
  13437. function getUnnormalizedProps(props, callPath = []) {
  13438. if (props &&
  13439. !isString$2(props) &&
  13440. props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  13441. const callee = props.callee;
  13442. if (!isString$2(callee) && propsHelperSet.has(callee)) {
  13443. return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
  13444. }
  13445. }
  13446. return [props, callPath];
  13447. }
  13448. function injectProp(node, prop, context) {
  13449. let propsWithInjection;
  13450. /**
  13451. * 1. mergeProps(...)
  13452. * 2. toHandlers(...)
  13453. * 3. normalizeProps(...)
  13454. * 4. normalizeProps(guardReactiveProps(...))
  13455. *
  13456. * we need to get the real props before normalization
  13457. */
  13458. let props = node.type === 13 /* NodeTypes.VNODE_CALL */ ? node.props : node.arguments[2];
  13459. let callPath = [];
  13460. let parentCall;
  13461. if (props &&
  13462. !isString$2(props) &&
  13463. props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  13464. const ret = getUnnormalizedProps(props);
  13465. props = ret[0];
  13466. callPath = ret[1];
  13467. parentCall = callPath[callPath.length - 1];
  13468. }
  13469. if (props == null || isString$2(props)) {
  13470. propsWithInjection = createObjectExpression([prop]);
  13471. }
  13472. else if (props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  13473. // merged props... add ours
  13474. // only inject key to object literal if it's the first argument so that
  13475. // if doesn't override user provided keys
  13476. const first = props.arguments[0];
  13477. if (!isString$2(first) && first.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  13478. // #6631
  13479. if (!hasProp(prop, first)) {
  13480. first.properties.unshift(prop);
  13481. }
  13482. }
  13483. else {
  13484. if (props.callee === TO_HANDLERS) {
  13485. // #2366
  13486. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  13487. createObjectExpression([prop]),
  13488. props
  13489. ]);
  13490. }
  13491. else {
  13492. props.arguments.unshift(createObjectExpression([prop]));
  13493. }
  13494. }
  13495. !propsWithInjection && (propsWithInjection = props);
  13496. }
  13497. else if (props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  13498. if (!hasProp(prop, props)) {
  13499. props.properties.unshift(prop);
  13500. }
  13501. propsWithInjection = props;
  13502. }
  13503. else {
  13504. // single v-bind with expression, return a merged replacement
  13505. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  13506. createObjectExpression([prop]),
  13507. props
  13508. ]);
  13509. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
  13510. // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
  13511. // the `guardReactiveProps` will no longer be needed
  13512. if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
  13513. parentCall = callPath[callPath.length - 2];
  13514. }
  13515. }
  13516. if (node.type === 13 /* NodeTypes.VNODE_CALL */) {
  13517. if (parentCall) {
  13518. parentCall.arguments[0] = propsWithInjection;
  13519. }
  13520. else {
  13521. node.props = propsWithInjection;
  13522. }
  13523. }
  13524. else {
  13525. if (parentCall) {
  13526. parentCall.arguments[0] = propsWithInjection;
  13527. }
  13528. else {
  13529. node.arguments[2] = propsWithInjection;
  13530. }
  13531. }
  13532. }
  13533. // check existing key to avoid overriding user provided keys
  13534. function hasProp(prop, props) {
  13535. let result = false;
  13536. if (prop.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  13537. const propKeyName = prop.key.content;
  13538. result = props.properties.some(p => p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  13539. p.key.content === propKeyName);
  13540. }
  13541. return result;
  13542. }
  13543. function toValidAssetId(name, type) {
  13544. // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
  13545. return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
  13546. return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
  13547. })}`;
  13548. }
  13549. // Check if a node contains expressions that reference current context scope ids
  13550. function hasScopeRef(node, ids) {
  13551. if (!node || Object.keys(ids).length === 0) {
  13552. return false;
  13553. }
  13554. switch (node.type) {
  13555. case 1 /* NodeTypes.ELEMENT */:
  13556. for (let i = 0; i < node.props.length; i++) {
  13557. const p = node.props[i];
  13558. if (p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  13559. (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {
  13560. return true;
  13561. }
  13562. }
  13563. return node.children.some(c => hasScopeRef(c, ids));
  13564. case 11 /* NodeTypes.FOR */:
  13565. if (hasScopeRef(node.source, ids)) {
  13566. return true;
  13567. }
  13568. return node.children.some(c => hasScopeRef(c, ids));
  13569. case 9 /* NodeTypes.IF */:
  13570. return node.branches.some(b => hasScopeRef(b, ids));
  13571. case 10 /* NodeTypes.IF_BRANCH */:
  13572. if (hasScopeRef(node.condition, ids)) {
  13573. return true;
  13574. }
  13575. return node.children.some(c => hasScopeRef(c, ids));
  13576. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  13577. return (!node.isStatic &&
  13578. isSimpleIdentifier(node.content) &&
  13579. !!ids[node.content]);
  13580. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  13581. return node.children.some(c => isObject$2(c) && hasScopeRef(c, ids));
  13582. case 5 /* NodeTypes.INTERPOLATION */:
  13583. case 12 /* NodeTypes.TEXT_CALL */:
  13584. return hasScopeRef(node.content, ids);
  13585. case 2 /* NodeTypes.TEXT */:
  13586. case 3 /* NodeTypes.COMMENT */:
  13587. return false;
  13588. default:
  13589. return false;
  13590. }
  13591. }
  13592. function getMemoedVNodeCall(node) {
  13593. if (node.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
  13594. return node.arguments[1].returns;
  13595. }
  13596. else {
  13597. return node;
  13598. }
  13599. }
  13600. function makeBlock(node, { helper, removeHelper, inSSR }) {
  13601. if (!node.isBlock) {
  13602. node.isBlock = true;
  13603. removeHelper(getVNodeHelper(inSSR, node.isComponent));
  13604. helper(OPEN_BLOCK);
  13605. helper(getVNodeBlockHelper(inSSR, node.isComponent));
  13606. }
  13607. }
  13608. const deprecationData = {
  13609. ["COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */]: {
  13610. message: `Platform-native elements with "is" prop will no longer be ` +
  13611. `treated as components in Vue 3 unless the "is" value is explicitly ` +
  13612. `prefixed with "vue:".`,
  13613. link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
  13614. },
  13615. ["COMPILER_V_BIND_SYNC" /* CompilerDeprecationTypes.COMPILER_V_BIND_SYNC */]: {
  13616. message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
  13617. `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
  13618. `\`v-model:${key}\`.`,
  13619. link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
  13620. },
  13621. ["COMPILER_V_BIND_PROP" /* CompilerDeprecationTypes.COMPILER_V_BIND_PROP */]: {
  13622. message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
  13623. `Vue 3 will automatically set a binding as DOM property when appropriate.`
  13624. },
  13625. ["COMPILER_V_BIND_OBJECT_ORDER" /* CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER */]: {
  13626. message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
  13627. `object spread: it will now overwrite an existing non-mergeable attribute ` +
  13628. `that appears before v-bind in the case of conflict. ` +
  13629. `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
  13630. `You can also suppress this warning if the usage is intended.`,
  13631. link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
  13632. },
  13633. ["COMPILER_V_ON_NATIVE" /* CompilerDeprecationTypes.COMPILER_V_ON_NATIVE */]: {
  13634. message: `.native modifier for v-on has been removed as is no longer necessary.`,
  13635. link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
  13636. },
  13637. ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* CompilerDeprecationTypes.COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
  13638. message: `v-if / v-for precedence when used on the same element has changed ` +
  13639. `in Vue 3: v-if now takes higher precedence and will no longer have ` +
  13640. `access to v-for scope variables. It is best to avoid the ambiguity ` +
  13641. `with <template> tags or use a computed property that filters v-for ` +
  13642. `data source.`,
  13643. link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
  13644. },
  13645. ["COMPILER_NATIVE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_NATIVE_TEMPLATE */]: {
  13646. message: `<template> with no special directives will render as a native template ` +
  13647. `element instead of its inner content in Vue 3.`
  13648. },
  13649. ["COMPILER_INLINE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_INLINE_TEMPLATE */]: {
  13650. message: `"inline-template" has been removed in Vue 3.`,
  13651. link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
  13652. },
  13653. ["COMPILER_FILTER" /* CompilerDeprecationTypes.COMPILER_FILTERS */]: {
  13654. message: `filters have been removed in Vue 3. ` +
  13655. `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
  13656. `Use method calls or computed properties instead.`,
  13657. link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
  13658. }
  13659. };
  13660. function getCompatValue(key, context) {
  13661. const config = context.options
  13662. ? context.options.compatConfig
  13663. : context.compatConfig;
  13664. const value = config && config[key];
  13665. if (key === 'MODE') {
  13666. return value || 3; // compiler defaults to v3 behavior
  13667. }
  13668. else {
  13669. return value;
  13670. }
  13671. }
  13672. function isCompatEnabled(key, context) {
  13673. const mode = getCompatValue('MODE', context);
  13674. const value = getCompatValue(key, context);
  13675. // in v3 mode, only enable if explicitly set to true
  13676. // otherwise enable for any non-false value
  13677. return mode === 3 ? value === true : value !== false;
  13678. }
  13679. function checkCompatEnabled(key, context, loc, ...args) {
  13680. const enabled = isCompatEnabled(key, context);
  13681. if (enabled) {
  13682. warnDeprecation(key, context, loc, ...args);
  13683. }
  13684. return enabled;
  13685. }
  13686. function warnDeprecation(key, context, loc, ...args) {
  13687. const val = getCompatValue(key, context);
  13688. if (val === 'suppress-warning') {
  13689. return;
  13690. }
  13691. const { message, link } = deprecationData[key];
  13692. const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
  13693. const err = new SyntaxError(msg);
  13694. err.code = key;
  13695. if (loc)
  13696. err.loc = loc;
  13697. context.onWarn(err);
  13698. }
  13699. // The default decoder only provides escapes for characters reserved as part of
  13700. // the template syntax, and is only used if the custom renderer did not provide
  13701. // a platform-specific decoder.
  13702. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  13703. const decodeMap = {
  13704. gt: '>',
  13705. lt: '<',
  13706. amp: '&',
  13707. apos: "'",
  13708. quot: '"'
  13709. };
  13710. const defaultParserOptions = {
  13711. delimiters: [`{{`, `}}`],
  13712. getNamespace: () => 0 /* Namespaces.HTML */,
  13713. getTextMode: () => 0 /* TextModes.DATA */,
  13714. isVoidTag: NO,
  13715. isPreTag: NO,
  13716. isCustomElement: NO,
  13717. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  13718. onError: defaultOnError,
  13719. onWarn: defaultOnWarn,
  13720. comments: true
  13721. };
  13722. function baseParse(content, options = {}) {
  13723. const context = createParserContext(content, options);
  13724. const start = getCursor(context);
  13725. return createRoot(parseChildren(context, 0 /* TextModes.DATA */, []), getSelection(context, start));
  13726. }
  13727. function createParserContext(content, rawOptions) {
  13728. const options = extend({}, defaultParserOptions);
  13729. let key;
  13730. for (key in rawOptions) {
  13731. // @ts-ignore
  13732. options[key] =
  13733. rawOptions[key] === undefined
  13734. ? defaultParserOptions[key]
  13735. : rawOptions[key];
  13736. }
  13737. return {
  13738. options,
  13739. column: 1,
  13740. line: 1,
  13741. offset: 0,
  13742. originalSource: content,
  13743. source: content,
  13744. inPre: false,
  13745. inVPre: false,
  13746. onWarn: options.onWarn
  13747. };
  13748. }
  13749. function parseChildren(context, mode, ancestors) {
  13750. const parent = last(ancestors);
  13751. const ns = parent ? parent.ns : 0 /* Namespaces.HTML */;
  13752. const nodes = [];
  13753. while (!isEnd(context, mode, ancestors)) {
  13754. const s = context.source;
  13755. let node = undefined;
  13756. if (mode === 0 /* TextModes.DATA */ || mode === 1 /* TextModes.RCDATA */) {
  13757. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  13758. // '{{'
  13759. node = parseInterpolation(context, mode);
  13760. }
  13761. else if (mode === 0 /* TextModes.DATA */ && s[0] === '<') {
  13762. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  13763. if (s.length === 1) {
  13764. emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 1);
  13765. }
  13766. else if (s[1] === '!') {
  13767. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  13768. if (startsWith(s, '<!--')) {
  13769. node = parseComment(context);
  13770. }
  13771. else if (startsWith(s, '<!DOCTYPE')) {
  13772. // Ignore DOCTYPE by a limitation.
  13773. node = parseBogusComment(context);
  13774. }
  13775. else if (startsWith(s, '<![CDATA[')) {
  13776. if (ns !== 0 /* Namespaces.HTML */) {
  13777. node = parseCDATA(context, ancestors);
  13778. }
  13779. else {
  13780. emitError(context, 1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */);
  13781. node = parseBogusComment(context);
  13782. }
  13783. }
  13784. else {
  13785. emitError(context, 11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */);
  13786. node = parseBogusComment(context);
  13787. }
  13788. }
  13789. else if (s[1] === '/') {
  13790. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  13791. if (s.length === 2) {
  13792. emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 2);
  13793. }
  13794. else if (s[2] === '>') {
  13795. emitError(context, 14 /* ErrorCodes.MISSING_END_TAG_NAME */, 2);
  13796. advanceBy(context, 3);
  13797. continue;
  13798. }
  13799. else if (/[a-z]/i.test(s[2])) {
  13800. emitError(context, 23 /* ErrorCodes.X_INVALID_END_TAG */);
  13801. parseTag(context, 1 /* TagType.End */, parent);
  13802. continue;
  13803. }
  13804. else {
  13805. emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  13806. node = parseBogusComment(context);
  13807. }
  13808. }
  13809. else if (/[a-z]/i.test(s[1])) {
  13810. node = parseElement(context, ancestors);
  13811. }
  13812. else if (s[1] === '?') {
  13813. emitError(context, 21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  13814. node = parseBogusComment(context);
  13815. }
  13816. else {
  13817. emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  13818. }
  13819. }
  13820. }
  13821. if (!node) {
  13822. node = parseText(context, mode);
  13823. }
  13824. if (isArray$3(node)) {
  13825. for (let i = 0; i < node.length; i++) {
  13826. pushNode(nodes, node[i]);
  13827. }
  13828. }
  13829. else {
  13830. pushNode(nodes, node);
  13831. }
  13832. }
  13833. // Whitespace handling strategy like v2
  13834. let removedWhitespace = false;
  13835. if (mode !== 2 /* TextModes.RAWTEXT */ && mode !== 1 /* TextModes.RCDATA */) {
  13836. const shouldCondense = context.options.whitespace !== 'preserve';
  13837. for (let i = 0; i < nodes.length; i++) {
  13838. const node = nodes[i];
  13839. if (node.type === 2 /* NodeTypes.TEXT */) {
  13840. if (!context.inPre) {
  13841. if (!/[^\t\r\n\f ]/.test(node.content)) {
  13842. const prev = nodes[i - 1];
  13843. const next = nodes[i + 1];
  13844. // Remove if:
  13845. // - the whitespace is the first or last node, or:
  13846. // - (condense mode) the whitespace is between twos comments, or:
  13847. // - (condense mode) the whitespace is between comment and element, or:
  13848. // - (condense mode) the whitespace is between two elements AND contains newline
  13849. if (!prev ||
  13850. !next ||
  13851. (shouldCondense &&
  13852. ((prev.type === 3 /* NodeTypes.COMMENT */ &&
  13853. next.type === 3 /* NodeTypes.COMMENT */) ||
  13854. (prev.type === 3 /* NodeTypes.COMMENT */ &&
  13855. next.type === 1 /* NodeTypes.ELEMENT */) ||
  13856. (prev.type === 1 /* NodeTypes.ELEMENT */ &&
  13857. next.type === 3 /* NodeTypes.COMMENT */) ||
  13858. (prev.type === 1 /* NodeTypes.ELEMENT */ &&
  13859. next.type === 1 /* NodeTypes.ELEMENT */ &&
  13860. /[\r\n]/.test(node.content))))) {
  13861. removedWhitespace = true;
  13862. nodes[i] = null;
  13863. }
  13864. else {
  13865. // Otherwise, the whitespace is condensed into a single space
  13866. node.content = ' ';
  13867. }
  13868. }
  13869. else if (shouldCondense) {
  13870. // in condense mode, consecutive whitespaces in text are condensed
  13871. // down to a single space.
  13872. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  13873. }
  13874. }
  13875. else {
  13876. // #6410 normalize windows newlines in <pre>:
  13877. // in SSR, browsers normalize server-rendered \r\n into a single \n
  13878. // in the DOM
  13879. node.content = node.content.replace(/\r\n/g, '\n');
  13880. }
  13881. }
  13882. // Remove comment nodes if desired by configuration.
  13883. else if (node.type === 3 /* NodeTypes.COMMENT */ && !context.options.comments) {
  13884. removedWhitespace = true;
  13885. nodes[i] = null;
  13886. }
  13887. }
  13888. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  13889. // remove leading newline per html spec
  13890. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  13891. const first = nodes[0];
  13892. if (first && first.type === 2 /* NodeTypes.TEXT */) {
  13893. first.content = first.content.replace(/^\r?\n/, '');
  13894. }
  13895. }
  13896. }
  13897. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  13898. }
  13899. function pushNode(nodes, node) {
  13900. if (node.type === 2 /* NodeTypes.TEXT */) {
  13901. const prev = last(nodes);
  13902. // Merge if both this and the previous node are text and those are
  13903. // consecutive. This happens for cases like "a < b".
  13904. if (prev &&
  13905. prev.type === 2 /* NodeTypes.TEXT */ &&
  13906. prev.loc.end.offset === node.loc.start.offset) {
  13907. prev.content += node.content;
  13908. prev.loc.end = node.loc.end;
  13909. prev.loc.source += node.loc.source;
  13910. return;
  13911. }
  13912. }
  13913. nodes.push(node);
  13914. }
  13915. function parseCDATA(context, ancestors) {
  13916. advanceBy(context, 9);
  13917. const nodes = parseChildren(context, 3 /* TextModes.CDATA */, ancestors);
  13918. if (context.source.length === 0) {
  13919. emitError(context, 6 /* ErrorCodes.EOF_IN_CDATA */);
  13920. }
  13921. else {
  13922. advanceBy(context, 3);
  13923. }
  13924. return nodes;
  13925. }
  13926. function parseComment(context) {
  13927. const start = getCursor(context);
  13928. let content;
  13929. // Regular comment.
  13930. const match = /--(\!)?>/.exec(context.source);
  13931. if (!match) {
  13932. content = context.source.slice(4);
  13933. advanceBy(context, context.source.length);
  13934. emitError(context, 7 /* ErrorCodes.EOF_IN_COMMENT */);
  13935. }
  13936. else {
  13937. if (match.index <= 3) {
  13938. emitError(context, 0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  13939. }
  13940. if (match[1]) {
  13941. emitError(context, 10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */);
  13942. }
  13943. content = context.source.slice(4, match.index);
  13944. // Advancing with reporting nested comments.
  13945. const s = context.source.slice(0, match.index);
  13946. let prevIndex = 1, nestedIndex = 0;
  13947. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  13948. advanceBy(context, nestedIndex - prevIndex + 1);
  13949. if (nestedIndex + 4 < s.length) {
  13950. emitError(context, 16 /* ErrorCodes.NESTED_COMMENT */);
  13951. }
  13952. prevIndex = nestedIndex + 1;
  13953. }
  13954. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  13955. }
  13956. return {
  13957. type: 3 /* NodeTypes.COMMENT */,
  13958. content,
  13959. loc: getSelection(context, start)
  13960. };
  13961. }
  13962. function parseBogusComment(context) {
  13963. const start = getCursor(context);
  13964. const contentStart = context.source[1] === '?' ? 1 : 2;
  13965. let content;
  13966. const closeIndex = context.source.indexOf('>');
  13967. if (closeIndex === -1) {
  13968. content = context.source.slice(contentStart);
  13969. advanceBy(context, context.source.length);
  13970. }
  13971. else {
  13972. content = context.source.slice(contentStart, closeIndex);
  13973. advanceBy(context, closeIndex + 1);
  13974. }
  13975. return {
  13976. type: 3 /* NodeTypes.COMMENT */,
  13977. content,
  13978. loc: getSelection(context, start)
  13979. };
  13980. }
  13981. function parseElement(context, ancestors) {
  13982. // Start tag.
  13983. const wasInPre = context.inPre;
  13984. const wasInVPre = context.inVPre;
  13985. const parent = last(ancestors);
  13986. const element = parseTag(context, 0 /* TagType.Start */, parent);
  13987. const isPreBoundary = context.inPre && !wasInPre;
  13988. const isVPreBoundary = context.inVPre && !wasInVPre;
  13989. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  13990. // #4030 self-closing <pre> tag
  13991. if (isPreBoundary) {
  13992. context.inPre = false;
  13993. }
  13994. if (isVPreBoundary) {
  13995. context.inVPre = false;
  13996. }
  13997. return element;
  13998. }
  13999. // Children.
  14000. ancestors.push(element);
  14001. const mode = context.options.getTextMode(element, parent);
  14002. const children = parseChildren(context, mode, ancestors);
  14003. ancestors.pop();
  14004. element.children = children;
  14005. // End tag.
  14006. if (startsWithEndTagOpen(context.source, element.tag)) {
  14007. parseTag(context, 1 /* TagType.End */, parent);
  14008. }
  14009. else {
  14010. emitError(context, 24 /* ErrorCodes.X_MISSING_END_TAG */, 0, element.loc.start);
  14011. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  14012. const first = children[0];
  14013. if (first && startsWith(first.loc.source, '<!--')) {
  14014. emitError(context, 8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  14015. }
  14016. }
  14017. }
  14018. element.loc = getSelection(context, element.loc.start);
  14019. if (isPreBoundary) {
  14020. context.inPre = false;
  14021. }
  14022. if (isVPreBoundary) {
  14023. context.inVPre = false;
  14024. }
  14025. return element;
  14026. }
  14027. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  14028. function parseTag(context, type, parent) {
  14029. // Tag open.
  14030. const start = getCursor(context);
  14031. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  14032. const tag = match[1];
  14033. const ns = context.options.getNamespace(tag, parent);
  14034. advanceBy(context, match[0].length);
  14035. advanceSpaces(context);
  14036. // save current state in case we need to re-parse attributes with v-pre
  14037. const cursor = getCursor(context);
  14038. const currentSource = context.source;
  14039. // check <pre> tag
  14040. if (context.options.isPreTag(tag)) {
  14041. context.inPre = true;
  14042. }
  14043. // Attributes.
  14044. let props = parseAttributes(context, type);
  14045. // check v-pre
  14046. if (type === 0 /* TagType.Start */ &&
  14047. !context.inVPre &&
  14048. props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'pre')) {
  14049. context.inVPre = true;
  14050. // reset context
  14051. extend(context, cursor);
  14052. context.source = currentSource;
  14053. // re-parse attrs and filter out v-pre itself
  14054. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  14055. }
  14056. // Tag close.
  14057. let isSelfClosing = false;
  14058. if (context.source.length === 0) {
  14059. emitError(context, 9 /* ErrorCodes.EOF_IN_TAG */);
  14060. }
  14061. else {
  14062. isSelfClosing = startsWith(context.source, '/>');
  14063. if (type === 1 /* TagType.End */ && isSelfClosing) {
  14064. emitError(context, 4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */);
  14065. }
  14066. advanceBy(context, isSelfClosing ? 2 : 1);
  14067. }
  14068. if (type === 1 /* TagType.End */) {
  14069. return;
  14070. }
  14071. let tagType = 0 /* ElementTypes.ELEMENT */;
  14072. if (!context.inVPre) {
  14073. if (tag === 'slot') {
  14074. tagType = 2 /* ElementTypes.SLOT */;
  14075. }
  14076. else if (tag === 'template') {
  14077. if (props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
  14078. tagType = 3 /* ElementTypes.TEMPLATE */;
  14079. }
  14080. }
  14081. else if (isComponent(tag, props, context)) {
  14082. tagType = 1 /* ElementTypes.COMPONENT */;
  14083. }
  14084. }
  14085. return {
  14086. type: 1 /* NodeTypes.ELEMENT */,
  14087. ns,
  14088. tag,
  14089. tagType,
  14090. props,
  14091. isSelfClosing,
  14092. children: [],
  14093. loc: getSelection(context, start),
  14094. codegenNode: undefined // to be created during transform phase
  14095. };
  14096. }
  14097. function isComponent(tag, props, context) {
  14098. const options = context.options;
  14099. if (options.isCustomElement(tag)) {
  14100. return false;
  14101. }
  14102. if (tag === 'component' ||
  14103. /^[A-Z]/.test(tag) ||
  14104. isCoreComponent(tag) ||
  14105. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  14106. (options.isNativeTag && !options.isNativeTag(tag))) {
  14107. return true;
  14108. }
  14109. // at this point the tag should be a native tag, but check for potential "is"
  14110. // casting
  14111. for (let i = 0; i < props.length; i++) {
  14112. const p = props[i];
  14113. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  14114. if (p.name === 'is' && p.value) {
  14115. if (p.value.content.startsWith('vue:')) {
  14116. return true;
  14117. }
  14118. }
  14119. }
  14120. else {
  14121. // directive
  14122. // v-is (TODO Deprecate)
  14123. if (p.name === 'is') {
  14124. return true;
  14125. }
  14126. else if (
  14127. // :is on plain element - only treat as component in compat mode
  14128. p.name === 'bind' &&
  14129. isStaticArgOf(p.arg, 'is') &&
  14130. false &&
  14131. checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
  14132. return true;
  14133. }
  14134. }
  14135. }
  14136. }
  14137. function parseAttributes(context, type) {
  14138. const props = [];
  14139. const attributeNames = new Set();
  14140. while (context.source.length > 0 &&
  14141. !startsWith(context.source, '>') &&
  14142. !startsWith(context.source, '/>')) {
  14143. if (startsWith(context.source, '/')) {
  14144. emitError(context, 22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */);
  14145. advanceBy(context, 1);
  14146. advanceSpaces(context);
  14147. continue;
  14148. }
  14149. if (type === 1 /* TagType.End */) {
  14150. emitError(context, 3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */);
  14151. }
  14152. const attr = parseAttribute(context, attributeNames);
  14153. // Trim whitespace between class
  14154. // https://github.com/vuejs/core/issues/4251
  14155. if (attr.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  14156. attr.value &&
  14157. attr.name === 'class') {
  14158. attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
  14159. }
  14160. if (type === 0 /* TagType.Start */) {
  14161. props.push(attr);
  14162. }
  14163. if (/^[^\t\r\n\f />]/.test(context.source)) {
  14164. emitError(context, 15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  14165. }
  14166. advanceSpaces(context);
  14167. }
  14168. return props;
  14169. }
  14170. function parseAttribute(context, nameSet) {
  14171. // Name.
  14172. const start = getCursor(context);
  14173. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  14174. const name = match[0];
  14175. if (nameSet.has(name)) {
  14176. emitError(context, 2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */);
  14177. }
  14178. nameSet.add(name);
  14179. if (name[0] === '=') {
  14180. emitError(context, 19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  14181. }
  14182. {
  14183. const pattern = /["'<]/g;
  14184. let m;
  14185. while ((m = pattern.exec(name))) {
  14186. emitError(context, 17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  14187. }
  14188. }
  14189. advanceBy(context, name.length);
  14190. // Value
  14191. let value = undefined;
  14192. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  14193. advanceSpaces(context);
  14194. advanceBy(context, 1);
  14195. advanceSpaces(context);
  14196. value = parseAttributeValue(context);
  14197. if (!value) {
  14198. emitError(context, 13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */);
  14199. }
  14200. }
  14201. const loc = getSelection(context, start);
  14202. if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
  14203. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  14204. let isPropShorthand = startsWith(name, '.');
  14205. let dirName = match[1] ||
  14206. (isPropShorthand || startsWith(name, ':')
  14207. ? 'bind'
  14208. : startsWith(name, '@')
  14209. ? 'on'
  14210. : 'slot');
  14211. let arg;
  14212. if (match[2]) {
  14213. const isSlot = dirName === 'slot';
  14214. const startOffset = name.lastIndexOf(match[2]);
  14215. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  14216. let content = match[2];
  14217. let isStatic = true;
  14218. if (content.startsWith('[')) {
  14219. isStatic = false;
  14220. if (!content.endsWith(']')) {
  14221. emitError(context, 27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  14222. content = content.slice(1);
  14223. }
  14224. else {
  14225. content = content.slice(1, content.length - 1);
  14226. }
  14227. }
  14228. else if (isSlot) {
  14229. // #1241 special case for v-slot: vuetify relies extensively on slot
  14230. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  14231. // supports such usage so we are keeping it consistent with 2.x.
  14232. content += match[3] || '';
  14233. }
  14234. arg = {
  14235. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  14236. content,
  14237. isStatic,
  14238. constType: isStatic
  14239. ? 3 /* ConstantTypes.CAN_STRINGIFY */
  14240. : 0 /* ConstantTypes.NOT_CONSTANT */,
  14241. loc
  14242. };
  14243. }
  14244. if (value && value.isQuoted) {
  14245. const valueLoc = value.loc;
  14246. valueLoc.start.offset++;
  14247. valueLoc.start.column++;
  14248. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  14249. valueLoc.source = valueLoc.source.slice(1, -1);
  14250. }
  14251. const modifiers = match[3] ? match[3].slice(1).split('.') : [];
  14252. if (isPropShorthand)
  14253. modifiers.push('prop');
  14254. return {
  14255. type: 7 /* NodeTypes.DIRECTIVE */,
  14256. name: dirName,
  14257. exp: value && {
  14258. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  14259. content: value.content,
  14260. isStatic: false,
  14261. // Treat as non-constant by default. This can be potentially set to
  14262. // other values by `transformExpression` to make it eligible for hoisting.
  14263. constType: 0 /* ConstantTypes.NOT_CONSTANT */,
  14264. loc: value.loc
  14265. },
  14266. arg,
  14267. modifiers,
  14268. loc
  14269. };
  14270. }
  14271. // missing directive name or illegal directive name
  14272. if (!context.inVPre && startsWith(name, 'v-')) {
  14273. emitError(context, 26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */);
  14274. }
  14275. return {
  14276. type: 6 /* NodeTypes.ATTRIBUTE */,
  14277. name,
  14278. value: value && {
  14279. type: 2 /* NodeTypes.TEXT */,
  14280. content: value.content,
  14281. loc: value.loc
  14282. },
  14283. loc
  14284. };
  14285. }
  14286. function parseAttributeValue(context) {
  14287. const start = getCursor(context);
  14288. let content;
  14289. const quote = context.source[0];
  14290. const isQuoted = quote === `"` || quote === `'`;
  14291. if (isQuoted) {
  14292. // Quoted value.
  14293. advanceBy(context, 1);
  14294. const endIndex = context.source.indexOf(quote);
  14295. if (endIndex === -1) {
  14296. content = parseTextData(context, context.source.length, 4 /* TextModes.ATTRIBUTE_VALUE */);
  14297. }
  14298. else {
  14299. content = parseTextData(context, endIndex, 4 /* TextModes.ATTRIBUTE_VALUE */);
  14300. advanceBy(context, 1);
  14301. }
  14302. }
  14303. else {
  14304. // Unquoted
  14305. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  14306. if (!match) {
  14307. return undefined;
  14308. }
  14309. const unexpectedChars = /["'<=`]/g;
  14310. let m;
  14311. while ((m = unexpectedChars.exec(match[0]))) {
  14312. emitError(context, 18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  14313. }
  14314. content = parseTextData(context, match[0].length, 4 /* TextModes.ATTRIBUTE_VALUE */);
  14315. }
  14316. return { content, isQuoted, loc: getSelection(context, start) };
  14317. }
  14318. function parseInterpolation(context, mode) {
  14319. const [open, close] = context.options.delimiters;
  14320. const closeIndex = context.source.indexOf(close, open.length);
  14321. if (closeIndex === -1) {
  14322. emitError(context, 25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */);
  14323. return undefined;
  14324. }
  14325. const start = getCursor(context);
  14326. advanceBy(context, open.length);
  14327. const innerStart = getCursor(context);
  14328. const innerEnd = getCursor(context);
  14329. const rawContentLength = closeIndex - open.length;
  14330. const rawContent = context.source.slice(0, rawContentLength);
  14331. const preTrimContent = parseTextData(context, rawContentLength, mode);
  14332. const content = preTrimContent.trim();
  14333. const startOffset = preTrimContent.indexOf(content);
  14334. if (startOffset > 0) {
  14335. advancePositionWithMutation(innerStart, rawContent, startOffset);
  14336. }
  14337. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  14338. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  14339. advanceBy(context, close.length);
  14340. return {
  14341. type: 5 /* NodeTypes.INTERPOLATION */,
  14342. content: {
  14343. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  14344. isStatic: false,
  14345. // Set `isConstant` to false by default and will decide in transformExpression
  14346. constType: 0 /* ConstantTypes.NOT_CONSTANT */,
  14347. content,
  14348. loc: getSelection(context, innerStart, innerEnd)
  14349. },
  14350. loc: getSelection(context, start)
  14351. };
  14352. }
  14353. function parseText(context, mode) {
  14354. const endTokens = mode === 3 /* TextModes.CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
  14355. let endIndex = context.source.length;
  14356. for (let i = 0; i < endTokens.length; i++) {
  14357. const index = context.source.indexOf(endTokens[i], 1);
  14358. if (index !== -1 && endIndex > index) {
  14359. endIndex = index;
  14360. }
  14361. }
  14362. const start = getCursor(context);
  14363. const content = parseTextData(context, endIndex, mode);
  14364. return {
  14365. type: 2 /* NodeTypes.TEXT */,
  14366. content,
  14367. loc: getSelection(context, start)
  14368. };
  14369. }
  14370. /**
  14371. * Get text data with a given length from the current location.
  14372. * This translates HTML entities in the text data.
  14373. */
  14374. function parseTextData(context, length, mode) {
  14375. const rawText = context.source.slice(0, length);
  14376. advanceBy(context, length);
  14377. if (mode === 2 /* TextModes.RAWTEXT */ ||
  14378. mode === 3 /* TextModes.CDATA */ ||
  14379. !rawText.includes('&')) {
  14380. return rawText;
  14381. }
  14382. else {
  14383. // DATA or RCDATA containing "&"". Entity decoding required.
  14384. return context.options.decodeEntities(rawText, mode === 4 /* TextModes.ATTRIBUTE_VALUE */);
  14385. }
  14386. }
  14387. function getCursor(context) {
  14388. const { column, line, offset } = context;
  14389. return { column, line, offset };
  14390. }
  14391. function getSelection(context, start, end) {
  14392. end = end || getCursor(context);
  14393. return {
  14394. start,
  14395. end,
  14396. source: context.originalSource.slice(start.offset, end.offset)
  14397. };
  14398. }
  14399. function last(xs) {
  14400. return xs[xs.length - 1];
  14401. }
  14402. function startsWith(source, searchString) {
  14403. return source.startsWith(searchString);
  14404. }
  14405. function advanceBy(context, numberOfCharacters) {
  14406. const { source } = context;
  14407. advancePositionWithMutation(context, source, numberOfCharacters);
  14408. context.source = source.slice(numberOfCharacters);
  14409. }
  14410. function advanceSpaces(context) {
  14411. const match = /^[\t\r\n\f ]+/.exec(context.source);
  14412. if (match) {
  14413. advanceBy(context, match[0].length);
  14414. }
  14415. }
  14416. function getNewPosition(context, start, numberOfCharacters) {
  14417. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  14418. }
  14419. function emitError(context, code, offset, loc = getCursor(context)) {
  14420. if (offset) {
  14421. loc.offset += offset;
  14422. loc.column += offset;
  14423. }
  14424. context.options.onError(createCompilerError(code, {
  14425. start: loc,
  14426. end: loc,
  14427. source: ''
  14428. }));
  14429. }
  14430. function isEnd(context, mode, ancestors) {
  14431. const s = context.source;
  14432. switch (mode) {
  14433. case 0 /* TextModes.DATA */:
  14434. if (startsWith(s, '</')) {
  14435. // TODO: probably bad performance
  14436. for (let i = ancestors.length - 1; i >= 0; --i) {
  14437. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  14438. return true;
  14439. }
  14440. }
  14441. }
  14442. break;
  14443. case 1 /* TextModes.RCDATA */:
  14444. case 2 /* TextModes.RAWTEXT */: {
  14445. const parent = last(ancestors);
  14446. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  14447. return true;
  14448. }
  14449. break;
  14450. }
  14451. case 3 /* TextModes.CDATA */:
  14452. if (startsWith(s, ']]>')) {
  14453. return true;
  14454. }
  14455. break;
  14456. }
  14457. return !s;
  14458. }
  14459. function startsWithEndTagOpen(source, tag) {
  14460. return (startsWith(source, '</') &&
  14461. source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
  14462. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  14463. }
  14464. function hoistStatic(root, context) {
  14465. walk$2(root, context,
  14466. // Root node is unfortunately non-hoistable due to potential parent
  14467. // fallthrough attributes.
  14468. isSingleElementRoot(root, root.children[0]));
  14469. }
  14470. function isSingleElementRoot(root, child) {
  14471. const { children } = root;
  14472. return (children.length === 1 &&
  14473. child.type === 1 /* NodeTypes.ELEMENT */ &&
  14474. !isSlotOutlet(child));
  14475. }
  14476. function walk$2(node, context, doNotHoistNode = false) {
  14477. const { children } = node;
  14478. const originalCount = children.length;
  14479. let hoistedCount = 0;
  14480. for (let i = 0; i < children.length; i++) {
  14481. const child = children[i];
  14482. // only plain elements & text calls are eligible for hoisting.
  14483. if (child.type === 1 /* NodeTypes.ELEMENT */ &&
  14484. child.tagType === 0 /* ElementTypes.ELEMENT */) {
  14485. const constantType = doNotHoistNode
  14486. ? 0 /* ConstantTypes.NOT_CONSTANT */
  14487. : getConstantType(child, context);
  14488. if (constantType > 0 /* ConstantTypes.NOT_CONSTANT */) {
  14489. if (constantType >= 2 /* ConstantTypes.CAN_HOIST */) {
  14490. child.codegenNode.patchFlag =
  14491. -1 /* PatchFlags.HOISTED */ + (` /* HOISTED */` );
  14492. child.codegenNode = context.hoist(child.codegenNode);
  14493. hoistedCount++;
  14494. continue;
  14495. }
  14496. }
  14497. else {
  14498. // node may contain dynamic children, but its props may be eligible for
  14499. // hoisting.
  14500. const codegenNode = child.codegenNode;
  14501. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  14502. const flag = getPatchFlag(codegenNode);
  14503. if ((!flag ||
  14504. flag === 512 /* PatchFlags.NEED_PATCH */ ||
  14505. flag === 1 /* PatchFlags.TEXT */) &&
  14506. getGeneratedPropsConstantType(child, context) >=
  14507. 2 /* ConstantTypes.CAN_HOIST */) {
  14508. const props = getNodeProps(child);
  14509. if (props) {
  14510. codegenNode.props = context.hoist(props);
  14511. }
  14512. }
  14513. if (codegenNode.dynamicProps) {
  14514. codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
  14515. }
  14516. }
  14517. }
  14518. }
  14519. // walk further
  14520. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  14521. const isComponent = child.tagType === 1 /* ElementTypes.COMPONENT */;
  14522. if (isComponent) {
  14523. context.scopes.vSlot++;
  14524. }
  14525. walk$2(child, context);
  14526. if (isComponent) {
  14527. context.scopes.vSlot--;
  14528. }
  14529. }
  14530. else if (child.type === 11 /* NodeTypes.FOR */) {
  14531. // Do not hoist v-for single child because it has to be a block
  14532. walk$2(child, context, child.children.length === 1);
  14533. }
  14534. else if (child.type === 9 /* NodeTypes.IF */) {
  14535. for (let i = 0; i < child.branches.length; i++) {
  14536. // Do not hoist v-if single child because it has to be a block
  14537. walk$2(child.branches[i], context, child.branches[i].children.length === 1);
  14538. }
  14539. }
  14540. }
  14541. if (hoistedCount && context.transformHoist) {
  14542. context.transformHoist(children, context, node);
  14543. }
  14544. // all children were hoisted - the entire children array is hoistable.
  14545. if (hoistedCount &&
  14546. hoistedCount === originalCount &&
  14547. node.type === 1 /* NodeTypes.ELEMENT */ &&
  14548. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  14549. node.codegenNode &&
  14550. node.codegenNode.type === 13 /* NodeTypes.VNODE_CALL */ &&
  14551. isArray$3(node.codegenNode.children)) {
  14552. node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
  14553. }
  14554. }
  14555. function getConstantType(node, context) {
  14556. const { constantCache } = context;
  14557. switch (node.type) {
  14558. case 1 /* NodeTypes.ELEMENT */:
  14559. if (node.tagType !== 0 /* ElementTypes.ELEMENT */) {
  14560. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14561. }
  14562. const cached = constantCache.get(node);
  14563. if (cached !== undefined) {
  14564. return cached;
  14565. }
  14566. const codegenNode = node.codegenNode;
  14567. if (codegenNode.type !== 13 /* NodeTypes.VNODE_CALL */) {
  14568. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14569. }
  14570. if (codegenNode.isBlock &&
  14571. node.tag !== 'svg' &&
  14572. node.tag !== 'foreignObject') {
  14573. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14574. }
  14575. const flag = getPatchFlag(codegenNode);
  14576. if (!flag) {
  14577. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  14578. // Element itself has no patch flag. However we still need to check:
  14579. // 1. Even for a node with no patch flag, it is possible for it to contain
  14580. // non-hoistable expressions that refers to scope variables, e.g. compiler
  14581. // injected keys or cached event handlers. Therefore we need to always
  14582. // check the codegenNode's props to be sure.
  14583. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  14584. if (generatedPropsType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14585. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  14586. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14587. }
  14588. if (generatedPropsType < returnType) {
  14589. returnType = generatedPropsType;
  14590. }
  14591. // 2. its children.
  14592. for (let i = 0; i < node.children.length; i++) {
  14593. const childType = getConstantType(node.children[i], context);
  14594. if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14595. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  14596. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14597. }
  14598. if (childType < returnType) {
  14599. returnType = childType;
  14600. }
  14601. }
  14602. // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
  14603. // type, check if any of the props can cause the type to be lowered
  14604. // we can skip can_patch because it's guaranteed by the absence of a
  14605. // patchFlag.
  14606. if (returnType > 1 /* ConstantTypes.CAN_SKIP_PATCH */) {
  14607. for (let i = 0; i < node.props.length; i++) {
  14608. const p = node.props[i];
  14609. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'bind' && p.exp) {
  14610. const expType = getConstantType(p.exp, context);
  14611. if (expType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14612. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  14613. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14614. }
  14615. if (expType < returnType) {
  14616. returnType = expType;
  14617. }
  14618. }
  14619. }
  14620. }
  14621. // only svg/foreignObject could be block here, however if they are
  14622. // static then they don't need to be blocks since there will be no
  14623. // nested updates.
  14624. if (codegenNode.isBlock) {
  14625. // except set custom directives.
  14626. for (let i = 0; i < node.props.length; i++) {
  14627. const p = node.props[i];
  14628. if (p.type === 7 /* NodeTypes.DIRECTIVE */) {
  14629. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  14630. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14631. }
  14632. }
  14633. context.removeHelper(OPEN_BLOCK);
  14634. context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
  14635. codegenNode.isBlock = false;
  14636. context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
  14637. }
  14638. constantCache.set(node, returnType);
  14639. return returnType;
  14640. }
  14641. else {
  14642. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  14643. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14644. }
  14645. case 2 /* NodeTypes.TEXT */:
  14646. case 3 /* NodeTypes.COMMENT */:
  14647. return 3 /* ConstantTypes.CAN_STRINGIFY */;
  14648. case 9 /* NodeTypes.IF */:
  14649. case 11 /* NodeTypes.FOR */:
  14650. case 10 /* NodeTypes.IF_BRANCH */:
  14651. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14652. case 5 /* NodeTypes.INTERPOLATION */:
  14653. case 12 /* NodeTypes.TEXT_CALL */:
  14654. return getConstantType(node.content, context);
  14655. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  14656. return node.constType;
  14657. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  14658. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  14659. for (let i = 0; i < node.children.length; i++) {
  14660. const child = node.children[i];
  14661. if (isString$2(child) || isSymbol$1(child)) {
  14662. continue;
  14663. }
  14664. const childType = getConstantType(child, context);
  14665. if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14666. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14667. }
  14668. else if (childType < returnType) {
  14669. returnType = childType;
  14670. }
  14671. }
  14672. return returnType;
  14673. default:
  14674. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14675. }
  14676. }
  14677. const allowHoistedHelperSet = new Set([
  14678. NORMALIZE_CLASS,
  14679. NORMALIZE_STYLE,
  14680. NORMALIZE_PROPS,
  14681. GUARD_REACTIVE_PROPS
  14682. ]);
  14683. function getConstantTypeOfHelperCall(value, context) {
  14684. if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ &&
  14685. !isString$2(value.callee) &&
  14686. allowHoistedHelperSet.has(value.callee)) {
  14687. const arg = value.arguments[0];
  14688. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  14689. return getConstantType(arg, context);
  14690. }
  14691. else if (arg.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  14692. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
  14693. return getConstantTypeOfHelperCall(arg, context);
  14694. }
  14695. }
  14696. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14697. }
  14698. function getGeneratedPropsConstantType(node, context) {
  14699. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  14700. const props = getNodeProps(node);
  14701. if (props && props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  14702. const { properties } = props;
  14703. for (let i = 0; i < properties.length; i++) {
  14704. const { key, value } = properties[i];
  14705. const keyType = getConstantType(key, context);
  14706. if (keyType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14707. return keyType;
  14708. }
  14709. if (keyType < returnType) {
  14710. returnType = keyType;
  14711. }
  14712. let valueType;
  14713. if (value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  14714. valueType = getConstantType(value, context);
  14715. }
  14716. else if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  14717. // some helper calls can be hoisted,
  14718. // such as the `normalizeProps` generated by the compiler for pre-normalize class,
  14719. // in this case we need to respect the ConstantType of the helper's arguments
  14720. valueType = getConstantTypeOfHelperCall(value, context);
  14721. }
  14722. else {
  14723. valueType = 0 /* ConstantTypes.NOT_CONSTANT */;
  14724. }
  14725. if (valueType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14726. return valueType;
  14727. }
  14728. if (valueType < returnType) {
  14729. returnType = valueType;
  14730. }
  14731. }
  14732. }
  14733. return returnType;
  14734. }
  14735. function getNodeProps(node) {
  14736. const codegenNode = node.codegenNode;
  14737. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  14738. return codegenNode.props;
  14739. }
  14740. }
  14741. function getPatchFlag(node) {
  14742. const flag = node.patchFlag;
  14743. return flag ? parseInt(flag, 10) : undefined;
  14744. }
  14745. 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 }) {
  14746. const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
  14747. const context = {
  14748. // options
  14749. selfName: nameMatch && capitalize$1(camelize(nameMatch[1])),
  14750. prefixIdentifiers,
  14751. hoistStatic,
  14752. cacheHandlers,
  14753. nodeTransforms,
  14754. directiveTransforms,
  14755. transformHoist,
  14756. isBuiltInComponent,
  14757. isCustomElement,
  14758. expressionPlugins,
  14759. scopeId,
  14760. slotted,
  14761. ssr,
  14762. inSSR,
  14763. ssrCssVars,
  14764. bindingMetadata,
  14765. inline,
  14766. isTS,
  14767. onError,
  14768. onWarn,
  14769. compatConfig,
  14770. // state
  14771. root,
  14772. helpers: new Map(),
  14773. components: new Set(),
  14774. directives: new Set(),
  14775. hoists: [],
  14776. imports: [],
  14777. constantCache: new Map(),
  14778. temps: 0,
  14779. cached: 0,
  14780. identifiers: Object.create(null),
  14781. scopes: {
  14782. vFor: 0,
  14783. vSlot: 0,
  14784. vPre: 0,
  14785. vOnce: 0
  14786. },
  14787. parent: null,
  14788. currentNode: root,
  14789. childIndex: 0,
  14790. inVOnce: false,
  14791. // methods
  14792. helper(name) {
  14793. const count = context.helpers.get(name) || 0;
  14794. context.helpers.set(name, count + 1);
  14795. return name;
  14796. },
  14797. removeHelper(name) {
  14798. const count = context.helpers.get(name);
  14799. if (count) {
  14800. const currentCount = count - 1;
  14801. if (!currentCount) {
  14802. context.helpers.delete(name);
  14803. }
  14804. else {
  14805. context.helpers.set(name, currentCount);
  14806. }
  14807. }
  14808. },
  14809. helperString(name) {
  14810. return `_${helperNameMap[context.helper(name)]}`;
  14811. },
  14812. replaceNode(node) {
  14813. /* istanbul ignore if */
  14814. {
  14815. if (!context.currentNode) {
  14816. throw new Error(`Node being replaced is already removed.`);
  14817. }
  14818. if (!context.parent) {
  14819. throw new Error(`Cannot replace root node.`);
  14820. }
  14821. }
  14822. context.parent.children[context.childIndex] = context.currentNode = node;
  14823. },
  14824. removeNode(node) {
  14825. if (!context.parent) {
  14826. throw new Error(`Cannot remove root node.`);
  14827. }
  14828. const list = context.parent.children;
  14829. const removalIndex = node
  14830. ? list.indexOf(node)
  14831. : context.currentNode
  14832. ? context.childIndex
  14833. : -1;
  14834. /* istanbul ignore if */
  14835. if (removalIndex < 0) {
  14836. throw new Error(`node being removed is not a child of current parent`);
  14837. }
  14838. if (!node || node === context.currentNode) {
  14839. // current node removed
  14840. context.currentNode = null;
  14841. context.onNodeRemoved();
  14842. }
  14843. else {
  14844. // sibling node removed
  14845. if (context.childIndex > removalIndex) {
  14846. context.childIndex--;
  14847. context.onNodeRemoved();
  14848. }
  14849. }
  14850. context.parent.children.splice(removalIndex, 1);
  14851. },
  14852. onNodeRemoved: () => { },
  14853. addIdentifiers(exp) {
  14854. // identifier tracking only happens in non-browser builds.
  14855. {
  14856. if (isString$2(exp)) {
  14857. addId(exp);
  14858. }
  14859. else if (exp.identifiers) {
  14860. exp.identifiers.forEach(addId);
  14861. }
  14862. else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  14863. addId(exp.content);
  14864. }
  14865. }
  14866. },
  14867. removeIdentifiers(exp) {
  14868. {
  14869. if (isString$2(exp)) {
  14870. removeId(exp);
  14871. }
  14872. else if (exp.identifiers) {
  14873. exp.identifiers.forEach(removeId);
  14874. }
  14875. else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  14876. removeId(exp.content);
  14877. }
  14878. }
  14879. },
  14880. hoist(exp) {
  14881. if (isString$2(exp))
  14882. exp = createSimpleExpression(exp);
  14883. context.hoists.push(exp);
  14884. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* ConstantTypes.CAN_HOIST */);
  14885. identifier.hoisted = exp;
  14886. return identifier;
  14887. },
  14888. cache(exp, isVNode = false) {
  14889. return createCacheExpression(context.cached++, exp, isVNode);
  14890. }
  14891. };
  14892. function addId(id) {
  14893. const { identifiers } = context;
  14894. if (identifiers[id] === undefined) {
  14895. identifiers[id] = 0;
  14896. }
  14897. identifiers[id]++;
  14898. }
  14899. function removeId(id) {
  14900. context.identifiers[id]--;
  14901. }
  14902. return context;
  14903. }
  14904. function transform$1(root, options) {
  14905. const context = createTransformContext(root, options);
  14906. traverseNode(root, context);
  14907. if (options.hoistStatic) {
  14908. hoistStatic(root, context);
  14909. }
  14910. if (!options.ssr) {
  14911. createRootCodegen(root, context);
  14912. }
  14913. // finalize meta information
  14914. root.helpers = new Set([...context.helpers.keys()]);
  14915. root.components = [...context.components];
  14916. root.directives = [...context.directives];
  14917. root.imports = context.imports;
  14918. root.hoists = context.hoists;
  14919. root.temps = context.temps;
  14920. root.cached = context.cached;
  14921. }
  14922. function createRootCodegen(root, context) {
  14923. const { helper } = context;
  14924. const { children } = root;
  14925. if (children.length === 1) {
  14926. const child = children[0];
  14927. // if the single child is an element, turn it into a block.
  14928. if (isSingleElementRoot(root, child) && child.codegenNode) {
  14929. // single element root is never hoisted so codegenNode will never be
  14930. // SimpleExpressionNode
  14931. const codegenNode = child.codegenNode;
  14932. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  14933. makeBlock(codegenNode, context);
  14934. }
  14935. root.codegenNode = codegenNode;
  14936. }
  14937. else {
  14938. // - single <slot/>, IfNode, ForNode: already blocks.
  14939. // - single text node: always patched.
  14940. // root codegen falls through via genNode()
  14941. root.codegenNode = child;
  14942. }
  14943. }
  14944. else if (children.length > 1) {
  14945. // root has multiple nodes - return a fragment block.
  14946. let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
  14947. let patchFlagText = PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
  14948. // check if the fragment actually contains a single valid child with
  14949. // the rest being comments
  14950. if (children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
  14951. patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
  14952. patchFlagText += `, ${PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
  14953. }
  14954. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
  14955. }
  14956. else ;
  14957. }
  14958. function traverseChildren(parent, context) {
  14959. let i = 0;
  14960. const nodeRemoved = () => {
  14961. i--;
  14962. };
  14963. for (; i < parent.children.length; i++) {
  14964. const child = parent.children[i];
  14965. if (isString$2(child))
  14966. continue;
  14967. context.parent = parent;
  14968. context.childIndex = i;
  14969. context.onNodeRemoved = nodeRemoved;
  14970. traverseNode(child, context);
  14971. }
  14972. }
  14973. function traverseNode(node, context) {
  14974. context.currentNode = node;
  14975. // apply transform plugins
  14976. const { nodeTransforms } = context;
  14977. const exitFns = [];
  14978. for (let i = 0; i < nodeTransforms.length; i++) {
  14979. const onExit = nodeTransforms[i](node, context);
  14980. if (onExit) {
  14981. if (isArray$3(onExit)) {
  14982. exitFns.push(...onExit);
  14983. }
  14984. else {
  14985. exitFns.push(onExit);
  14986. }
  14987. }
  14988. if (!context.currentNode) {
  14989. // node was removed
  14990. return;
  14991. }
  14992. else {
  14993. // node may have been replaced
  14994. node = context.currentNode;
  14995. }
  14996. }
  14997. switch (node.type) {
  14998. case 3 /* NodeTypes.COMMENT */:
  14999. if (!context.ssr) {
  15000. // inject import for the Comment symbol, which is needed for creating
  15001. // comment nodes with `createVNode`
  15002. context.helper(CREATE_COMMENT);
  15003. }
  15004. break;
  15005. case 5 /* NodeTypes.INTERPOLATION */:
  15006. // no need to traverse, but we need to inject toString helper
  15007. if (!context.ssr) {
  15008. context.helper(TO_DISPLAY_STRING);
  15009. }
  15010. break;
  15011. // for container types, further traverse downwards
  15012. case 9 /* NodeTypes.IF */:
  15013. for (let i = 0; i < node.branches.length; i++) {
  15014. traverseNode(node.branches[i], context);
  15015. }
  15016. break;
  15017. case 10 /* NodeTypes.IF_BRANCH */:
  15018. case 11 /* NodeTypes.FOR */:
  15019. case 1 /* NodeTypes.ELEMENT */:
  15020. case 0 /* NodeTypes.ROOT */:
  15021. traverseChildren(node, context);
  15022. break;
  15023. }
  15024. // exit transforms
  15025. context.currentNode = node;
  15026. let i = exitFns.length;
  15027. while (i--) {
  15028. exitFns[i]();
  15029. }
  15030. }
  15031. function createStructuralDirectiveTransform(name, fn) {
  15032. const matches = isString$2(name)
  15033. ? (n) => n === name
  15034. : (n) => name.test(n);
  15035. return (node, context) => {
  15036. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  15037. const { props } = node;
  15038. // structural directive transforms are not concerned with slots
  15039. // as they are handled separately in vSlot.ts
  15040. if (node.tagType === 3 /* ElementTypes.TEMPLATE */ && props.some(isVSlot)) {
  15041. return;
  15042. }
  15043. const exitFns = [];
  15044. for (let i = 0; i < props.length; i++) {
  15045. const prop = props[i];
  15046. if (prop.type === 7 /* NodeTypes.DIRECTIVE */ && matches(prop.name)) {
  15047. // structural directives are removed to avoid infinite recursion
  15048. // also we remove them *before* applying so that it can further
  15049. // traverse itself in case it moves the node around
  15050. props.splice(i, 1);
  15051. i--;
  15052. const onExit = fn(node, prop, context);
  15053. if (onExit)
  15054. exitFns.push(onExit);
  15055. }
  15056. }
  15057. return exitFns;
  15058. }
  15059. };
  15060. }
  15061. var sourceMap$2 = {};
  15062. var sourceMapGenerator$1 = {};
  15063. var base64Vlq$1 = {};
  15064. var base64$3 = {};
  15065. /* -*- Mode: js; js-indent-level: 2; -*- */
  15066. /*
  15067. * Copyright 2011 Mozilla Foundation and contributors
  15068. * Licensed under the New BSD license. See LICENSE or:
  15069. * http://opensource.org/licenses/BSD-3-Clause
  15070. */
  15071. var intToCharMap$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  15072. /**
  15073. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  15074. */
  15075. base64$3.encode = function (number) {
  15076. if (0 <= number && number < intToCharMap$1.length) {
  15077. return intToCharMap$1[number];
  15078. }
  15079. throw new TypeError("Must be between 0 and 63: " + number);
  15080. };
  15081. /**
  15082. * Decode a single base 64 character code digit to an integer. Returns -1 on
  15083. * failure.
  15084. */
  15085. base64$3.decode = function (charCode) {
  15086. var bigA = 65; // 'A'
  15087. var bigZ = 90; // 'Z'
  15088. var littleA = 97; // 'a'
  15089. var littleZ = 122; // 'z'
  15090. var zero = 48; // '0'
  15091. var nine = 57; // '9'
  15092. var plus = 43; // '+'
  15093. var slash = 47; // '/'
  15094. var littleOffset = 26;
  15095. var numberOffset = 52;
  15096. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  15097. if (bigA <= charCode && charCode <= bigZ) {
  15098. return (charCode - bigA);
  15099. }
  15100. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  15101. if (littleA <= charCode && charCode <= littleZ) {
  15102. return (charCode - littleA + littleOffset);
  15103. }
  15104. // 52 - 61: 0123456789
  15105. if (zero <= charCode && charCode <= nine) {
  15106. return (charCode - zero + numberOffset);
  15107. }
  15108. // 62: +
  15109. if (charCode == plus) {
  15110. return 62;
  15111. }
  15112. // 63: /
  15113. if (charCode == slash) {
  15114. return 63;
  15115. }
  15116. // Invalid base64 digit.
  15117. return -1;
  15118. };
  15119. /* -*- Mode: js; js-indent-level: 2; -*- */
  15120. /*
  15121. * Copyright 2011 Mozilla Foundation and contributors
  15122. * Licensed under the New BSD license. See LICENSE or:
  15123. * http://opensource.org/licenses/BSD-3-Clause
  15124. *
  15125. * Based on the Base 64 VLQ implementation in Closure Compiler:
  15126. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  15127. *
  15128. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  15129. * Redistribution and use in source and binary forms, with or without
  15130. * modification, are permitted provided that the following conditions are
  15131. * met:
  15132. *
  15133. * * Redistributions of source code must retain the above copyright
  15134. * notice, this list of conditions and the following disclaimer.
  15135. * * Redistributions in binary form must reproduce the above
  15136. * copyright notice, this list of conditions and the following
  15137. * disclaimer in the documentation and/or other materials provided
  15138. * with the distribution.
  15139. * * Neither the name of Google Inc. nor the names of its
  15140. * contributors may be used to endorse or promote products derived
  15141. * from this software without specific prior written permission.
  15142. *
  15143. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  15144. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  15145. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  15146. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  15147. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  15148. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  15149. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  15150. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  15151. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  15152. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  15153. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  15154. */
  15155. var base64$2 = base64$3;
  15156. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  15157. // length quantities we use in the source map spec, the first bit is the sign,
  15158. // the next four bits are the actual value, and the 6th bit is the
  15159. // continuation bit. The continuation bit tells us whether there are more
  15160. // digits in this value following this digit.
  15161. //
  15162. // Continuation
  15163. // | Sign
  15164. // | |
  15165. // V V
  15166. // 101011
  15167. var VLQ_BASE_SHIFT$1 = 5;
  15168. // binary: 100000
  15169. var VLQ_BASE$1 = 1 << VLQ_BASE_SHIFT$1;
  15170. // binary: 011111
  15171. var VLQ_BASE_MASK$1 = VLQ_BASE$1 - 1;
  15172. // binary: 100000
  15173. var VLQ_CONTINUATION_BIT$1 = VLQ_BASE$1;
  15174. /**
  15175. * Converts from a two-complement value to a value where the sign bit is
  15176. * placed in the least significant bit. For example, as decimals:
  15177. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  15178. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  15179. */
  15180. function toVLQSigned$1(aValue) {
  15181. return aValue < 0
  15182. ? ((-aValue) << 1) + 1
  15183. : (aValue << 1) + 0;
  15184. }
  15185. /**
  15186. * Converts to a two-complement value from a value where the sign bit is
  15187. * placed in the least significant bit. For example, as decimals:
  15188. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  15189. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  15190. */
  15191. function fromVLQSigned$1(aValue) {
  15192. var isNegative = (aValue & 1) === 1;
  15193. var shifted = aValue >> 1;
  15194. return isNegative
  15195. ? -shifted
  15196. : shifted;
  15197. }
  15198. /**
  15199. * Returns the base 64 VLQ encoded value.
  15200. */
  15201. base64Vlq$1.encode = function base64VLQ_encode(aValue) {
  15202. var encoded = "";
  15203. var digit;
  15204. var vlq = toVLQSigned$1(aValue);
  15205. do {
  15206. digit = vlq & VLQ_BASE_MASK$1;
  15207. vlq >>>= VLQ_BASE_SHIFT$1;
  15208. if (vlq > 0) {
  15209. // There are still more digits in this value, so we must make sure the
  15210. // continuation bit is marked.
  15211. digit |= VLQ_CONTINUATION_BIT$1;
  15212. }
  15213. encoded += base64$2.encode(digit);
  15214. } while (vlq > 0);
  15215. return encoded;
  15216. };
  15217. /**
  15218. * Decodes the next base 64 VLQ value from the given string and returns the
  15219. * value and the rest of the string via the out parameter.
  15220. */
  15221. base64Vlq$1.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  15222. var strLen = aStr.length;
  15223. var result = 0;
  15224. var shift = 0;
  15225. var continuation, digit;
  15226. do {
  15227. if (aIndex >= strLen) {
  15228. throw new Error("Expected more digits in base 64 VLQ value.");
  15229. }
  15230. digit = base64$2.decode(aStr.charCodeAt(aIndex++));
  15231. if (digit === -1) {
  15232. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  15233. }
  15234. continuation = !!(digit & VLQ_CONTINUATION_BIT$1);
  15235. digit &= VLQ_BASE_MASK$1;
  15236. result = result + (digit << shift);
  15237. shift += VLQ_BASE_SHIFT$1;
  15238. } while (continuation);
  15239. aOutParam.value = fromVLQSigned$1(result);
  15240. aOutParam.rest = aIndex;
  15241. };
  15242. var util$c = {};
  15243. /* -*- Mode: js; js-indent-level: 2; -*- */
  15244. (function (exports) {
  15245. /*
  15246. * Copyright 2011 Mozilla Foundation and contributors
  15247. * Licensed under the New BSD license. See LICENSE or:
  15248. * http://opensource.org/licenses/BSD-3-Clause
  15249. */
  15250. /**
  15251. * This is a helper function for getting values from parameter/options
  15252. * objects.
  15253. *
  15254. * @param args The object we are extracting values from
  15255. * @param name The name of the property we are getting.
  15256. * @param defaultValue An optional value to return if the property is missing
  15257. * from the object. If this is not specified and the property is missing, an
  15258. * error will be thrown.
  15259. */
  15260. function getArg(aArgs, aName, aDefaultValue) {
  15261. if (aName in aArgs) {
  15262. return aArgs[aName];
  15263. } else if (arguments.length === 3) {
  15264. return aDefaultValue;
  15265. } else {
  15266. throw new Error('"' + aName + '" is a required argument.');
  15267. }
  15268. }
  15269. exports.getArg = getArg;
  15270. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  15271. var dataUrlRegexp = /^data:.+\,.+$/;
  15272. function urlParse(aUrl) {
  15273. var match = aUrl.match(urlRegexp);
  15274. if (!match) {
  15275. return null;
  15276. }
  15277. return {
  15278. scheme: match[1],
  15279. auth: match[2],
  15280. host: match[3],
  15281. port: match[4],
  15282. path: match[5]
  15283. };
  15284. }
  15285. exports.urlParse = urlParse;
  15286. function urlGenerate(aParsedUrl) {
  15287. var url = '';
  15288. if (aParsedUrl.scheme) {
  15289. url += aParsedUrl.scheme + ':';
  15290. }
  15291. url += '//';
  15292. if (aParsedUrl.auth) {
  15293. url += aParsedUrl.auth + '@';
  15294. }
  15295. if (aParsedUrl.host) {
  15296. url += aParsedUrl.host;
  15297. }
  15298. if (aParsedUrl.port) {
  15299. url += ":" + aParsedUrl.port;
  15300. }
  15301. if (aParsedUrl.path) {
  15302. url += aParsedUrl.path;
  15303. }
  15304. return url;
  15305. }
  15306. exports.urlGenerate = urlGenerate;
  15307. /**
  15308. * Normalizes a path, or the path portion of a URL:
  15309. *
  15310. * - Replaces consecutive slashes with one slash.
  15311. * - Removes unnecessary '.' parts.
  15312. * - Removes unnecessary '<dir>/..' parts.
  15313. *
  15314. * Based on code in the Node.js 'path' core module.
  15315. *
  15316. * @param aPath The path or url to normalize.
  15317. */
  15318. function normalize(aPath) {
  15319. var path = aPath;
  15320. var url = urlParse(aPath);
  15321. if (url) {
  15322. if (!url.path) {
  15323. return aPath;
  15324. }
  15325. path = url.path;
  15326. }
  15327. var isAbsolute = exports.isAbsolute(path);
  15328. var parts = path.split(/\/+/);
  15329. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  15330. part = parts[i];
  15331. if (part === '.') {
  15332. parts.splice(i, 1);
  15333. } else if (part === '..') {
  15334. up++;
  15335. } else if (up > 0) {
  15336. if (part === '') {
  15337. // The first part is blank if the path is absolute. Trying to go
  15338. // above the root is a no-op. Therefore we can remove all '..' parts
  15339. // directly after the root.
  15340. parts.splice(i + 1, up);
  15341. up = 0;
  15342. } else {
  15343. parts.splice(i, 2);
  15344. up--;
  15345. }
  15346. }
  15347. }
  15348. path = parts.join('/');
  15349. if (path === '') {
  15350. path = isAbsolute ? '/' : '.';
  15351. }
  15352. if (url) {
  15353. url.path = path;
  15354. return urlGenerate(url);
  15355. }
  15356. return path;
  15357. }
  15358. exports.normalize = normalize;
  15359. /**
  15360. * Joins two paths/URLs.
  15361. *
  15362. * @param aRoot The root path or URL.
  15363. * @param aPath The path or URL to be joined with the root.
  15364. *
  15365. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  15366. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  15367. * first.
  15368. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  15369. * is updated with the result and aRoot is returned. Otherwise the result
  15370. * is returned.
  15371. * - If aPath is absolute, the result is aPath.
  15372. * - Otherwise the two paths are joined with a slash.
  15373. * - Joining for example 'http://' and 'www.example.com' is also supported.
  15374. */
  15375. function join(aRoot, aPath) {
  15376. if (aRoot === "") {
  15377. aRoot = ".";
  15378. }
  15379. if (aPath === "") {
  15380. aPath = ".";
  15381. }
  15382. var aPathUrl = urlParse(aPath);
  15383. var aRootUrl = urlParse(aRoot);
  15384. if (aRootUrl) {
  15385. aRoot = aRootUrl.path || '/';
  15386. }
  15387. // `join(foo, '//www.example.org')`
  15388. if (aPathUrl && !aPathUrl.scheme) {
  15389. if (aRootUrl) {
  15390. aPathUrl.scheme = aRootUrl.scheme;
  15391. }
  15392. return urlGenerate(aPathUrl);
  15393. }
  15394. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  15395. return aPath;
  15396. }
  15397. // `join('http://', 'www.example.com')`
  15398. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  15399. aRootUrl.host = aPath;
  15400. return urlGenerate(aRootUrl);
  15401. }
  15402. var joined = aPath.charAt(0) === '/'
  15403. ? aPath
  15404. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  15405. if (aRootUrl) {
  15406. aRootUrl.path = joined;
  15407. return urlGenerate(aRootUrl);
  15408. }
  15409. return joined;
  15410. }
  15411. exports.join = join;
  15412. exports.isAbsolute = function (aPath) {
  15413. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  15414. };
  15415. /**
  15416. * Make a path relative to a URL or another path.
  15417. *
  15418. * @param aRoot The root path or URL.
  15419. * @param aPath The path or URL to be made relative to aRoot.
  15420. */
  15421. function relative(aRoot, aPath) {
  15422. if (aRoot === "") {
  15423. aRoot = ".";
  15424. }
  15425. aRoot = aRoot.replace(/\/$/, '');
  15426. // It is possible for the path to be above the root. In this case, simply
  15427. // checking whether the root is a prefix of the path won't work. Instead, we
  15428. // need to remove components from the root one by one, until either we find
  15429. // a prefix that fits, or we run out of components to remove.
  15430. var level = 0;
  15431. while (aPath.indexOf(aRoot + '/') !== 0) {
  15432. var index = aRoot.lastIndexOf("/");
  15433. if (index < 0) {
  15434. return aPath;
  15435. }
  15436. // If the only part of the root that is left is the scheme (i.e. http://,
  15437. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  15438. // have exhausted all components, so the path is not relative to the root.
  15439. aRoot = aRoot.slice(0, index);
  15440. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  15441. return aPath;
  15442. }
  15443. ++level;
  15444. }
  15445. // Make sure we add a "../" for each component we removed from the root.
  15446. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  15447. }
  15448. exports.relative = relative;
  15449. var supportsNullProto = (function () {
  15450. var obj = Object.create(null);
  15451. return !('__proto__' in obj);
  15452. }());
  15453. function identity (s) {
  15454. return s;
  15455. }
  15456. /**
  15457. * Because behavior goes wacky when you set `__proto__` on objects, we
  15458. * have to prefix all the strings in our set with an arbitrary character.
  15459. *
  15460. * See https://github.com/mozilla/source-map/pull/31 and
  15461. * https://github.com/mozilla/source-map/issues/30
  15462. *
  15463. * @param String aStr
  15464. */
  15465. function toSetString(aStr) {
  15466. if (isProtoString(aStr)) {
  15467. return '$' + aStr;
  15468. }
  15469. return aStr;
  15470. }
  15471. exports.toSetString = supportsNullProto ? identity : toSetString;
  15472. function fromSetString(aStr) {
  15473. if (isProtoString(aStr)) {
  15474. return aStr.slice(1);
  15475. }
  15476. return aStr;
  15477. }
  15478. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  15479. function isProtoString(s) {
  15480. if (!s) {
  15481. return false;
  15482. }
  15483. var length = s.length;
  15484. if (length < 9 /* "__proto__".length */) {
  15485. return false;
  15486. }
  15487. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  15488. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  15489. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  15490. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  15491. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  15492. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  15493. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  15494. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  15495. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  15496. return false;
  15497. }
  15498. for (var i = length - 10; i >= 0; i--) {
  15499. if (s.charCodeAt(i) !== 36 /* '$' */) {
  15500. return false;
  15501. }
  15502. }
  15503. return true;
  15504. }
  15505. /**
  15506. * Comparator between two mappings where the original positions are compared.
  15507. *
  15508. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  15509. * mappings with the same original source/line/column, but different generated
  15510. * line and column the same. Useful when searching for a mapping with a
  15511. * stubbed out mapping.
  15512. */
  15513. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  15514. var cmp = strcmp(mappingA.source, mappingB.source);
  15515. if (cmp !== 0) {
  15516. return cmp;
  15517. }
  15518. cmp = mappingA.originalLine - mappingB.originalLine;
  15519. if (cmp !== 0) {
  15520. return cmp;
  15521. }
  15522. cmp = mappingA.originalColumn - mappingB.originalColumn;
  15523. if (cmp !== 0 || onlyCompareOriginal) {
  15524. return cmp;
  15525. }
  15526. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  15527. if (cmp !== 0) {
  15528. return cmp;
  15529. }
  15530. cmp = mappingA.generatedLine - mappingB.generatedLine;
  15531. if (cmp !== 0) {
  15532. return cmp;
  15533. }
  15534. return strcmp(mappingA.name, mappingB.name);
  15535. }
  15536. exports.compareByOriginalPositions = compareByOriginalPositions;
  15537. /**
  15538. * Comparator between two mappings with deflated source and name indices where
  15539. * the generated positions are compared.
  15540. *
  15541. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  15542. * mappings with the same generated line and column, but different
  15543. * source/name/original line and column the same. Useful when searching for a
  15544. * mapping with a stubbed out mapping.
  15545. */
  15546. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  15547. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  15548. if (cmp !== 0) {
  15549. return cmp;
  15550. }
  15551. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  15552. if (cmp !== 0 || onlyCompareGenerated) {
  15553. return cmp;
  15554. }
  15555. cmp = strcmp(mappingA.source, mappingB.source);
  15556. if (cmp !== 0) {
  15557. return cmp;
  15558. }
  15559. cmp = mappingA.originalLine - mappingB.originalLine;
  15560. if (cmp !== 0) {
  15561. return cmp;
  15562. }
  15563. cmp = mappingA.originalColumn - mappingB.originalColumn;
  15564. if (cmp !== 0) {
  15565. return cmp;
  15566. }
  15567. return strcmp(mappingA.name, mappingB.name);
  15568. }
  15569. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  15570. function strcmp(aStr1, aStr2) {
  15571. if (aStr1 === aStr2) {
  15572. return 0;
  15573. }
  15574. if (aStr1 === null) {
  15575. return 1; // aStr2 !== null
  15576. }
  15577. if (aStr2 === null) {
  15578. return -1; // aStr1 !== null
  15579. }
  15580. if (aStr1 > aStr2) {
  15581. return 1;
  15582. }
  15583. return -1;
  15584. }
  15585. /**
  15586. * Comparator between two mappings with inflated source and name strings where
  15587. * the generated positions are compared.
  15588. */
  15589. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  15590. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  15591. if (cmp !== 0) {
  15592. return cmp;
  15593. }
  15594. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  15595. if (cmp !== 0) {
  15596. return cmp;
  15597. }
  15598. cmp = strcmp(mappingA.source, mappingB.source);
  15599. if (cmp !== 0) {
  15600. return cmp;
  15601. }
  15602. cmp = mappingA.originalLine - mappingB.originalLine;
  15603. if (cmp !== 0) {
  15604. return cmp;
  15605. }
  15606. cmp = mappingA.originalColumn - mappingB.originalColumn;
  15607. if (cmp !== 0) {
  15608. return cmp;
  15609. }
  15610. return strcmp(mappingA.name, mappingB.name);
  15611. }
  15612. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  15613. /**
  15614. * Strip any JSON XSSI avoidance prefix from the string (as documented
  15615. * in the source maps specification), and then parse the string as
  15616. * JSON.
  15617. */
  15618. function parseSourceMapInput(str) {
  15619. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  15620. }
  15621. exports.parseSourceMapInput = parseSourceMapInput;
  15622. /**
  15623. * Compute the URL of a source given the the source root, the source's
  15624. * URL, and the source map's URL.
  15625. */
  15626. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  15627. sourceURL = sourceURL || '';
  15628. if (sourceRoot) {
  15629. // This follows what Chrome does.
  15630. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  15631. sourceRoot += '/';
  15632. }
  15633. // The spec says:
  15634. // Line 4: An optional source root, useful for relocating source
  15635. // files on a server or removing repeated values in the
  15636. // “sources” entry. This value is prepended to the individual
  15637. // entries in the “source” field.
  15638. sourceURL = sourceRoot + sourceURL;
  15639. }
  15640. // Historically, SourceMapConsumer did not take the sourceMapURL as
  15641. // a parameter. This mode is still somewhat supported, which is why
  15642. // this code block is conditional. However, it's preferable to pass
  15643. // the source map URL to SourceMapConsumer, so that this function
  15644. // can implement the source URL resolution algorithm as outlined in
  15645. // the spec. This block is basically the equivalent of:
  15646. // new URL(sourceURL, sourceMapURL).toString()
  15647. // ... except it avoids using URL, which wasn't available in the
  15648. // older releases of node still supported by this library.
  15649. //
  15650. // The spec says:
  15651. // If the sources are not absolute URLs after prepending of the
  15652. // “sourceRoot”, the sources are resolved relative to the
  15653. // SourceMap (like resolving script src in a html document).
  15654. if (sourceMapURL) {
  15655. var parsed = urlParse(sourceMapURL);
  15656. if (!parsed) {
  15657. throw new Error("sourceMapURL could not be parsed");
  15658. }
  15659. if (parsed.path) {
  15660. // Strip the last path component, but keep the "/".
  15661. var index = parsed.path.lastIndexOf('/');
  15662. if (index >= 0) {
  15663. parsed.path = parsed.path.substring(0, index + 1);
  15664. }
  15665. }
  15666. sourceURL = join(urlGenerate(parsed), sourceURL);
  15667. }
  15668. return normalize(sourceURL);
  15669. }
  15670. exports.computeSourceURL = computeSourceURL;
  15671. } (util$c));
  15672. var arraySet$1 = {};
  15673. /* -*- Mode: js; js-indent-level: 2; -*- */
  15674. /*
  15675. * Copyright 2011 Mozilla Foundation and contributors
  15676. * Licensed under the New BSD license. See LICENSE or:
  15677. * http://opensource.org/licenses/BSD-3-Clause
  15678. */
  15679. var util$b = util$c;
  15680. var has$1 = Object.prototype.hasOwnProperty;
  15681. var hasNativeMap$1 = typeof Map !== "undefined";
  15682. /**
  15683. * A data structure which is a combination of an array and a set. Adding a new
  15684. * member is O(1), testing for membership is O(1), and finding the index of an
  15685. * element is O(1). Removing elements from the set is not supported. Only
  15686. * strings are supported for membership.
  15687. */
  15688. function ArraySet$5() {
  15689. this._array = [];
  15690. this._set = hasNativeMap$1 ? new Map() : Object.create(null);
  15691. }
  15692. /**
  15693. * Static method for creating ArraySet instances from an existing array.
  15694. */
  15695. ArraySet$5.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  15696. var set = new ArraySet$5();
  15697. for (var i = 0, len = aArray.length; i < len; i++) {
  15698. set.add(aArray[i], aAllowDuplicates);
  15699. }
  15700. return set;
  15701. };
  15702. /**
  15703. * Return how many unique items are in this ArraySet. If duplicates have been
  15704. * added, than those do not count towards the size.
  15705. *
  15706. * @returns Number
  15707. */
  15708. ArraySet$5.prototype.size = function ArraySet_size() {
  15709. return hasNativeMap$1 ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  15710. };
  15711. /**
  15712. * Add the given string to this set.
  15713. *
  15714. * @param String aStr
  15715. */
  15716. ArraySet$5.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  15717. var sStr = hasNativeMap$1 ? aStr : util$b.toSetString(aStr);
  15718. var isDuplicate = hasNativeMap$1 ? this.has(aStr) : has$1.call(this._set, sStr);
  15719. var idx = this._array.length;
  15720. if (!isDuplicate || aAllowDuplicates) {
  15721. this._array.push(aStr);
  15722. }
  15723. if (!isDuplicate) {
  15724. if (hasNativeMap$1) {
  15725. this._set.set(aStr, idx);
  15726. } else {
  15727. this._set[sStr] = idx;
  15728. }
  15729. }
  15730. };
  15731. /**
  15732. * Is the given string a member of this set?
  15733. *
  15734. * @param String aStr
  15735. */
  15736. ArraySet$5.prototype.has = function ArraySet_has(aStr) {
  15737. if (hasNativeMap$1) {
  15738. return this._set.has(aStr);
  15739. } else {
  15740. var sStr = util$b.toSetString(aStr);
  15741. return has$1.call(this._set, sStr);
  15742. }
  15743. };
  15744. /**
  15745. * What is the index of the given string in the array?
  15746. *
  15747. * @param String aStr
  15748. */
  15749. ArraySet$5.prototype.indexOf = function ArraySet_indexOf(aStr) {
  15750. if (hasNativeMap$1) {
  15751. var idx = this._set.get(aStr);
  15752. if (idx >= 0) {
  15753. return idx;
  15754. }
  15755. } else {
  15756. var sStr = util$b.toSetString(aStr);
  15757. if (has$1.call(this._set, sStr)) {
  15758. return this._set[sStr];
  15759. }
  15760. }
  15761. throw new Error('"' + aStr + '" is not in the set.');
  15762. };
  15763. /**
  15764. * What is the element at the given index?
  15765. *
  15766. * @param Number aIdx
  15767. */
  15768. ArraySet$5.prototype.at = function ArraySet_at(aIdx) {
  15769. if (aIdx >= 0 && aIdx < this._array.length) {
  15770. return this._array[aIdx];
  15771. }
  15772. throw new Error('No element indexed by ' + aIdx);
  15773. };
  15774. /**
  15775. * Returns the array representation of this set (which has the proper indices
  15776. * indicated by indexOf). Note that this is a copy of the internal array used
  15777. * for storing the members so that no one can mess with internal state.
  15778. */
  15779. ArraySet$5.prototype.toArray = function ArraySet_toArray() {
  15780. return this._array.slice();
  15781. };
  15782. arraySet$1.ArraySet = ArraySet$5;
  15783. var mappingList$1 = {};
  15784. /* -*- Mode: js; js-indent-level: 2; -*- */
  15785. /*
  15786. * Copyright 2014 Mozilla Foundation and contributors
  15787. * Licensed under the New BSD license. See LICENSE or:
  15788. * http://opensource.org/licenses/BSD-3-Clause
  15789. */
  15790. var util$a = util$c;
  15791. /**
  15792. * Determine whether mappingB is after mappingA with respect to generated
  15793. * position.
  15794. */
  15795. function generatedPositionAfter$1(mappingA, mappingB) {
  15796. // Optimized for most common case
  15797. var lineA = mappingA.generatedLine;
  15798. var lineB = mappingB.generatedLine;
  15799. var columnA = mappingA.generatedColumn;
  15800. var columnB = mappingB.generatedColumn;
  15801. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  15802. util$a.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  15803. }
  15804. /**
  15805. * A data structure to provide a sorted view of accumulated mappings in a
  15806. * performance conscious manner. It trades a neglibable overhead in general
  15807. * case for a large speedup in case of mappings being added in order.
  15808. */
  15809. function MappingList$3() {
  15810. this._array = [];
  15811. this._sorted = true;
  15812. // Serves as infimum
  15813. this._last = {generatedLine: -1, generatedColumn: 0};
  15814. }
  15815. /**
  15816. * Iterate through internal items. This method takes the same arguments that
  15817. * `Array.prototype.forEach` takes.
  15818. *
  15819. * NOTE: The order of the mappings is NOT guaranteed.
  15820. */
  15821. MappingList$3.prototype.unsortedForEach =
  15822. function MappingList_forEach(aCallback, aThisArg) {
  15823. this._array.forEach(aCallback, aThisArg);
  15824. };
  15825. /**
  15826. * Add the given source mapping.
  15827. *
  15828. * @param Object aMapping
  15829. */
  15830. MappingList$3.prototype.add = function MappingList_add(aMapping) {
  15831. if (generatedPositionAfter$1(this._last, aMapping)) {
  15832. this._last = aMapping;
  15833. this._array.push(aMapping);
  15834. } else {
  15835. this._sorted = false;
  15836. this._array.push(aMapping);
  15837. }
  15838. };
  15839. /**
  15840. * Returns the flat, sorted array of mappings. The mappings are sorted by
  15841. * generated position.
  15842. *
  15843. * WARNING: This method returns internal data without copying, for
  15844. * performance. The return value must NOT be mutated, and should be treated as
  15845. * an immutable borrow. If you want to take ownership, you must make your own
  15846. * copy.
  15847. */
  15848. MappingList$3.prototype.toArray = function MappingList_toArray() {
  15849. if (!this._sorted) {
  15850. this._array.sort(util$a.compareByGeneratedPositionsInflated);
  15851. this._sorted = true;
  15852. }
  15853. return this._array;
  15854. };
  15855. mappingList$1.MappingList = MappingList$3;
  15856. /* -*- Mode: js; js-indent-level: 2; -*- */
  15857. /*
  15858. * Copyright 2011 Mozilla Foundation and contributors
  15859. * Licensed under the New BSD license. See LICENSE or:
  15860. * http://opensource.org/licenses/BSD-3-Clause
  15861. */
  15862. var base64VLQ$3 = base64Vlq$1;
  15863. var util$9 = util$c;
  15864. var ArraySet$4 = arraySet$1.ArraySet;
  15865. var MappingList$2 = mappingList$1.MappingList;
  15866. /**
  15867. * An instance of the SourceMapGenerator represents a source map which is
  15868. * being built incrementally. You may pass an object with the following
  15869. * properties:
  15870. *
  15871. * - file: The filename of the generated source.
  15872. * - sourceRoot: A root for all relative URLs in this source map.
  15873. */
  15874. function SourceMapGenerator$8(aArgs) {
  15875. if (!aArgs) {
  15876. aArgs = {};
  15877. }
  15878. this._file = util$9.getArg(aArgs, 'file', null);
  15879. this._sourceRoot = util$9.getArg(aArgs, 'sourceRoot', null);
  15880. this._skipValidation = util$9.getArg(aArgs, 'skipValidation', false);
  15881. this._sources = new ArraySet$4();
  15882. this._names = new ArraySet$4();
  15883. this._mappings = new MappingList$2();
  15884. this._sourcesContents = null;
  15885. }
  15886. SourceMapGenerator$8.prototype._version = 3;
  15887. /**
  15888. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  15889. *
  15890. * @param aSourceMapConsumer The SourceMap.
  15891. */
  15892. SourceMapGenerator$8.fromSourceMap =
  15893. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  15894. var sourceRoot = aSourceMapConsumer.sourceRoot;
  15895. var generator = new SourceMapGenerator$8({
  15896. file: aSourceMapConsumer.file,
  15897. sourceRoot: sourceRoot
  15898. });
  15899. aSourceMapConsumer.eachMapping(function (mapping) {
  15900. var newMapping = {
  15901. generated: {
  15902. line: mapping.generatedLine,
  15903. column: mapping.generatedColumn
  15904. }
  15905. };
  15906. if (mapping.source != null) {
  15907. newMapping.source = mapping.source;
  15908. if (sourceRoot != null) {
  15909. newMapping.source = util$9.relative(sourceRoot, newMapping.source);
  15910. }
  15911. newMapping.original = {
  15912. line: mapping.originalLine,
  15913. column: mapping.originalColumn
  15914. };
  15915. if (mapping.name != null) {
  15916. newMapping.name = mapping.name;
  15917. }
  15918. }
  15919. generator.addMapping(newMapping);
  15920. });
  15921. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  15922. var sourceRelative = sourceFile;
  15923. if (sourceRoot !== null) {
  15924. sourceRelative = util$9.relative(sourceRoot, sourceFile);
  15925. }
  15926. if (!generator._sources.has(sourceRelative)) {
  15927. generator._sources.add(sourceRelative);
  15928. }
  15929. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  15930. if (content != null) {
  15931. generator.setSourceContent(sourceFile, content);
  15932. }
  15933. });
  15934. return generator;
  15935. };
  15936. /**
  15937. * Add a single mapping from original source line and column to the generated
  15938. * source's line and column for this source map being created. The mapping
  15939. * object should have the following properties:
  15940. *
  15941. * - generated: An object with the generated line and column positions.
  15942. * - original: An object with the original line and column positions.
  15943. * - source: The original source file (relative to the sourceRoot).
  15944. * - name: An optional original token name for this mapping.
  15945. */
  15946. SourceMapGenerator$8.prototype.addMapping =
  15947. function SourceMapGenerator_addMapping(aArgs) {
  15948. var generated = util$9.getArg(aArgs, 'generated');
  15949. var original = util$9.getArg(aArgs, 'original', null);
  15950. var source = util$9.getArg(aArgs, 'source', null);
  15951. var name = util$9.getArg(aArgs, 'name', null);
  15952. if (!this._skipValidation) {
  15953. this._validateMapping(generated, original, source, name);
  15954. }
  15955. if (source != null) {
  15956. source = String(source);
  15957. if (!this._sources.has(source)) {
  15958. this._sources.add(source);
  15959. }
  15960. }
  15961. if (name != null) {
  15962. name = String(name);
  15963. if (!this._names.has(name)) {
  15964. this._names.add(name);
  15965. }
  15966. }
  15967. this._mappings.add({
  15968. generatedLine: generated.line,
  15969. generatedColumn: generated.column,
  15970. originalLine: original != null && original.line,
  15971. originalColumn: original != null && original.column,
  15972. source: source,
  15973. name: name
  15974. });
  15975. };
  15976. /**
  15977. * Set the source content for a source file.
  15978. */
  15979. SourceMapGenerator$8.prototype.setSourceContent =
  15980. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  15981. var source = aSourceFile;
  15982. if (this._sourceRoot != null) {
  15983. source = util$9.relative(this._sourceRoot, source);
  15984. }
  15985. if (aSourceContent != null) {
  15986. // Add the source content to the _sourcesContents map.
  15987. // Create a new _sourcesContents map if the property is null.
  15988. if (!this._sourcesContents) {
  15989. this._sourcesContents = Object.create(null);
  15990. }
  15991. this._sourcesContents[util$9.toSetString(source)] = aSourceContent;
  15992. } else if (this._sourcesContents) {
  15993. // Remove the source file from the _sourcesContents map.
  15994. // If the _sourcesContents map is empty, set the property to null.
  15995. delete this._sourcesContents[util$9.toSetString(source)];
  15996. if (Object.keys(this._sourcesContents).length === 0) {
  15997. this._sourcesContents = null;
  15998. }
  15999. }
  16000. };
  16001. /**
  16002. * Applies the mappings of a sub-source-map for a specific source file to the
  16003. * source map being generated. Each mapping to the supplied source file is
  16004. * rewritten using the supplied source map. Note: The resolution for the
  16005. * resulting mappings is the minimium of this map and the supplied map.
  16006. *
  16007. * @param aSourceMapConsumer The source map to be applied.
  16008. * @param aSourceFile Optional. The filename of the source file.
  16009. * If omitted, SourceMapConsumer's file property will be used.
  16010. * @param aSourceMapPath Optional. The dirname of the path to the source map
  16011. * to be applied. If relative, it is relative to the SourceMapConsumer.
  16012. * This parameter is needed when the two source maps aren't in the same
  16013. * directory, and the source map to be applied contains relative source
  16014. * paths. If so, those relative source paths need to be rewritten
  16015. * relative to the SourceMapGenerator.
  16016. */
  16017. SourceMapGenerator$8.prototype.applySourceMap =
  16018. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  16019. var sourceFile = aSourceFile;
  16020. // If aSourceFile is omitted, we will use the file property of the SourceMap
  16021. if (aSourceFile == null) {
  16022. if (aSourceMapConsumer.file == null) {
  16023. throw new Error(
  16024. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  16025. 'or the source map\'s "file" property. Both were omitted.'
  16026. );
  16027. }
  16028. sourceFile = aSourceMapConsumer.file;
  16029. }
  16030. var sourceRoot = this._sourceRoot;
  16031. // Make "sourceFile" relative if an absolute Url is passed.
  16032. if (sourceRoot != null) {
  16033. sourceFile = util$9.relative(sourceRoot, sourceFile);
  16034. }
  16035. // Applying the SourceMap can add and remove items from the sources and
  16036. // the names array.
  16037. var newSources = new ArraySet$4();
  16038. var newNames = new ArraySet$4();
  16039. // Find mappings for the "sourceFile"
  16040. this._mappings.unsortedForEach(function (mapping) {
  16041. if (mapping.source === sourceFile && mapping.originalLine != null) {
  16042. // Check if it can be mapped by the source map, then update the mapping.
  16043. var original = aSourceMapConsumer.originalPositionFor({
  16044. line: mapping.originalLine,
  16045. column: mapping.originalColumn
  16046. });
  16047. if (original.source != null) {
  16048. // Copy mapping
  16049. mapping.source = original.source;
  16050. if (aSourceMapPath != null) {
  16051. mapping.source = util$9.join(aSourceMapPath, mapping.source);
  16052. }
  16053. if (sourceRoot != null) {
  16054. mapping.source = util$9.relative(sourceRoot, mapping.source);
  16055. }
  16056. mapping.originalLine = original.line;
  16057. mapping.originalColumn = original.column;
  16058. if (original.name != null) {
  16059. mapping.name = original.name;
  16060. }
  16061. }
  16062. }
  16063. var source = mapping.source;
  16064. if (source != null && !newSources.has(source)) {
  16065. newSources.add(source);
  16066. }
  16067. var name = mapping.name;
  16068. if (name != null && !newNames.has(name)) {
  16069. newNames.add(name);
  16070. }
  16071. }, this);
  16072. this._sources = newSources;
  16073. this._names = newNames;
  16074. // Copy sourcesContents of applied map.
  16075. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  16076. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  16077. if (content != null) {
  16078. if (aSourceMapPath != null) {
  16079. sourceFile = util$9.join(aSourceMapPath, sourceFile);
  16080. }
  16081. if (sourceRoot != null) {
  16082. sourceFile = util$9.relative(sourceRoot, sourceFile);
  16083. }
  16084. this.setSourceContent(sourceFile, content);
  16085. }
  16086. }, this);
  16087. };
  16088. /**
  16089. * A mapping can have one of the three levels of data:
  16090. *
  16091. * 1. Just the generated position.
  16092. * 2. The Generated position, original position, and original source.
  16093. * 3. Generated and original position, original source, as well as a name
  16094. * token.
  16095. *
  16096. * To maintain consistency, we validate that any new mapping being added falls
  16097. * in to one of these categories.
  16098. */
  16099. SourceMapGenerator$8.prototype._validateMapping =
  16100. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  16101. aName) {
  16102. // When aOriginal is truthy but has empty values for .line and .column,
  16103. // it is most likely a programmer error. In this case we throw a very
  16104. // specific error message to try to guide them the right way.
  16105. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  16106. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  16107. throw new Error(
  16108. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  16109. 'the original mapping entirely and only map the generated position. If so, pass ' +
  16110. 'null for the original mapping instead of an object with empty or null values.'
  16111. );
  16112. }
  16113. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  16114. && aGenerated.line > 0 && aGenerated.column >= 0
  16115. && !aOriginal && !aSource && !aName) {
  16116. // Case 1.
  16117. return;
  16118. }
  16119. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  16120. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  16121. && aGenerated.line > 0 && aGenerated.column >= 0
  16122. && aOriginal.line > 0 && aOriginal.column >= 0
  16123. && aSource) {
  16124. // Cases 2 and 3.
  16125. return;
  16126. }
  16127. else {
  16128. throw new Error('Invalid mapping: ' + JSON.stringify({
  16129. generated: aGenerated,
  16130. source: aSource,
  16131. original: aOriginal,
  16132. name: aName
  16133. }));
  16134. }
  16135. };
  16136. /**
  16137. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  16138. * specified by the source map format.
  16139. */
  16140. SourceMapGenerator$8.prototype._serializeMappings =
  16141. function SourceMapGenerator_serializeMappings() {
  16142. var previousGeneratedColumn = 0;
  16143. var previousGeneratedLine = 1;
  16144. var previousOriginalColumn = 0;
  16145. var previousOriginalLine = 0;
  16146. var previousName = 0;
  16147. var previousSource = 0;
  16148. var result = '';
  16149. var next;
  16150. var mapping;
  16151. var nameIdx;
  16152. var sourceIdx;
  16153. var mappings = this._mappings.toArray();
  16154. for (var i = 0, len = mappings.length; i < len; i++) {
  16155. mapping = mappings[i];
  16156. next = '';
  16157. if (mapping.generatedLine !== previousGeneratedLine) {
  16158. previousGeneratedColumn = 0;
  16159. while (mapping.generatedLine !== previousGeneratedLine) {
  16160. next += ';';
  16161. previousGeneratedLine++;
  16162. }
  16163. }
  16164. else {
  16165. if (i > 0) {
  16166. if (!util$9.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  16167. continue;
  16168. }
  16169. next += ',';
  16170. }
  16171. }
  16172. next += base64VLQ$3.encode(mapping.generatedColumn
  16173. - previousGeneratedColumn);
  16174. previousGeneratedColumn = mapping.generatedColumn;
  16175. if (mapping.source != null) {
  16176. sourceIdx = this._sources.indexOf(mapping.source);
  16177. next += base64VLQ$3.encode(sourceIdx - previousSource);
  16178. previousSource = sourceIdx;
  16179. // lines are stored 0-based in SourceMap spec version 3
  16180. next += base64VLQ$3.encode(mapping.originalLine - 1
  16181. - previousOriginalLine);
  16182. previousOriginalLine = mapping.originalLine - 1;
  16183. next += base64VLQ$3.encode(mapping.originalColumn
  16184. - previousOriginalColumn);
  16185. previousOriginalColumn = mapping.originalColumn;
  16186. if (mapping.name != null) {
  16187. nameIdx = this._names.indexOf(mapping.name);
  16188. next += base64VLQ$3.encode(nameIdx - previousName);
  16189. previousName = nameIdx;
  16190. }
  16191. }
  16192. result += next;
  16193. }
  16194. return result;
  16195. };
  16196. SourceMapGenerator$8.prototype._generateSourcesContent =
  16197. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  16198. return aSources.map(function (source) {
  16199. if (!this._sourcesContents) {
  16200. return null;
  16201. }
  16202. if (aSourceRoot != null) {
  16203. source = util$9.relative(aSourceRoot, source);
  16204. }
  16205. var key = util$9.toSetString(source);
  16206. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  16207. ? this._sourcesContents[key]
  16208. : null;
  16209. }, this);
  16210. };
  16211. /**
  16212. * Externalize the source map.
  16213. */
  16214. SourceMapGenerator$8.prototype.toJSON =
  16215. function SourceMapGenerator_toJSON() {
  16216. var map = {
  16217. version: this._version,
  16218. sources: this._sources.toArray(),
  16219. names: this._names.toArray(),
  16220. mappings: this._serializeMappings()
  16221. };
  16222. if (this._file != null) {
  16223. map.file = this._file;
  16224. }
  16225. if (this._sourceRoot != null) {
  16226. map.sourceRoot = this._sourceRoot;
  16227. }
  16228. if (this._sourcesContents) {
  16229. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  16230. }
  16231. return map;
  16232. };
  16233. /**
  16234. * Render the source map being generated to a string.
  16235. */
  16236. SourceMapGenerator$8.prototype.toString =
  16237. function SourceMapGenerator_toString() {
  16238. return JSON.stringify(this.toJSON());
  16239. };
  16240. sourceMapGenerator$1.SourceMapGenerator = SourceMapGenerator$8;
  16241. var sourceMapConsumer$1 = {};
  16242. var binarySearch$3 = {};
  16243. /* -*- Mode: js; js-indent-level: 2; -*- */
  16244. (function (exports) {
  16245. /*
  16246. * Copyright 2011 Mozilla Foundation and contributors
  16247. * Licensed under the New BSD license. See LICENSE or:
  16248. * http://opensource.org/licenses/BSD-3-Clause
  16249. */
  16250. exports.GREATEST_LOWER_BOUND = 1;
  16251. exports.LEAST_UPPER_BOUND = 2;
  16252. /**
  16253. * Recursive implementation of binary search.
  16254. *
  16255. * @param aLow Indices here and lower do not contain the needle.
  16256. * @param aHigh Indices here and higher do not contain the needle.
  16257. * @param aNeedle The element being searched for.
  16258. * @param aHaystack The non-empty array being searched.
  16259. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  16260. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  16261. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  16262. * closest element that is smaller than or greater than the one we are
  16263. * searching for, respectively, if the exact element cannot be found.
  16264. */
  16265. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  16266. // This function terminates when one of the following is true:
  16267. //
  16268. // 1. We find the exact element we are looking for.
  16269. //
  16270. // 2. We did not find the exact element, but we can return the index of
  16271. // the next-closest element.
  16272. //
  16273. // 3. We did not find the exact element, and there is no next-closest
  16274. // element than the one we are searching for, so we return -1.
  16275. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  16276. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  16277. if (cmp === 0) {
  16278. // Found the element we are looking for.
  16279. return mid;
  16280. }
  16281. else if (cmp > 0) {
  16282. // Our needle is greater than aHaystack[mid].
  16283. if (aHigh - mid > 1) {
  16284. // The element is in the upper half.
  16285. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  16286. }
  16287. // The exact needle element was not found in this haystack. Determine if
  16288. // we are in termination case (3) or (2) and return the appropriate thing.
  16289. if (aBias == exports.LEAST_UPPER_BOUND) {
  16290. return aHigh < aHaystack.length ? aHigh : -1;
  16291. } else {
  16292. return mid;
  16293. }
  16294. }
  16295. else {
  16296. // Our needle is less than aHaystack[mid].
  16297. if (mid - aLow > 1) {
  16298. // The element is in the lower half.
  16299. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  16300. }
  16301. // we are in termination case (3) or (2) and return the appropriate thing.
  16302. if (aBias == exports.LEAST_UPPER_BOUND) {
  16303. return mid;
  16304. } else {
  16305. return aLow < 0 ? -1 : aLow;
  16306. }
  16307. }
  16308. }
  16309. /**
  16310. * This is an implementation of binary search which will always try and return
  16311. * the index of the closest element if there is no exact hit. This is because
  16312. * mappings between original and generated line/col pairs are single points,
  16313. * and there is an implicit region between each of them, so a miss just means
  16314. * that you aren't on the very start of a region.
  16315. *
  16316. * @param aNeedle The element you are looking for.
  16317. * @param aHaystack The array that is being searched.
  16318. * @param aCompare A function which takes the needle and an element in the
  16319. * array and returns -1, 0, or 1 depending on whether the needle is less
  16320. * than, equal to, or greater than the element, respectively.
  16321. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  16322. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  16323. * closest element that is smaller than or greater than the one we are
  16324. * searching for, respectively, if the exact element cannot be found.
  16325. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  16326. */
  16327. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  16328. if (aHaystack.length === 0) {
  16329. return -1;
  16330. }
  16331. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  16332. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  16333. if (index < 0) {
  16334. return -1;
  16335. }
  16336. // We have found either the exact element, or the next-closest element than
  16337. // the one we are searching for. However, there may be more than one such
  16338. // element. Make sure we always return the smallest of these.
  16339. while (index - 1 >= 0) {
  16340. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  16341. break;
  16342. }
  16343. --index;
  16344. }
  16345. return index;
  16346. };
  16347. } (binarySearch$3));
  16348. var quickSort$3 = {};
  16349. /* -*- Mode: js; js-indent-level: 2; -*- */
  16350. /*
  16351. * Copyright 2011 Mozilla Foundation and contributors
  16352. * Licensed under the New BSD license. See LICENSE or:
  16353. * http://opensource.org/licenses/BSD-3-Clause
  16354. */
  16355. // It turns out that some (most?) JavaScript engines don't self-host
  16356. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  16357. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  16358. // custom comparator function, calling back and forth between the VM's C++ and
  16359. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  16360. // worse generated code for the comparator function than would be optimal. In
  16361. // fact, when sorting with a comparator, these costs outweigh the benefits of
  16362. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  16363. // a ~3500ms mean speed-up in `bench/bench.html`.
  16364. /**
  16365. * Swap the elements indexed by `x` and `y` in the array `ary`.
  16366. *
  16367. * @param {Array} ary
  16368. * The array.
  16369. * @param {Number} x
  16370. * The index of the first item.
  16371. * @param {Number} y
  16372. * The index of the second item.
  16373. */
  16374. function swap$1(ary, x, y) {
  16375. var temp = ary[x];
  16376. ary[x] = ary[y];
  16377. ary[y] = temp;
  16378. }
  16379. /**
  16380. * Returns a random integer within the range `low .. high` inclusive.
  16381. *
  16382. * @param {Number} low
  16383. * The lower bound on the range.
  16384. * @param {Number} high
  16385. * The upper bound on the range.
  16386. */
  16387. function randomIntInRange(low, high) {
  16388. return Math.round(low + (Math.random() * (high - low)));
  16389. }
  16390. /**
  16391. * The Quick Sort algorithm.
  16392. *
  16393. * @param {Array} ary
  16394. * An array to sort.
  16395. * @param {function} comparator
  16396. * Function to use to compare two items.
  16397. * @param {Number} p
  16398. * Start index of the array
  16399. * @param {Number} r
  16400. * End index of the array
  16401. */
  16402. function doQuickSort(ary, comparator, p, r) {
  16403. // If our lower bound is less than our upper bound, we (1) partition the
  16404. // array into two pieces and (2) recurse on each half. If it is not, this is
  16405. // the empty array and our base case.
  16406. if (p < r) {
  16407. // (1) Partitioning.
  16408. //
  16409. // The partitioning chooses a pivot between `p` and `r` and moves all
  16410. // elements that are less than or equal to the pivot to the before it, and
  16411. // all the elements that are greater than it after it. The effect is that
  16412. // once partition is done, the pivot is in the exact place it will be when
  16413. // the array is put in sorted order, and it will not need to be moved
  16414. // again. This runs in O(n) time.
  16415. // Always choose a random pivot so that an input array which is reverse
  16416. // sorted does not cause O(n^2) running time.
  16417. var pivotIndex = randomIntInRange(p, r);
  16418. var i = p - 1;
  16419. swap$1(ary, pivotIndex, r);
  16420. var pivot = ary[r];
  16421. // Immediately after `j` is incremented in this loop, the following hold
  16422. // true:
  16423. //
  16424. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  16425. //
  16426. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  16427. for (var j = p; j < r; j++) {
  16428. if (comparator(ary[j], pivot) <= 0) {
  16429. i += 1;
  16430. swap$1(ary, i, j);
  16431. }
  16432. }
  16433. swap$1(ary, i + 1, j);
  16434. var q = i + 1;
  16435. // (2) Recurse on each half.
  16436. doQuickSort(ary, comparator, p, q - 1);
  16437. doQuickSort(ary, comparator, q + 1, r);
  16438. }
  16439. }
  16440. /**
  16441. * Sort the given array in-place with the given comparator function.
  16442. *
  16443. * @param {Array} ary
  16444. * An array to sort.
  16445. * @param {function} comparator
  16446. * Function to use to compare two items.
  16447. */
  16448. quickSort$3.quickSort = function (ary, comparator) {
  16449. doQuickSort(ary, comparator, 0, ary.length - 1);
  16450. };
  16451. /* -*- Mode: js; js-indent-level: 2; -*- */
  16452. /*
  16453. * Copyright 2011 Mozilla Foundation and contributors
  16454. * Licensed under the New BSD license. See LICENSE or:
  16455. * http://opensource.org/licenses/BSD-3-Clause
  16456. */
  16457. var util$8 = util$c;
  16458. var binarySearch$2 = binarySearch$3;
  16459. var ArraySet$3 = arraySet$1.ArraySet;
  16460. var base64VLQ$2 = base64Vlq$1;
  16461. var quickSort$2 = quickSort$3.quickSort;
  16462. function SourceMapConsumer$6(aSourceMap, aSourceMapURL) {
  16463. var sourceMap = aSourceMap;
  16464. if (typeof aSourceMap === 'string') {
  16465. sourceMap = util$8.parseSourceMapInput(aSourceMap);
  16466. }
  16467. return sourceMap.sections != null
  16468. ? new IndexedSourceMapConsumer$1(sourceMap, aSourceMapURL)
  16469. : new BasicSourceMapConsumer$1(sourceMap, aSourceMapURL);
  16470. }
  16471. SourceMapConsumer$6.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  16472. return BasicSourceMapConsumer$1.fromSourceMap(aSourceMap, aSourceMapURL);
  16473. };
  16474. /**
  16475. * The version of the source mapping spec that we are consuming.
  16476. */
  16477. SourceMapConsumer$6.prototype._version = 3;
  16478. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  16479. // parsed mapping coordinates from the source map's "mappings" attribute. They
  16480. // are lazily instantiated, accessed via the `_generatedMappings` and
  16481. // `_originalMappings` getters respectively, and we only parse the mappings
  16482. // and create these arrays once queried for a source location. We jump through
  16483. // these hoops because there can be many thousands of mappings, and parsing
  16484. // them is expensive, so we only want to do it if we must.
  16485. //
  16486. // Each object in the arrays is of the form:
  16487. //
  16488. // {
  16489. // generatedLine: The line number in the generated code,
  16490. // generatedColumn: The column number in the generated code,
  16491. // source: The path to the original source file that generated this
  16492. // chunk of code,
  16493. // originalLine: The line number in the original source that
  16494. // corresponds to this chunk of generated code,
  16495. // originalColumn: The column number in the original source that
  16496. // corresponds to this chunk of generated code,
  16497. // name: The name of the original symbol which generated this chunk of
  16498. // code.
  16499. // }
  16500. //
  16501. // All properties except for `generatedLine` and `generatedColumn` can be
  16502. // `null`.
  16503. //
  16504. // `_generatedMappings` is ordered by the generated positions.
  16505. //
  16506. // `_originalMappings` is ordered by the original positions.
  16507. SourceMapConsumer$6.prototype.__generatedMappings = null;
  16508. Object.defineProperty(SourceMapConsumer$6.prototype, '_generatedMappings', {
  16509. configurable: true,
  16510. enumerable: true,
  16511. get: function () {
  16512. if (!this.__generatedMappings) {
  16513. this._parseMappings(this._mappings, this.sourceRoot);
  16514. }
  16515. return this.__generatedMappings;
  16516. }
  16517. });
  16518. SourceMapConsumer$6.prototype.__originalMappings = null;
  16519. Object.defineProperty(SourceMapConsumer$6.prototype, '_originalMappings', {
  16520. configurable: true,
  16521. enumerable: true,
  16522. get: function () {
  16523. if (!this.__originalMappings) {
  16524. this._parseMappings(this._mappings, this.sourceRoot);
  16525. }
  16526. return this.__originalMappings;
  16527. }
  16528. });
  16529. SourceMapConsumer$6.prototype._charIsMappingSeparator =
  16530. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  16531. var c = aStr.charAt(index);
  16532. return c === ";" || c === ",";
  16533. };
  16534. /**
  16535. * Parse the mappings in a string in to a data structure which we can easily
  16536. * query (the ordered arrays in the `this.__generatedMappings` and
  16537. * `this.__originalMappings` properties).
  16538. */
  16539. SourceMapConsumer$6.prototype._parseMappings =
  16540. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  16541. throw new Error("Subclasses must implement _parseMappings");
  16542. };
  16543. SourceMapConsumer$6.GENERATED_ORDER = 1;
  16544. SourceMapConsumer$6.ORIGINAL_ORDER = 2;
  16545. SourceMapConsumer$6.GREATEST_LOWER_BOUND = 1;
  16546. SourceMapConsumer$6.LEAST_UPPER_BOUND = 2;
  16547. /**
  16548. * Iterate over each mapping between an original source/line/column and a
  16549. * generated line/column in this source map.
  16550. *
  16551. * @param Function aCallback
  16552. * The function that is called with each mapping.
  16553. * @param Object aContext
  16554. * Optional. If specified, this object will be the value of `this` every
  16555. * time that `aCallback` is called.
  16556. * @param aOrder
  16557. * Either `SourceMapConsumer.GENERATED_ORDER` or
  16558. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  16559. * iterate over the mappings sorted by the generated file's line/column
  16560. * order or the original's source/line/column order, respectively. Defaults to
  16561. * `SourceMapConsumer.GENERATED_ORDER`.
  16562. */
  16563. SourceMapConsumer$6.prototype.eachMapping =
  16564. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  16565. var context = aContext || null;
  16566. var order = aOrder || SourceMapConsumer$6.GENERATED_ORDER;
  16567. var mappings;
  16568. switch (order) {
  16569. case SourceMapConsumer$6.GENERATED_ORDER:
  16570. mappings = this._generatedMappings;
  16571. break;
  16572. case SourceMapConsumer$6.ORIGINAL_ORDER:
  16573. mappings = this._originalMappings;
  16574. break;
  16575. default:
  16576. throw new Error("Unknown order of iteration.");
  16577. }
  16578. var sourceRoot = this.sourceRoot;
  16579. mappings.map(function (mapping) {
  16580. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  16581. source = util$8.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  16582. return {
  16583. source: source,
  16584. generatedLine: mapping.generatedLine,
  16585. generatedColumn: mapping.generatedColumn,
  16586. originalLine: mapping.originalLine,
  16587. originalColumn: mapping.originalColumn,
  16588. name: mapping.name === null ? null : this._names.at(mapping.name)
  16589. };
  16590. }, this).forEach(aCallback, context);
  16591. };
  16592. /**
  16593. * Returns all generated line and column information for the original source,
  16594. * line, and column provided. If no column is provided, returns all mappings
  16595. * corresponding to a either the line we are searching for or the next
  16596. * closest line that has any mappings. Otherwise, returns all mappings
  16597. * corresponding to the given line and either the column we are searching for
  16598. * or the next closest column that has any offsets.
  16599. *
  16600. * The only argument is an object with the following properties:
  16601. *
  16602. * - source: The filename of the original source.
  16603. * - line: The line number in the original source. The line number is 1-based.
  16604. * - column: Optional. the column number in the original source.
  16605. * The column number is 0-based.
  16606. *
  16607. * and an array of objects is returned, each with the following properties:
  16608. *
  16609. * - line: The line number in the generated source, or null. The
  16610. * line number is 1-based.
  16611. * - column: The column number in the generated source, or null.
  16612. * The column number is 0-based.
  16613. */
  16614. SourceMapConsumer$6.prototype.allGeneratedPositionsFor =
  16615. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  16616. var line = util$8.getArg(aArgs, 'line');
  16617. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  16618. // returns the index of the closest mapping less than the needle. By
  16619. // setting needle.originalColumn to 0, we thus find the last mapping for
  16620. // the given line, provided such a mapping exists.
  16621. var needle = {
  16622. source: util$8.getArg(aArgs, 'source'),
  16623. originalLine: line,
  16624. originalColumn: util$8.getArg(aArgs, 'column', 0)
  16625. };
  16626. needle.source = this._findSourceIndex(needle.source);
  16627. if (needle.source < 0) {
  16628. return [];
  16629. }
  16630. var mappings = [];
  16631. var index = this._findMapping(needle,
  16632. this._originalMappings,
  16633. "originalLine",
  16634. "originalColumn",
  16635. util$8.compareByOriginalPositions,
  16636. binarySearch$2.LEAST_UPPER_BOUND);
  16637. if (index >= 0) {
  16638. var mapping = this._originalMappings[index];
  16639. if (aArgs.column === undefined) {
  16640. var originalLine = mapping.originalLine;
  16641. // Iterate until either we run out of mappings, or we run into
  16642. // a mapping for a different line than the one we found. Since
  16643. // mappings are sorted, this is guaranteed to find all mappings for
  16644. // the line we found.
  16645. while (mapping && mapping.originalLine === originalLine) {
  16646. mappings.push({
  16647. line: util$8.getArg(mapping, 'generatedLine', null),
  16648. column: util$8.getArg(mapping, 'generatedColumn', null),
  16649. lastColumn: util$8.getArg(mapping, 'lastGeneratedColumn', null)
  16650. });
  16651. mapping = this._originalMappings[++index];
  16652. }
  16653. } else {
  16654. var originalColumn = mapping.originalColumn;
  16655. // Iterate until either we run out of mappings, or we run into
  16656. // a mapping for a different line than the one we were searching for.
  16657. // Since mappings are sorted, this is guaranteed to find all mappings for
  16658. // the line we are searching for.
  16659. while (mapping &&
  16660. mapping.originalLine === line &&
  16661. mapping.originalColumn == originalColumn) {
  16662. mappings.push({
  16663. line: util$8.getArg(mapping, 'generatedLine', null),
  16664. column: util$8.getArg(mapping, 'generatedColumn', null),
  16665. lastColumn: util$8.getArg(mapping, 'lastGeneratedColumn', null)
  16666. });
  16667. mapping = this._originalMappings[++index];
  16668. }
  16669. }
  16670. }
  16671. return mappings;
  16672. };
  16673. sourceMapConsumer$1.SourceMapConsumer = SourceMapConsumer$6;
  16674. /**
  16675. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  16676. * query for information about the original file positions by giving it a file
  16677. * position in the generated source.
  16678. *
  16679. * The first parameter is the raw source map (either as a JSON string, or
  16680. * already parsed to an object). According to the spec, source maps have the
  16681. * following attributes:
  16682. *
  16683. * - version: Which version of the source map spec this map is following.
  16684. * - sources: An array of URLs to the original source files.
  16685. * - names: An array of identifiers which can be referrenced by individual mappings.
  16686. * - sourceRoot: Optional. The URL root from which all sources are relative.
  16687. * - sourcesContent: Optional. An array of contents of the original source files.
  16688. * - mappings: A string of base64 VLQs which contain the actual mappings.
  16689. * - file: Optional. The generated file this source map is associated with.
  16690. *
  16691. * Here is an example source map, taken from the source map spec[0]:
  16692. *
  16693. * {
  16694. * version : 3,
  16695. * file: "out.js",
  16696. * sourceRoot : "",
  16697. * sources: ["foo.js", "bar.js"],
  16698. * names: ["src", "maps", "are", "fun"],
  16699. * mappings: "AA,AB;;ABCDE;"
  16700. * }
  16701. *
  16702. * The second parameter, if given, is a string whose value is the URL
  16703. * at which the source map was found. This URL is used to compute the
  16704. * sources array.
  16705. *
  16706. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  16707. */
  16708. function BasicSourceMapConsumer$1(aSourceMap, aSourceMapURL) {
  16709. var sourceMap = aSourceMap;
  16710. if (typeof aSourceMap === 'string') {
  16711. sourceMap = util$8.parseSourceMapInput(aSourceMap);
  16712. }
  16713. var version = util$8.getArg(sourceMap, 'version');
  16714. var sources = util$8.getArg(sourceMap, 'sources');
  16715. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  16716. // requires the array) to play nice here.
  16717. var names = util$8.getArg(sourceMap, 'names', []);
  16718. var sourceRoot = util$8.getArg(sourceMap, 'sourceRoot', null);
  16719. var sourcesContent = util$8.getArg(sourceMap, 'sourcesContent', null);
  16720. var mappings = util$8.getArg(sourceMap, 'mappings');
  16721. var file = util$8.getArg(sourceMap, 'file', null);
  16722. // Once again, Sass deviates from the spec and supplies the version as a
  16723. // string rather than a number, so we use loose equality checking here.
  16724. if (version != this._version) {
  16725. throw new Error('Unsupported version: ' + version);
  16726. }
  16727. if (sourceRoot) {
  16728. sourceRoot = util$8.normalize(sourceRoot);
  16729. }
  16730. sources = sources
  16731. .map(String)
  16732. // Some source maps produce relative source paths like "./foo.js" instead of
  16733. // "foo.js". Normalize these first so that future comparisons will succeed.
  16734. // See bugzil.la/1090768.
  16735. .map(util$8.normalize)
  16736. // Always ensure that absolute sources are internally stored relative to
  16737. // the source root, if the source root is absolute. Not doing this would
  16738. // be particularly problematic when the source root is a prefix of the
  16739. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  16740. .map(function (source) {
  16741. return sourceRoot && util$8.isAbsolute(sourceRoot) && util$8.isAbsolute(source)
  16742. ? util$8.relative(sourceRoot, source)
  16743. : source;
  16744. });
  16745. // Pass `true` below to allow duplicate names and sources. While source maps
  16746. // are intended to be compressed and deduplicated, the TypeScript compiler
  16747. // sometimes generates source maps with duplicates in them. See Github issue
  16748. // #72 and bugzil.la/889492.
  16749. this._names = ArraySet$3.fromArray(names.map(String), true);
  16750. this._sources = ArraySet$3.fromArray(sources, true);
  16751. this._absoluteSources = this._sources.toArray().map(function (s) {
  16752. return util$8.computeSourceURL(sourceRoot, s, aSourceMapURL);
  16753. });
  16754. this.sourceRoot = sourceRoot;
  16755. this.sourcesContent = sourcesContent;
  16756. this._mappings = mappings;
  16757. this._sourceMapURL = aSourceMapURL;
  16758. this.file = file;
  16759. }
  16760. BasicSourceMapConsumer$1.prototype = Object.create(SourceMapConsumer$6.prototype);
  16761. BasicSourceMapConsumer$1.prototype.consumer = SourceMapConsumer$6;
  16762. /**
  16763. * Utility function to find the index of a source. Returns -1 if not
  16764. * found.
  16765. */
  16766. BasicSourceMapConsumer$1.prototype._findSourceIndex = function(aSource) {
  16767. var relativeSource = aSource;
  16768. if (this.sourceRoot != null) {
  16769. relativeSource = util$8.relative(this.sourceRoot, relativeSource);
  16770. }
  16771. if (this._sources.has(relativeSource)) {
  16772. return this._sources.indexOf(relativeSource);
  16773. }
  16774. // Maybe aSource is an absolute URL as returned by |sources|. In
  16775. // this case we can't simply undo the transform.
  16776. var i;
  16777. for (i = 0; i < this._absoluteSources.length; ++i) {
  16778. if (this._absoluteSources[i] == aSource) {
  16779. return i;
  16780. }
  16781. }
  16782. return -1;
  16783. };
  16784. /**
  16785. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  16786. *
  16787. * @param SourceMapGenerator aSourceMap
  16788. * The source map that will be consumed.
  16789. * @param String aSourceMapURL
  16790. * The URL at which the source map can be found (optional)
  16791. * @returns BasicSourceMapConsumer
  16792. */
  16793. BasicSourceMapConsumer$1.fromSourceMap =
  16794. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  16795. var smc = Object.create(BasicSourceMapConsumer$1.prototype);
  16796. var names = smc._names = ArraySet$3.fromArray(aSourceMap._names.toArray(), true);
  16797. var sources = smc._sources = ArraySet$3.fromArray(aSourceMap._sources.toArray(), true);
  16798. smc.sourceRoot = aSourceMap._sourceRoot;
  16799. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  16800. smc.sourceRoot);
  16801. smc.file = aSourceMap._file;
  16802. smc._sourceMapURL = aSourceMapURL;
  16803. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  16804. return util$8.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  16805. });
  16806. // Because we are modifying the entries (by converting string sources and
  16807. // names to indices into the sources and names ArraySets), we have to make
  16808. // a copy of the entry or else bad things happen. Shared mutable state
  16809. // strikes again! See github issue #191.
  16810. var generatedMappings = aSourceMap._mappings.toArray().slice();
  16811. var destGeneratedMappings = smc.__generatedMappings = [];
  16812. var destOriginalMappings = smc.__originalMappings = [];
  16813. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  16814. var srcMapping = generatedMappings[i];
  16815. var destMapping = new Mapping$1;
  16816. destMapping.generatedLine = srcMapping.generatedLine;
  16817. destMapping.generatedColumn = srcMapping.generatedColumn;
  16818. if (srcMapping.source) {
  16819. destMapping.source = sources.indexOf(srcMapping.source);
  16820. destMapping.originalLine = srcMapping.originalLine;
  16821. destMapping.originalColumn = srcMapping.originalColumn;
  16822. if (srcMapping.name) {
  16823. destMapping.name = names.indexOf(srcMapping.name);
  16824. }
  16825. destOriginalMappings.push(destMapping);
  16826. }
  16827. destGeneratedMappings.push(destMapping);
  16828. }
  16829. quickSort$2(smc.__originalMappings, util$8.compareByOriginalPositions);
  16830. return smc;
  16831. };
  16832. /**
  16833. * The version of the source mapping spec that we are consuming.
  16834. */
  16835. BasicSourceMapConsumer$1.prototype._version = 3;
  16836. /**
  16837. * The list of original sources.
  16838. */
  16839. Object.defineProperty(BasicSourceMapConsumer$1.prototype, 'sources', {
  16840. get: function () {
  16841. return this._absoluteSources.slice();
  16842. }
  16843. });
  16844. /**
  16845. * Provide the JIT with a nice shape / hidden class.
  16846. */
  16847. function Mapping$1() {
  16848. this.generatedLine = 0;
  16849. this.generatedColumn = 0;
  16850. this.source = null;
  16851. this.originalLine = null;
  16852. this.originalColumn = null;
  16853. this.name = null;
  16854. }
  16855. /**
  16856. * Parse the mappings in a string in to a data structure which we can easily
  16857. * query (the ordered arrays in the `this.__generatedMappings` and
  16858. * `this.__originalMappings` properties).
  16859. */
  16860. BasicSourceMapConsumer$1.prototype._parseMappings =
  16861. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  16862. var generatedLine = 1;
  16863. var previousGeneratedColumn = 0;
  16864. var previousOriginalLine = 0;
  16865. var previousOriginalColumn = 0;
  16866. var previousSource = 0;
  16867. var previousName = 0;
  16868. var length = aStr.length;
  16869. var index = 0;
  16870. var cachedSegments = {};
  16871. var temp = {};
  16872. var originalMappings = [];
  16873. var generatedMappings = [];
  16874. var mapping, str, segment, end, value;
  16875. while (index < length) {
  16876. if (aStr.charAt(index) === ';') {
  16877. generatedLine++;
  16878. index++;
  16879. previousGeneratedColumn = 0;
  16880. }
  16881. else if (aStr.charAt(index) === ',') {
  16882. index++;
  16883. }
  16884. else {
  16885. mapping = new Mapping$1();
  16886. mapping.generatedLine = generatedLine;
  16887. // Because each offset is encoded relative to the previous one,
  16888. // many segments often have the same encoding. We can exploit this
  16889. // fact by caching the parsed variable length fields of each segment,
  16890. // allowing us to avoid a second parse if we encounter the same
  16891. // segment again.
  16892. for (end = index; end < length; end++) {
  16893. if (this._charIsMappingSeparator(aStr, end)) {
  16894. break;
  16895. }
  16896. }
  16897. str = aStr.slice(index, end);
  16898. segment = cachedSegments[str];
  16899. if (segment) {
  16900. index += str.length;
  16901. } else {
  16902. segment = [];
  16903. while (index < end) {
  16904. base64VLQ$2.decode(aStr, index, temp);
  16905. value = temp.value;
  16906. index = temp.rest;
  16907. segment.push(value);
  16908. }
  16909. if (segment.length === 2) {
  16910. throw new Error('Found a source, but no line and column');
  16911. }
  16912. if (segment.length === 3) {
  16913. throw new Error('Found a source and line, but no column');
  16914. }
  16915. cachedSegments[str] = segment;
  16916. }
  16917. // Generated column.
  16918. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  16919. previousGeneratedColumn = mapping.generatedColumn;
  16920. if (segment.length > 1) {
  16921. // Original source.
  16922. mapping.source = previousSource + segment[1];
  16923. previousSource += segment[1];
  16924. // Original line.
  16925. mapping.originalLine = previousOriginalLine + segment[2];
  16926. previousOriginalLine = mapping.originalLine;
  16927. // Lines are stored 0-based
  16928. mapping.originalLine += 1;
  16929. // Original column.
  16930. mapping.originalColumn = previousOriginalColumn + segment[3];
  16931. previousOriginalColumn = mapping.originalColumn;
  16932. if (segment.length > 4) {
  16933. // Original name.
  16934. mapping.name = previousName + segment[4];
  16935. previousName += segment[4];
  16936. }
  16937. }
  16938. generatedMappings.push(mapping);
  16939. if (typeof mapping.originalLine === 'number') {
  16940. originalMappings.push(mapping);
  16941. }
  16942. }
  16943. }
  16944. quickSort$2(generatedMappings, util$8.compareByGeneratedPositionsDeflated);
  16945. this.__generatedMappings = generatedMappings;
  16946. quickSort$2(originalMappings, util$8.compareByOriginalPositions);
  16947. this.__originalMappings = originalMappings;
  16948. };
  16949. /**
  16950. * Find the mapping that best matches the hypothetical "needle" mapping that
  16951. * we are searching for in the given "haystack" of mappings.
  16952. */
  16953. BasicSourceMapConsumer$1.prototype._findMapping =
  16954. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  16955. aColumnName, aComparator, aBias) {
  16956. // To return the position we are searching for, we must first find the
  16957. // mapping for the given position and then return the opposite position it
  16958. // points to. Because the mappings are sorted, we can use binary search to
  16959. // find the best mapping.
  16960. if (aNeedle[aLineName] <= 0) {
  16961. throw new TypeError('Line must be greater than or equal to 1, got '
  16962. + aNeedle[aLineName]);
  16963. }
  16964. if (aNeedle[aColumnName] < 0) {
  16965. throw new TypeError('Column must be greater than or equal to 0, got '
  16966. + aNeedle[aColumnName]);
  16967. }
  16968. return binarySearch$2.search(aNeedle, aMappings, aComparator, aBias);
  16969. };
  16970. /**
  16971. * Compute the last column for each generated mapping. The last column is
  16972. * inclusive.
  16973. */
  16974. BasicSourceMapConsumer$1.prototype.computeColumnSpans =
  16975. function SourceMapConsumer_computeColumnSpans() {
  16976. for (var index = 0; index < this._generatedMappings.length; ++index) {
  16977. var mapping = this._generatedMappings[index];
  16978. // Mappings do not contain a field for the last generated columnt. We
  16979. // can come up with an optimistic estimate, however, by assuming that
  16980. // mappings are contiguous (i.e. given two consecutive mappings, the
  16981. // first mapping ends where the second one starts).
  16982. if (index + 1 < this._generatedMappings.length) {
  16983. var nextMapping = this._generatedMappings[index + 1];
  16984. if (mapping.generatedLine === nextMapping.generatedLine) {
  16985. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  16986. continue;
  16987. }
  16988. }
  16989. // The last mapping for each line spans the entire line.
  16990. mapping.lastGeneratedColumn = Infinity;
  16991. }
  16992. };
  16993. /**
  16994. * Returns the original source, line, and column information for the generated
  16995. * source's line and column positions provided. The only argument is an object
  16996. * with the following properties:
  16997. *
  16998. * - line: The line number in the generated source. The line number
  16999. * is 1-based.
  17000. * - column: The column number in the generated source. The column
  17001. * number is 0-based.
  17002. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  17003. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  17004. * closest element that is smaller than or greater than the one we are
  17005. * searching for, respectively, if the exact element cannot be found.
  17006. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  17007. *
  17008. * and an object is returned with the following properties:
  17009. *
  17010. * - source: The original source file, or null.
  17011. * - line: The line number in the original source, or null. The
  17012. * line number is 1-based.
  17013. * - column: The column number in the original source, or null. The
  17014. * column number is 0-based.
  17015. * - name: The original identifier, or null.
  17016. */
  17017. BasicSourceMapConsumer$1.prototype.originalPositionFor =
  17018. function SourceMapConsumer_originalPositionFor(aArgs) {
  17019. var needle = {
  17020. generatedLine: util$8.getArg(aArgs, 'line'),
  17021. generatedColumn: util$8.getArg(aArgs, 'column')
  17022. };
  17023. var index = this._findMapping(
  17024. needle,
  17025. this._generatedMappings,
  17026. "generatedLine",
  17027. "generatedColumn",
  17028. util$8.compareByGeneratedPositionsDeflated,
  17029. util$8.getArg(aArgs, 'bias', SourceMapConsumer$6.GREATEST_LOWER_BOUND)
  17030. );
  17031. if (index >= 0) {
  17032. var mapping = this._generatedMappings[index];
  17033. if (mapping.generatedLine === needle.generatedLine) {
  17034. var source = util$8.getArg(mapping, 'source', null);
  17035. if (source !== null) {
  17036. source = this._sources.at(source);
  17037. source = util$8.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  17038. }
  17039. var name = util$8.getArg(mapping, 'name', null);
  17040. if (name !== null) {
  17041. name = this._names.at(name);
  17042. }
  17043. return {
  17044. source: source,
  17045. line: util$8.getArg(mapping, 'originalLine', null),
  17046. column: util$8.getArg(mapping, 'originalColumn', null),
  17047. name: name
  17048. };
  17049. }
  17050. }
  17051. return {
  17052. source: null,
  17053. line: null,
  17054. column: null,
  17055. name: null
  17056. };
  17057. };
  17058. /**
  17059. * Return true if we have the source content for every source in the source
  17060. * map, false otherwise.
  17061. */
  17062. BasicSourceMapConsumer$1.prototype.hasContentsOfAllSources =
  17063. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  17064. if (!this.sourcesContent) {
  17065. return false;
  17066. }
  17067. return this.sourcesContent.length >= this._sources.size() &&
  17068. !this.sourcesContent.some(function (sc) { return sc == null; });
  17069. };
  17070. /**
  17071. * Returns the original source content. The only argument is the url of the
  17072. * original source file. Returns null if no original source content is
  17073. * available.
  17074. */
  17075. BasicSourceMapConsumer$1.prototype.sourceContentFor =
  17076. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  17077. if (!this.sourcesContent) {
  17078. return null;
  17079. }
  17080. var index = this._findSourceIndex(aSource);
  17081. if (index >= 0) {
  17082. return this.sourcesContent[index];
  17083. }
  17084. var relativeSource = aSource;
  17085. if (this.sourceRoot != null) {
  17086. relativeSource = util$8.relative(this.sourceRoot, relativeSource);
  17087. }
  17088. var url;
  17089. if (this.sourceRoot != null
  17090. && (url = util$8.urlParse(this.sourceRoot))) {
  17091. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  17092. // many users. We can help them out when they expect file:// URIs to
  17093. // behave like it would if they were running a local HTTP server. See
  17094. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  17095. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  17096. if (url.scheme == "file"
  17097. && this._sources.has(fileUriAbsPath)) {
  17098. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  17099. }
  17100. if ((!url.path || url.path == "/")
  17101. && this._sources.has("/" + relativeSource)) {
  17102. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  17103. }
  17104. }
  17105. // This function is used recursively from
  17106. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  17107. // don't want to throw if we can't find the source - we just want to
  17108. // return null, so we provide a flag to exit gracefully.
  17109. if (nullOnMissing) {
  17110. return null;
  17111. }
  17112. else {
  17113. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  17114. }
  17115. };
  17116. /**
  17117. * Returns the generated line and column information for the original source,
  17118. * line, and column positions provided. The only argument is an object with
  17119. * the following properties:
  17120. *
  17121. * - source: The filename of the original source.
  17122. * - line: The line number in the original source. The line number
  17123. * is 1-based.
  17124. * - column: The column number in the original source. The column
  17125. * number is 0-based.
  17126. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  17127. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  17128. * closest element that is smaller than or greater than the one we are
  17129. * searching for, respectively, if the exact element cannot be found.
  17130. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  17131. *
  17132. * and an object is returned with the following properties:
  17133. *
  17134. * - line: The line number in the generated source, or null. The
  17135. * line number is 1-based.
  17136. * - column: The column number in the generated source, or null.
  17137. * The column number is 0-based.
  17138. */
  17139. BasicSourceMapConsumer$1.prototype.generatedPositionFor =
  17140. function SourceMapConsumer_generatedPositionFor(aArgs) {
  17141. var source = util$8.getArg(aArgs, 'source');
  17142. source = this._findSourceIndex(source);
  17143. if (source < 0) {
  17144. return {
  17145. line: null,
  17146. column: null,
  17147. lastColumn: null
  17148. };
  17149. }
  17150. var needle = {
  17151. source: source,
  17152. originalLine: util$8.getArg(aArgs, 'line'),
  17153. originalColumn: util$8.getArg(aArgs, 'column')
  17154. };
  17155. var index = this._findMapping(
  17156. needle,
  17157. this._originalMappings,
  17158. "originalLine",
  17159. "originalColumn",
  17160. util$8.compareByOriginalPositions,
  17161. util$8.getArg(aArgs, 'bias', SourceMapConsumer$6.GREATEST_LOWER_BOUND)
  17162. );
  17163. if (index >= 0) {
  17164. var mapping = this._originalMappings[index];
  17165. if (mapping.source === needle.source) {
  17166. return {
  17167. line: util$8.getArg(mapping, 'generatedLine', null),
  17168. column: util$8.getArg(mapping, 'generatedColumn', null),
  17169. lastColumn: util$8.getArg(mapping, 'lastGeneratedColumn', null)
  17170. };
  17171. }
  17172. }
  17173. return {
  17174. line: null,
  17175. column: null,
  17176. lastColumn: null
  17177. };
  17178. };
  17179. sourceMapConsumer$1.BasicSourceMapConsumer = BasicSourceMapConsumer$1;
  17180. /**
  17181. * An IndexedSourceMapConsumer instance represents a parsed source map which
  17182. * we can query for information. It differs from BasicSourceMapConsumer in
  17183. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  17184. * input.
  17185. *
  17186. * The first parameter is a raw source map (either as a JSON string, or already
  17187. * parsed to an object). According to the spec for indexed source maps, they
  17188. * have the following attributes:
  17189. *
  17190. * - version: Which version of the source map spec this map is following.
  17191. * - file: Optional. The generated file this source map is associated with.
  17192. * - sections: A list of section definitions.
  17193. *
  17194. * Each value under the "sections" field has two fields:
  17195. * - offset: The offset into the original specified at which this section
  17196. * begins to apply, defined as an object with a "line" and "column"
  17197. * field.
  17198. * - map: A source map definition. This source map could also be indexed,
  17199. * but doesn't have to be.
  17200. *
  17201. * Instead of the "map" field, it's also possible to have a "url" field
  17202. * specifying a URL to retrieve a source map from, but that's currently
  17203. * unsupported.
  17204. *
  17205. * Here's an example source map, taken from the source map spec[0], but
  17206. * modified to omit a section which uses the "url" field.
  17207. *
  17208. * {
  17209. * version : 3,
  17210. * file: "app.js",
  17211. * sections: [{
  17212. * offset: {line:100, column:10},
  17213. * map: {
  17214. * version : 3,
  17215. * file: "section.js",
  17216. * sources: ["foo.js", "bar.js"],
  17217. * names: ["src", "maps", "are", "fun"],
  17218. * mappings: "AAAA,E;;ABCDE;"
  17219. * }
  17220. * }],
  17221. * }
  17222. *
  17223. * The second parameter, if given, is a string whose value is the URL
  17224. * at which the source map was found. This URL is used to compute the
  17225. * sources array.
  17226. *
  17227. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  17228. */
  17229. function IndexedSourceMapConsumer$1(aSourceMap, aSourceMapURL) {
  17230. var sourceMap = aSourceMap;
  17231. if (typeof aSourceMap === 'string') {
  17232. sourceMap = util$8.parseSourceMapInput(aSourceMap);
  17233. }
  17234. var version = util$8.getArg(sourceMap, 'version');
  17235. var sections = util$8.getArg(sourceMap, 'sections');
  17236. if (version != this._version) {
  17237. throw new Error('Unsupported version: ' + version);
  17238. }
  17239. this._sources = new ArraySet$3();
  17240. this._names = new ArraySet$3();
  17241. var lastOffset = {
  17242. line: -1,
  17243. column: 0
  17244. };
  17245. this._sections = sections.map(function (s) {
  17246. if (s.url) {
  17247. // The url field will require support for asynchronicity.
  17248. // See https://github.com/mozilla/source-map/issues/16
  17249. throw new Error('Support for url field in sections not implemented.');
  17250. }
  17251. var offset = util$8.getArg(s, 'offset');
  17252. var offsetLine = util$8.getArg(offset, 'line');
  17253. var offsetColumn = util$8.getArg(offset, 'column');
  17254. if (offsetLine < lastOffset.line ||
  17255. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  17256. throw new Error('Section offsets must be ordered and non-overlapping.');
  17257. }
  17258. lastOffset = offset;
  17259. return {
  17260. generatedOffset: {
  17261. // The offset fields are 0-based, but we use 1-based indices when
  17262. // encoding/decoding from VLQ.
  17263. generatedLine: offsetLine + 1,
  17264. generatedColumn: offsetColumn + 1
  17265. },
  17266. consumer: new SourceMapConsumer$6(util$8.getArg(s, 'map'), aSourceMapURL)
  17267. }
  17268. });
  17269. }
  17270. IndexedSourceMapConsumer$1.prototype = Object.create(SourceMapConsumer$6.prototype);
  17271. IndexedSourceMapConsumer$1.prototype.constructor = SourceMapConsumer$6;
  17272. /**
  17273. * The version of the source mapping spec that we are consuming.
  17274. */
  17275. IndexedSourceMapConsumer$1.prototype._version = 3;
  17276. /**
  17277. * The list of original sources.
  17278. */
  17279. Object.defineProperty(IndexedSourceMapConsumer$1.prototype, 'sources', {
  17280. get: function () {
  17281. var sources = [];
  17282. for (var i = 0; i < this._sections.length; i++) {
  17283. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  17284. sources.push(this._sections[i].consumer.sources[j]);
  17285. }
  17286. }
  17287. return sources;
  17288. }
  17289. });
  17290. /**
  17291. * Returns the original source, line, and column information for the generated
  17292. * source's line and column positions provided. The only argument is an object
  17293. * with the following properties:
  17294. *
  17295. * - line: The line number in the generated source. The line number
  17296. * is 1-based.
  17297. * - column: The column number in the generated source. The column
  17298. * number is 0-based.
  17299. *
  17300. * and an object is returned with the following properties:
  17301. *
  17302. * - source: The original source file, or null.
  17303. * - line: The line number in the original source, or null. The
  17304. * line number is 1-based.
  17305. * - column: The column number in the original source, or null. The
  17306. * column number is 0-based.
  17307. * - name: The original identifier, or null.
  17308. */
  17309. IndexedSourceMapConsumer$1.prototype.originalPositionFor =
  17310. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  17311. var needle = {
  17312. generatedLine: util$8.getArg(aArgs, 'line'),
  17313. generatedColumn: util$8.getArg(aArgs, 'column')
  17314. };
  17315. // Find the section containing the generated position we're trying to map
  17316. // to an original position.
  17317. var sectionIndex = binarySearch$2.search(needle, this._sections,
  17318. function(needle, section) {
  17319. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  17320. if (cmp) {
  17321. return cmp;
  17322. }
  17323. return (needle.generatedColumn -
  17324. section.generatedOffset.generatedColumn);
  17325. });
  17326. var section = this._sections[sectionIndex];
  17327. if (!section) {
  17328. return {
  17329. source: null,
  17330. line: null,
  17331. column: null,
  17332. name: null
  17333. };
  17334. }
  17335. return section.consumer.originalPositionFor({
  17336. line: needle.generatedLine -
  17337. (section.generatedOffset.generatedLine - 1),
  17338. column: needle.generatedColumn -
  17339. (section.generatedOffset.generatedLine === needle.generatedLine
  17340. ? section.generatedOffset.generatedColumn - 1
  17341. : 0),
  17342. bias: aArgs.bias
  17343. });
  17344. };
  17345. /**
  17346. * Return true if we have the source content for every source in the source
  17347. * map, false otherwise.
  17348. */
  17349. IndexedSourceMapConsumer$1.prototype.hasContentsOfAllSources =
  17350. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  17351. return this._sections.every(function (s) {
  17352. return s.consumer.hasContentsOfAllSources();
  17353. });
  17354. };
  17355. /**
  17356. * Returns the original source content. The only argument is the url of the
  17357. * original source file. Returns null if no original source content is
  17358. * available.
  17359. */
  17360. IndexedSourceMapConsumer$1.prototype.sourceContentFor =
  17361. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  17362. for (var i = 0; i < this._sections.length; i++) {
  17363. var section = this._sections[i];
  17364. var content = section.consumer.sourceContentFor(aSource, true);
  17365. if (content) {
  17366. return content;
  17367. }
  17368. }
  17369. if (nullOnMissing) {
  17370. return null;
  17371. }
  17372. else {
  17373. throw new Error('"' + aSource + '" is not in the SourceMap.');
  17374. }
  17375. };
  17376. /**
  17377. * Returns the generated line and column information for the original source,
  17378. * line, and column positions provided. The only argument is an object with
  17379. * the following properties:
  17380. *
  17381. * - source: The filename of the original source.
  17382. * - line: The line number in the original source. The line number
  17383. * is 1-based.
  17384. * - column: The column number in the original source. The column
  17385. * number is 0-based.
  17386. *
  17387. * and an object is returned with the following properties:
  17388. *
  17389. * - line: The line number in the generated source, or null. The
  17390. * line number is 1-based.
  17391. * - column: The column number in the generated source, or null.
  17392. * The column number is 0-based.
  17393. */
  17394. IndexedSourceMapConsumer$1.prototype.generatedPositionFor =
  17395. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  17396. for (var i = 0; i < this._sections.length; i++) {
  17397. var section = this._sections[i];
  17398. // Only consider this section if the requested source is in the list of
  17399. // sources of the consumer.
  17400. if (section.consumer._findSourceIndex(util$8.getArg(aArgs, 'source')) === -1) {
  17401. continue;
  17402. }
  17403. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  17404. if (generatedPosition) {
  17405. var ret = {
  17406. line: generatedPosition.line +
  17407. (section.generatedOffset.generatedLine - 1),
  17408. column: generatedPosition.column +
  17409. (section.generatedOffset.generatedLine === generatedPosition.line
  17410. ? section.generatedOffset.generatedColumn - 1
  17411. : 0)
  17412. };
  17413. return ret;
  17414. }
  17415. }
  17416. return {
  17417. line: null,
  17418. column: null
  17419. };
  17420. };
  17421. /**
  17422. * Parse the mappings in a string in to a data structure which we can easily
  17423. * query (the ordered arrays in the `this.__generatedMappings` and
  17424. * `this.__originalMappings` properties).
  17425. */
  17426. IndexedSourceMapConsumer$1.prototype._parseMappings =
  17427. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  17428. this.__generatedMappings = [];
  17429. this.__originalMappings = [];
  17430. for (var i = 0; i < this._sections.length; i++) {
  17431. var section = this._sections[i];
  17432. var sectionMappings = section.consumer._generatedMappings;
  17433. for (var j = 0; j < sectionMappings.length; j++) {
  17434. var mapping = sectionMappings[j];
  17435. var source = section.consumer._sources.at(mapping.source);
  17436. source = util$8.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  17437. this._sources.add(source);
  17438. source = this._sources.indexOf(source);
  17439. var name = null;
  17440. if (mapping.name) {
  17441. name = section.consumer._names.at(mapping.name);
  17442. this._names.add(name);
  17443. name = this._names.indexOf(name);
  17444. }
  17445. // The mappings coming from the consumer for the section have
  17446. // generated positions relative to the start of the section, so we
  17447. // need to offset them to be relative to the start of the concatenated
  17448. // generated file.
  17449. var adjustedMapping = {
  17450. source: source,
  17451. generatedLine: mapping.generatedLine +
  17452. (section.generatedOffset.generatedLine - 1),
  17453. generatedColumn: mapping.generatedColumn +
  17454. (section.generatedOffset.generatedLine === mapping.generatedLine
  17455. ? section.generatedOffset.generatedColumn - 1
  17456. : 0),
  17457. originalLine: mapping.originalLine,
  17458. originalColumn: mapping.originalColumn,
  17459. name: name
  17460. };
  17461. this.__generatedMappings.push(adjustedMapping);
  17462. if (typeof adjustedMapping.originalLine === 'number') {
  17463. this.__originalMappings.push(adjustedMapping);
  17464. }
  17465. }
  17466. }
  17467. quickSort$2(this.__generatedMappings, util$8.compareByGeneratedPositionsDeflated);
  17468. quickSort$2(this.__originalMappings, util$8.compareByOriginalPositions);
  17469. };
  17470. sourceMapConsumer$1.IndexedSourceMapConsumer = IndexedSourceMapConsumer$1;
  17471. var sourceNode$1 = {};
  17472. /* -*- Mode: js; js-indent-level: 2; -*- */
  17473. /*
  17474. * Copyright 2011 Mozilla Foundation and contributors
  17475. * Licensed under the New BSD license. See LICENSE or:
  17476. * http://opensource.org/licenses/BSD-3-Clause
  17477. */
  17478. var SourceMapGenerator$7 = sourceMapGenerator$1.SourceMapGenerator;
  17479. var util$7 = util$c;
  17480. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  17481. // operating systems these days (capturing the result).
  17482. var REGEX_NEWLINE$1 = /(\r?\n)/;
  17483. // Newline character code for charCodeAt() comparisons
  17484. var NEWLINE_CODE$1 = 10;
  17485. // Private symbol for identifying `SourceNode`s when multiple versions of
  17486. // the source-map library are loaded. This MUST NOT CHANGE across
  17487. // versions!
  17488. var isSourceNode$1 = "$$$isSourceNode$$$";
  17489. /**
  17490. * SourceNodes provide a way to abstract over interpolating/concatenating
  17491. * snippets of generated JavaScript source code while maintaining the line and
  17492. * column information associated with the original source code.
  17493. *
  17494. * @param aLine The original line number.
  17495. * @param aColumn The original column number.
  17496. * @param aSource The original source's filename.
  17497. * @param aChunks Optional. An array of strings which are snippets of
  17498. * generated JS, or other SourceNodes.
  17499. * @param aName The original identifier.
  17500. */
  17501. function SourceNode$1(aLine, aColumn, aSource, aChunks, aName) {
  17502. this.children = [];
  17503. this.sourceContents = {};
  17504. this.line = aLine == null ? null : aLine;
  17505. this.column = aColumn == null ? null : aColumn;
  17506. this.source = aSource == null ? null : aSource;
  17507. this.name = aName == null ? null : aName;
  17508. this[isSourceNode$1] = true;
  17509. if (aChunks != null) this.add(aChunks);
  17510. }
  17511. /**
  17512. * Creates a SourceNode from generated code and a SourceMapConsumer.
  17513. *
  17514. * @param aGeneratedCode The generated code
  17515. * @param aSourceMapConsumer The SourceMap for the generated code
  17516. * @param aRelativePath Optional. The path that relative sources in the
  17517. * SourceMapConsumer should be relative to.
  17518. */
  17519. SourceNode$1.fromStringWithSourceMap =
  17520. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  17521. // The SourceNode we want to fill with the generated code
  17522. // and the SourceMap
  17523. var node = new SourceNode$1();
  17524. // All even indices of this array are one line of the generated code,
  17525. // while all odd indices are the newlines between two adjacent lines
  17526. // (since `REGEX_NEWLINE` captures its match).
  17527. // Processed fragments are accessed by calling `shiftNextLine`.
  17528. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE$1);
  17529. var remainingLinesIndex = 0;
  17530. var shiftNextLine = function() {
  17531. var lineContents = getNextLine();
  17532. // The last line of a file might not have a newline.
  17533. var newLine = getNextLine() || "";
  17534. return lineContents + newLine;
  17535. function getNextLine() {
  17536. return remainingLinesIndex < remainingLines.length ?
  17537. remainingLines[remainingLinesIndex++] : undefined;
  17538. }
  17539. };
  17540. // We need to remember the position of "remainingLines"
  17541. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  17542. // The generate SourceNodes we need a code range.
  17543. // To extract it current and last mapping is used.
  17544. // Here we store the last mapping.
  17545. var lastMapping = null;
  17546. aSourceMapConsumer.eachMapping(function (mapping) {
  17547. if (lastMapping !== null) {
  17548. // We add the code from "lastMapping" to "mapping":
  17549. // First check if there is a new line in between.
  17550. if (lastGeneratedLine < mapping.generatedLine) {
  17551. // Associate first line with "lastMapping"
  17552. addMappingWithCode(lastMapping, shiftNextLine());
  17553. lastGeneratedLine++;
  17554. lastGeneratedColumn = 0;
  17555. // The remaining code is added without mapping
  17556. } else {
  17557. // There is no new line in between.
  17558. // Associate the code between "lastGeneratedColumn" and
  17559. // "mapping.generatedColumn" with "lastMapping"
  17560. var nextLine = remainingLines[remainingLinesIndex] || '';
  17561. var code = nextLine.substr(0, mapping.generatedColumn -
  17562. lastGeneratedColumn);
  17563. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  17564. lastGeneratedColumn);
  17565. lastGeneratedColumn = mapping.generatedColumn;
  17566. addMappingWithCode(lastMapping, code);
  17567. // No more remaining code, continue
  17568. lastMapping = mapping;
  17569. return;
  17570. }
  17571. }
  17572. // We add the generated code until the first mapping
  17573. // to the SourceNode without any mapping.
  17574. // Each line is added as separate string.
  17575. while (lastGeneratedLine < mapping.generatedLine) {
  17576. node.add(shiftNextLine());
  17577. lastGeneratedLine++;
  17578. }
  17579. if (lastGeneratedColumn < mapping.generatedColumn) {
  17580. var nextLine = remainingLines[remainingLinesIndex] || '';
  17581. node.add(nextLine.substr(0, mapping.generatedColumn));
  17582. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  17583. lastGeneratedColumn = mapping.generatedColumn;
  17584. }
  17585. lastMapping = mapping;
  17586. }, this);
  17587. // We have processed all mappings.
  17588. if (remainingLinesIndex < remainingLines.length) {
  17589. if (lastMapping) {
  17590. // Associate the remaining code in the current line with "lastMapping"
  17591. addMappingWithCode(lastMapping, shiftNextLine());
  17592. }
  17593. // and add the remaining lines without any mapping
  17594. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  17595. }
  17596. // Copy sourcesContent into SourceNode
  17597. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  17598. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  17599. if (content != null) {
  17600. if (aRelativePath != null) {
  17601. sourceFile = util$7.join(aRelativePath, sourceFile);
  17602. }
  17603. node.setSourceContent(sourceFile, content);
  17604. }
  17605. });
  17606. return node;
  17607. function addMappingWithCode(mapping, code) {
  17608. if (mapping === null || mapping.source === undefined) {
  17609. node.add(code);
  17610. } else {
  17611. var source = aRelativePath
  17612. ? util$7.join(aRelativePath, mapping.source)
  17613. : mapping.source;
  17614. node.add(new SourceNode$1(mapping.originalLine,
  17615. mapping.originalColumn,
  17616. source,
  17617. code,
  17618. mapping.name));
  17619. }
  17620. }
  17621. };
  17622. /**
  17623. * Add a chunk of generated JS to this source node.
  17624. *
  17625. * @param aChunk A string snippet of generated JS code, another instance of
  17626. * SourceNode, or an array where each member is one of those things.
  17627. */
  17628. SourceNode$1.prototype.add = function SourceNode_add(aChunk) {
  17629. if (Array.isArray(aChunk)) {
  17630. aChunk.forEach(function (chunk) {
  17631. this.add(chunk);
  17632. }, this);
  17633. }
  17634. else if (aChunk[isSourceNode$1] || typeof aChunk === "string") {
  17635. if (aChunk) {
  17636. this.children.push(aChunk);
  17637. }
  17638. }
  17639. else {
  17640. throw new TypeError(
  17641. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  17642. );
  17643. }
  17644. return this;
  17645. };
  17646. /**
  17647. * Add a chunk of generated JS to the beginning of this source node.
  17648. *
  17649. * @param aChunk A string snippet of generated JS code, another instance of
  17650. * SourceNode, or an array where each member is one of those things.
  17651. */
  17652. SourceNode$1.prototype.prepend = function SourceNode_prepend(aChunk) {
  17653. if (Array.isArray(aChunk)) {
  17654. for (var i = aChunk.length-1; i >= 0; i--) {
  17655. this.prepend(aChunk[i]);
  17656. }
  17657. }
  17658. else if (aChunk[isSourceNode$1] || typeof aChunk === "string") {
  17659. this.children.unshift(aChunk);
  17660. }
  17661. else {
  17662. throw new TypeError(
  17663. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  17664. );
  17665. }
  17666. return this;
  17667. };
  17668. /**
  17669. * Walk over the tree of JS snippets in this node and its children. The
  17670. * walking function is called once for each snippet of JS and is passed that
  17671. * snippet and the its original associated source's line/column location.
  17672. *
  17673. * @param aFn The traversal function.
  17674. */
  17675. SourceNode$1.prototype.walk = function SourceNode_walk(aFn) {
  17676. var chunk;
  17677. for (var i = 0, len = this.children.length; i < len; i++) {
  17678. chunk = this.children[i];
  17679. if (chunk[isSourceNode$1]) {
  17680. chunk.walk(aFn);
  17681. }
  17682. else {
  17683. if (chunk !== '') {
  17684. aFn(chunk, { source: this.source,
  17685. line: this.line,
  17686. column: this.column,
  17687. name: this.name });
  17688. }
  17689. }
  17690. }
  17691. };
  17692. /**
  17693. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  17694. * each of `this.children`.
  17695. *
  17696. * @param aSep The separator.
  17697. */
  17698. SourceNode$1.prototype.join = function SourceNode_join(aSep) {
  17699. var newChildren;
  17700. var i;
  17701. var len = this.children.length;
  17702. if (len > 0) {
  17703. newChildren = [];
  17704. for (i = 0; i < len-1; i++) {
  17705. newChildren.push(this.children[i]);
  17706. newChildren.push(aSep);
  17707. }
  17708. newChildren.push(this.children[i]);
  17709. this.children = newChildren;
  17710. }
  17711. return this;
  17712. };
  17713. /**
  17714. * Call String.prototype.replace on the very right-most source snippet. Useful
  17715. * for trimming whitespace from the end of a source node, etc.
  17716. *
  17717. * @param aPattern The pattern to replace.
  17718. * @param aReplacement The thing to replace the pattern with.
  17719. */
  17720. SourceNode$1.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  17721. var lastChild = this.children[this.children.length - 1];
  17722. if (lastChild[isSourceNode$1]) {
  17723. lastChild.replaceRight(aPattern, aReplacement);
  17724. }
  17725. else if (typeof lastChild === 'string') {
  17726. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  17727. }
  17728. else {
  17729. this.children.push(''.replace(aPattern, aReplacement));
  17730. }
  17731. return this;
  17732. };
  17733. /**
  17734. * Set the source content for a source file. This will be added to the SourceMapGenerator
  17735. * in the sourcesContent field.
  17736. *
  17737. * @param aSourceFile The filename of the source file
  17738. * @param aSourceContent The content of the source file
  17739. */
  17740. SourceNode$1.prototype.setSourceContent =
  17741. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  17742. this.sourceContents[util$7.toSetString(aSourceFile)] = aSourceContent;
  17743. };
  17744. /**
  17745. * Walk over the tree of SourceNodes. The walking function is called for each
  17746. * source file content and is passed the filename and source content.
  17747. *
  17748. * @param aFn The traversal function.
  17749. */
  17750. SourceNode$1.prototype.walkSourceContents =
  17751. function SourceNode_walkSourceContents(aFn) {
  17752. for (var i = 0, len = this.children.length; i < len; i++) {
  17753. if (this.children[i][isSourceNode$1]) {
  17754. this.children[i].walkSourceContents(aFn);
  17755. }
  17756. }
  17757. var sources = Object.keys(this.sourceContents);
  17758. for (var i = 0, len = sources.length; i < len; i++) {
  17759. aFn(util$7.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  17760. }
  17761. };
  17762. /**
  17763. * Return the string representation of this source node. Walks over the tree
  17764. * and concatenates all the various snippets together to one string.
  17765. */
  17766. SourceNode$1.prototype.toString = function SourceNode_toString() {
  17767. var str = "";
  17768. this.walk(function (chunk) {
  17769. str += chunk;
  17770. });
  17771. return str;
  17772. };
  17773. /**
  17774. * Returns the string representation of this source node along with a source
  17775. * map.
  17776. */
  17777. SourceNode$1.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  17778. var generated = {
  17779. code: "",
  17780. line: 1,
  17781. column: 0
  17782. };
  17783. var map = new SourceMapGenerator$7(aArgs);
  17784. var sourceMappingActive = false;
  17785. var lastOriginalSource = null;
  17786. var lastOriginalLine = null;
  17787. var lastOriginalColumn = null;
  17788. var lastOriginalName = null;
  17789. this.walk(function (chunk, original) {
  17790. generated.code += chunk;
  17791. if (original.source !== null
  17792. && original.line !== null
  17793. && original.column !== null) {
  17794. if(lastOriginalSource !== original.source
  17795. || lastOriginalLine !== original.line
  17796. || lastOriginalColumn !== original.column
  17797. || lastOriginalName !== original.name) {
  17798. map.addMapping({
  17799. source: original.source,
  17800. original: {
  17801. line: original.line,
  17802. column: original.column
  17803. },
  17804. generated: {
  17805. line: generated.line,
  17806. column: generated.column
  17807. },
  17808. name: original.name
  17809. });
  17810. }
  17811. lastOriginalSource = original.source;
  17812. lastOriginalLine = original.line;
  17813. lastOriginalColumn = original.column;
  17814. lastOriginalName = original.name;
  17815. sourceMappingActive = true;
  17816. } else if (sourceMappingActive) {
  17817. map.addMapping({
  17818. generated: {
  17819. line: generated.line,
  17820. column: generated.column
  17821. }
  17822. });
  17823. lastOriginalSource = null;
  17824. sourceMappingActive = false;
  17825. }
  17826. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  17827. if (chunk.charCodeAt(idx) === NEWLINE_CODE$1) {
  17828. generated.line++;
  17829. generated.column = 0;
  17830. // Mappings end at eol
  17831. if (idx + 1 === length) {
  17832. lastOriginalSource = null;
  17833. sourceMappingActive = false;
  17834. } else if (sourceMappingActive) {
  17835. map.addMapping({
  17836. source: original.source,
  17837. original: {
  17838. line: original.line,
  17839. column: original.column
  17840. },
  17841. generated: {
  17842. line: generated.line,
  17843. column: generated.column
  17844. },
  17845. name: original.name
  17846. });
  17847. }
  17848. } else {
  17849. generated.column++;
  17850. }
  17851. }
  17852. });
  17853. this.walkSourceContents(function (sourceFile, sourceContent) {
  17854. map.setSourceContent(sourceFile, sourceContent);
  17855. });
  17856. return { code: generated.code, map: map };
  17857. };
  17858. sourceNode$1.SourceNode = SourceNode$1;
  17859. /*
  17860. * Copyright 2009-2011 Mozilla Foundation and contributors
  17861. * Licensed under the New BSD license. See LICENSE.txt or:
  17862. * http://opensource.org/licenses/BSD-3-Clause
  17863. */
  17864. var SourceMapGenerator$6 = sourceMap$2.SourceMapGenerator = sourceMapGenerator$1.SourceMapGenerator;
  17865. var SourceMapConsumer$5 = sourceMap$2.SourceMapConsumer = sourceMapConsumer$1.SourceMapConsumer;
  17866. sourceMap$2.SourceNode = sourceNode$1.SourceNode;
  17867. const PURE_ANNOTATION = `/*#__PURE__*/`;
  17868. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  17869. 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 }) {
  17870. const context = {
  17871. mode,
  17872. prefixIdentifiers,
  17873. sourceMap,
  17874. filename,
  17875. scopeId,
  17876. optimizeImports,
  17877. runtimeGlobalName,
  17878. runtimeModuleName,
  17879. ssrRuntimeModuleName,
  17880. ssr,
  17881. isTS,
  17882. inSSR,
  17883. source: ast.loc.source,
  17884. code: ``,
  17885. column: 1,
  17886. line: 1,
  17887. offset: 0,
  17888. indentLevel: 0,
  17889. pure: false,
  17890. map: undefined,
  17891. helper(key) {
  17892. return `_${helperNameMap[key]}`;
  17893. },
  17894. push(code, node) {
  17895. context.code += code;
  17896. if (context.map) {
  17897. if (node) {
  17898. let name;
  17899. if (node.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !node.isStatic) {
  17900. const content = node.content.replace(/^_ctx\./, '');
  17901. if (content !== node.content && isSimpleIdentifier(content)) {
  17902. name = content;
  17903. }
  17904. }
  17905. addMapping(node.loc.start, name);
  17906. }
  17907. advancePositionWithMutation(context, code);
  17908. if (node && node.loc !== locStub) {
  17909. addMapping(node.loc.end);
  17910. }
  17911. }
  17912. },
  17913. indent() {
  17914. newline(++context.indentLevel);
  17915. },
  17916. deindent(withoutNewLine = false) {
  17917. if (withoutNewLine) {
  17918. --context.indentLevel;
  17919. }
  17920. else {
  17921. newline(--context.indentLevel);
  17922. }
  17923. },
  17924. newline() {
  17925. newline(context.indentLevel);
  17926. }
  17927. };
  17928. function newline(n) {
  17929. context.push('\n' + ` `.repeat(n));
  17930. }
  17931. function addMapping(loc, name) {
  17932. context.map.addMapping({
  17933. name,
  17934. source: context.filename,
  17935. original: {
  17936. line: loc.line,
  17937. column: loc.column - 1 // source-map column is 0 based
  17938. },
  17939. generated: {
  17940. line: context.line,
  17941. column: context.column - 1
  17942. }
  17943. });
  17944. }
  17945. if (sourceMap) {
  17946. // lazy require source-map implementation, only in non-browser builds
  17947. context.map = new SourceMapGenerator$6();
  17948. context.map.setSourceContent(filename, context.source);
  17949. }
  17950. return context;
  17951. }
  17952. function generate(ast, options = {}) {
  17953. const context = createCodegenContext(ast, options);
  17954. if (options.onContextCreated)
  17955. options.onContextCreated(context);
  17956. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  17957. const helpers = Array.from(ast.helpers);
  17958. const hasHelpers = helpers.length > 0;
  17959. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  17960. const genScopeId = scopeId != null && mode === 'module';
  17961. const isSetupInlined = !!options.inline;
  17962. // preambles
  17963. // in setup() inline mode, the preamble is generated in a sub context
  17964. // and returned separately.
  17965. const preambleContext = isSetupInlined
  17966. ? createCodegenContext(ast, options)
  17967. : context;
  17968. if (mode === 'module') {
  17969. genModulePreamble(ast, preambleContext, genScopeId, isSetupInlined);
  17970. }
  17971. else {
  17972. genFunctionPreamble(ast, preambleContext);
  17973. }
  17974. // enter render function
  17975. const functionName = ssr ? `ssrRender` : `render`;
  17976. const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
  17977. if (options.bindingMetadata && !options.inline) {
  17978. // binding optimization args
  17979. args.push('$props', '$setup', '$data', '$options');
  17980. }
  17981. const signature = options.isTS
  17982. ? args.map(arg => `${arg}: any`).join(',')
  17983. : args.join(', ');
  17984. if (isSetupInlined) {
  17985. push(`(${signature}) => {`);
  17986. }
  17987. else {
  17988. push(`function ${functionName}(${signature}) {`);
  17989. }
  17990. indent();
  17991. if (useWithBlock) {
  17992. push(`with (_ctx) {`);
  17993. indent();
  17994. // function mode const declarations should be inside with block
  17995. // also they should be renamed to avoid collision with user properties
  17996. if (hasHelpers) {
  17997. push(`const { ${helpers.map(aliasHelper).join(', ')} } = _Vue`);
  17998. push(`\n`);
  17999. newline();
  18000. }
  18001. }
  18002. // generate asset resolution statements
  18003. if (ast.components.length) {
  18004. genAssets(ast.components, 'component', context);
  18005. if (ast.directives.length || ast.temps > 0) {
  18006. newline();
  18007. }
  18008. }
  18009. if (ast.directives.length) {
  18010. genAssets(ast.directives, 'directive', context);
  18011. if (ast.temps > 0) {
  18012. newline();
  18013. }
  18014. }
  18015. if (ast.temps > 0) {
  18016. push(`let `);
  18017. for (let i = 0; i < ast.temps; i++) {
  18018. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  18019. }
  18020. }
  18021. if (ast.components.length || ast.directives.length || ast.temps) {
  18022. push(`\n`);
  18023. newline();
  18024. }
  18025. // generate the VNode tree expression
  18026. if (!ssr) {
  18027. push(`return `);
  18028. }
  18029. if (ast.codegenNode) {
  18030. genNode(ast.codegenNode, context);
  18031. }
  18032. else {
  18033. push(`null`);
  18034. }
  18035. if (useWithBlock) {
  18036. deindent();
  18037. push(`}`);
  18038. }
  18039. deindent();
  18040. push(`}`);
  18041. return {
  18042. ast,
  18043. code: context.code,
  18044. preamble: isSetupInlined ? preambleContext.code : ``,
  18045. // SourceMapGenerator does have toJSON() method but it's not in the types
  18046. map: context.map ? context.map.toJSON() : undefined
  18047. };
  18048. }
  18049. function genFunctionPreamble(ast, context) {
  18050. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
  18051. const VueBinding = ssr
  18052. ? `require(${JSON.stringify(runtimeModuleName)})`
  18053. : runtimeGlobalName;
  18054. // Generate const declaration for helpers
  18055. // In prefix mode, we place the const declaration at top so it's done
  18056. // only once; But if we not prefixing, we place the declaration inside the
  18057. // with block so it doesn't incur the `in` check cost for every helper access.
  18058. const helpers = Array.from(ast.helpers);
  18059. if (helpers.length > 0) {
  18060. if (prefixIdentifiers) {
  18061. push(`const { ${helpers.map(aliasHelper).join(', ')} } = ${VueBinding}\n`);
  18062. }
  18063. else {
  18064. // "with" mode.
  18065. // save Vue in a separate variable to avoid collision
  18066. push(`const _Vue = ${VueBinding}\n`);
  18067. // in "with" mode, helpers are declared inside the with block to avoid
  18068. // has check cost, but hoists are lifted out of the function - we need
  18069. // to provide the helper here.
  18070. if (ast.hoists.length) {
  18071. const staticHelpers = [
  18072. CREATE_VNODE,
  18073. CREATE_ELEMENT_VNODE,
  18074. CREATE_COMMENT,
  18075. CREATE_TEXT,
  18076. CREATE_STATIC
  18077. ]
  18078. .filter(helper => helpers.includes(helper))
  18079. .map(aliasHelper)
  18080. .join(', ');
  18081. push(`const { ${staticHelpers} } = _Vue\n`);
  18082. }
  18083. }
  18084. }
  18085. // generate variables for ssr helpers
  18086. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  18087. // ssr guarantees prefixIdentifier: true
  18088. push(`const { ${ast.ssrHelpers
  18089. .map(aliasHelper)
  18090. .join(', ')} } = require("${ssrRuntimeModuleName}")\n`);
  18091. }
  18092. genHoists(ast.hoists, context);
  18093. newline();
  18094. push(`return `);
  18095. }
  18096. function genModulePreamble(ast, context, genScopeId, inline) {
  18097. const { push, newline, optimizeImports, runtimeModuleName, ssrRuntimeModuleName } = context;
  18098. if (genScopeId && ast.hoists.length) {
  18099. ast.helpers.add(PUSH_SCOPE_ID);
  18100. ast.helpers.add(POP_SCOPE_ID);
  18101. }
  18102. // generate import statements for helpers
  18103. if (ast.helpers.size) {
  18104. const helpers = Array.from(ast.helpers);
  18105. if (optimizeImports) {
  18106. // when bundled with webpack with code-split, calling an import binding
  18107. // as a function leads to it being wrapped with `Object(a.b)` or `(0,a.b)`,
  18108. // incurring both payload size increase and potential perf overhead.
  18109. // therefore we assign the imports to variables (which is a constant ~50b
  18110. // cost per-component instead of scaling with template size)
  18111. push(`import { ${helpers
  18112. .map(s => helperNameMap[s])
  18113. .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
  18114. push(`\n// Binding optimization for webpack code-split\nconst ${helpers
  18115. .map(s => `_${helperNameMap[s]} = ${helperNameMap[s]}`)
  18116. .join(', ')}\n`);
  18117. }
  18118. else {
  18119. push(`import { ${helpers
  18120. .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
  18121. .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
  18122. }
  18123. }
  18124. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  18125. push(`import { ${ast.ssrHelpers
  18126. .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
  18127. .join(', ')} } from "${ssrRuntimeModuleName}"\n`);
  18128. }
  18129. if (ast.imports.length) {
  18130. genImports(ast.imports, context);
  18131. newline();
  18132. }
  18133. genHoists(ast.hoists, context);
  18134. newline();
  18135. if (!inline) {
  18136. push(`export `);
  18137. }
  18138. }
  18139. function genAssets(assets, type, { helper, push, newline, isTS }) {
  18140. const resolver = helper(type === 'component'
  18141. ? RESOLVE_COMPONENT
  18142. : RESOLVE_DIRECTIVE);
  18143. for (let i = 0; i < assets.length; i++) {
  18144. let id = assets[i];
  18145. // potential component implicit self-reference inferred from SFC filename
  18146. const maybeSelfReference = id.endsWith('__self');
  18147. if (maybeSelfReference) {
  18148. id = id.slice(0, -6);
  18149. }
  18150. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
  18151. if (i < assets.length - 1) {
  18152. newline();
  18153. }
  18154. }
  18155. }
  18156. function genHoists(hoists, context) {
  18157. if (!hoists.length) {
  18158. return;
  18159. }
  18160. context.pure = true;
  18161. const { push, newline, helper, scopeId, mode } = context;
  18162. const genScopeId = scopeId != null && mode !== 'function';
  18163. newline();
  18164. // generate inlined withScopeId helper
  18165. if (genScopeId) {
  18166. push(`const _withScopeId = n => (${helper(PUSH_SCOPE_ID)}("${scopeId}"),n=n(),${helper(POP_SCOPE_ID)}(),n)`);
  18167. newline();
  18168. }
  18169. for (let i = 0; i < hoists.length; i++) {
  18170. const exp = hoists[i];
  18171. if (exp) {
  18172. const needScopeIdWrapper = genScopeId && exp.type === 13 /* NodeTypes.VNODE_CALL */;
  18173. push(`const _hoisted_${i + 1} = ${needScopeIdWrapper ? `${PURE_ANNOTATION} _withScopeId(() => ` : ``}`);
  18174. genNode(exp, context);
  18175. if (needScopeIdWrapper) {
  18176. push(`)`);
  18177. }
  18178. newline();
  18179. }
  18180. }
  18181. context.pure = false;
  18182. }
  18183. function genImports(importsOptions, context) {
  18184. if (!importsOptions.length) {
  18185. return;
  18186. }
  18187. importsOptions.forEach(imports => {
  18188. context.push(`import `);
  18189. genNode(imports.exp, context);
  18190. context.push(` from '${imports.path}'`);
  18191. context.newline();
  18192. });
  18193. }
  18194. function isText(n) {
  18195. return (isString$2(n) ||
  18196. n.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  18197. n.type === 2 /* NodeTypes.TEXT */ ||
  18198. n.type === 5 /* NodeTypes.INTERPOLATION */ ||
  18199. n.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */);
  18200. }
  18201. function genNodeListAsArray(nodes, context) {
  18202. const multilines = nodes.length > 3 ||
  18203. (nodes.some(n => isArray$3(n) || !isText(n)));
  18204. context.push(`[`);
  18205. multilines && context.indent();
  18206. genNodeList(nodes, context, multilines);
  18207. multilines && context.deindent();
  18208. context.push(`]`);
  18209. }
  18210. function genNodeList(nodes, context, multilines = false, comma = true) {
  18211. const { push, newline } = context;
  18212. for (let i = 0; i < nodes.length; i++) {
  18213. const node = nodes[i];
  18214. if (isString$2(node)) {
  18215. push(node);
  18216. }
  18217. else if (isArray$3(node)) {
  18218. genNodeListAsArray(node, context);
  18219. }
  18220. else {
  18221. genNode(node, context);
  18222. }
  18223. if (i < nodes.length - 1) {
  18224. if (multilines) {
  18225. comma && push(',');
  18226. newline();
  18227. }
  18228. else {
  18229. comma && push(', ');
  18230. }
  18231. }
  18232. }
  18233. }
  18234. function genNode(node, context) {
  18235. if (isString$2(node)) {
  18236. context.push(node);
  18237. return;
  18238. }
  18239. if (isSymbol$1(node)) {
  18240. context.push(context.helper(node));
  18241. return;
  18242. }
  18243. switch (node.type) {
  18244. case 1 /* NodeTypes.ELEMENT */:
  18245. case 9 /* NodeTypes.IF */:
  18246. case 11 /* NodeTypes.FOR */:
  18247. assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  18248. `Apply appropriate transforms first.`);
  18249. genNode(node.codegenNode, context);
  18250. break;
  18251. case 2 /* NodeTypes.TEXT */:
  18252. genText(node, context);
  18253. break;
  18254. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  18255. genExpression(node, context);
  18256. break;
  18257. case 5 /* NodeTypes.INTERPOLATION */:
  18258. genInterpolation(node, context);
  18259. break;
  18260. case 12 /* NodeTypes.TEXT_CALL */:
  18261. genNode(node.codegenNode, context);
  18262. break;
  18263. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  18264. genCompoundExpression(node, context);
  18265. break;
  18266. case 3 /* NodeTypes.COMMENT */:
  18267. genComment(node, context);
  18268. break;
  18269. case 13 /* NodeTypes.VNODE_CALL */:
  18270. genVNodeCall(node, context);
  18271. break;
  18272. case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
  18273. genCallExpression(node, context);
  18274. break;
  18275. case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
  18276. genObjectExpression(node, context);
  18277. break;
  18278. case 17 /* NodeTypes.JS_ARRAY_EXPRESSION */:
  18279. genArrayExpression(node, context);
  18280. break;
  18281. case 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */:
  18282. genFunctionExpression(node, context);
  18283. break;
  18284. case 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */:
  18285. genConditionalExpression(node, context);
  18286. break;
  18287. case 20 /* NodeTypes.JS_CACHE_EXPRESSION */:
  18288. genCacheExpression(node, context);
  18289. break;
  18290. case 21 /* NodeTypes.JS_BLOCK_STATEMENT */:
  18291. genNodeList(node.body, context, true, false);
  18292. break;
  18293. // SSR only types
  18294. case 22 /* NodeTypes.JS_TEMPLATE_LITERAL */:
  18295. genTemplateLiteral(node, context);
  18296. break;
  18297. case 23 /* NodeTypes.JS_IF_STATEMENT */:
  18298. genIfStatement(node, context);
  18299. break;
  18300. case 24 /* NodeTypes.JS_ASSIGNMENT_EXPRESSION */:
  18301. genAssignmentExpression(node, context);
  18302. break;
  18303. case 25 /* NodeTypes.JS_SEQUENCE_EXPRESSION */:
  18304. genSequenceExpression(node, context);
  18305. break;
  18306. case 26 /* NodeTypes.JS_RETURN_STATEMENT */:
  18307. genReturnStatement(node, context);
  18308. break;
  18309. /* istanbul ignore next */
  18310. case 10 /* NodeTypes.IF_BRANCH */:
  18311. // noop
  18312. break;
  18313. default:
  18314. {
  18315. assert(false, `unhandled codegen node type: ${node.type}`);
  18316. // make sure we exhaust all possible types
  18317. const exhaustiveCheck = node;
  18318. return exhaustiveCheck;
  18319. }
  18320. }
  18321. }
  18322. function genText(node, context) {
  18323. context.push(JSON.stringify(node.content), node);
  18324. }
  18325. function genExpression(node, context) {
  18326. const { content, isStatic } = node;
  18327. context.push(isStatic ? JSON.stringify(content) : content, node);
  18328. }
  18329. function genInterpolation(node, context) {
  18330. const { push, helper, pure } = context;
  18331. if (pure)
  18332. push(PURE_ANNOTATION);
  18333. push(`${helper(TO_DISPLAY_STRING)}(`);
  18334. genNode(node.content, context);
  18335. push(`)`);
  18336. }
  18337. function genCompoundExpression(node, context) {
  18338. for (let i = 0; i < node.children.length; i++) {
  18339. const child = node.children[i];
  18340. if (isString$2(child)) {
  18341. context.push(child);
  18342. }
  18343. else {
  18344. genNode(child, context);
  18345. }
  18346. }
  18347. }
  18348. function genExpressionAsPropertyKey(node, context) {
  18349. const { push } = context;
  18350. if (node.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  18351. push(`[`);
  18352. genCompoundExpression(node, context);
  18353. push(`]`);
  18354. }
  18355. else if (node.isStatic) {
  18356. // only quote keys if necessary
  18357. const text = isSimpleIdentifier(node.content)
  18358. ? node.content
  18359. : JSON.stringify(node.content);
  18360. push(text, node);
  18361. }
  18362. else {
  18363. push(`[${node.content}]`, node);
  18364. }
  18365. }
  18366. function genComment(node, context) {
  18367. const { push, helper, pure } = context;
  18368. if (pure) {
  18369. push(PURE_ANNOTATION);
  18370. }
  18371. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  18372. }
  18373. function genVNodeCall(node, context) {
  18374. const { push, helper, pure } = context;
  18375. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
  18376. if (directives) {
  18377. push(helper(WITH_DIRECTIVES) + `(`);
  18378. }
  18379. if (isBlock) {
  18380. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  18381. }
  18382. if (pure) {
  18383. push(PURE_ANNOTATION);
  18384. }
  18385. const callHelper = isBlock
  18386. ? getVNodeBlockHelper(context.inSSR, isComponent)
  18387. : getVNodeHelper(context.inSSR, isComponent);
  18388. push(helper(callHelper) + `(`, node);
  18389. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  18390. push(`)`);
  18391. if (isBlock) {
  18392. push(`)`);
  18393. }
  18394. if (directives) {
  18395. push(`, `);
  18396. genNode(directives, context);
  18397. push(`)`);
  18398. }
  18399. }
  18400. function genNullableArgs(args) {
  18401. let i = args.length;
  18402. while (i--) {
  18403. if (args[i] != null)
  18404. break;
  18405. }
  18406. return args.slice(0, i + 1).map(arg => arg || `null`);
  18407. }
  18408. // JavaScript
  18409. function genCallExpression(node, context) {
  18410. const { push, helper, pure } = context;
  18411. const callee = isString$2(node.callee) ? node.callee : helper(node.callee);
  18412. if (pure) {
  18413. push(PURE_ANNOTATION);
  18414. }
  18415. push(callee + `(`, node);
  18416. genNodeList(node.arguments, context);
  18417. push(`)`);
  18418. }
  18419. function genObjectExpression(node, context) {
  18420. const { push, indent, deindent, newline } = context;
  18421. const { properties } = node;
  18422. if (!properties.length) {
  18423. push(`{}`, node);
  18424. return;
  18425. }
  18426. const multilines = properties.length > 1 ||
  18427. (properties.some(p => p.value.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */));
  18428. push(multilines ? `{` : `{ `);
  18429. multilines && indent();
  18430. for (let i = 0; i < properties.length; i++) {
  18431. const { key, value } = properties[i];
  18432. // key
  18433. genExpressionAsPropertyKey(key, context);
  18434. push(`: `);
  18435. // value
  18436. genNode(value, context);
  18437. if (i < properties.length - 1) {
  18438. // will only reach this if it's multilines
  18439. push(`,`);
  18440. newline();
  18441. }
  18442. }
  18443. multilines && deindent();
  18444. push(multilines ? `}` : ` }`);
  18445. }
  18446. function genArrayExpression(node, context) {
  18447. genNodeListAsArray(node.elements, context);
  18448. }
  18449. function genFunctionExpression(node, context) {
  18450. const { push, indent, deindent } = context;
  18451. const { params, returns, body, newline, isSlot } = node;
  18452. if (isSlot) {
  18453. // wrap slot functions with owner context
  18454. push(`_${helperNameMap[WITH_CTX]}(`);
  18455. }
  18456. push(`(`, node);
  18457. if (isArray$3(params)) {
  18458. genNodeList(params, context);
  18459. }
  18460. else if (params) {
  18461. genNode(params, context);
  18462. }
  18463. push(`) => `);
  18464. if (newline || body) {
  18465. push(`{`);
  18466. indent();
  18467. }
  18468. if (returns) {
  18469. if (newline) {
  18470. push(`return `);
  18471. }
  18472. if (isArray$3(returns)) {
  18473. genNodeListAsArray(returns, context);
  18474. }
  18475. else {
  18476. genNode(returns, context);
  18477. }
  18478. }
  18479. else if (body) {
  18480. genNode(body, context);
  18481. }
  18482. if (newline || body) {
  18483. deindent();
  18484. push(`}`);
  18485. }
  18486. if (isSlot) {
  18487. push(`)`);
  18488. }
  18489. }
  18490. function genConditionalExpression(node, context) {
  18491. const { test, consequent, alternate, newline: needNewline } = node;
  18492. const { push, indent, deindent, newline } = context;
  18493. if (test.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  18494. const needsParens = !isSimpleIdentifier(test.content);
  18495. needsParens && push(`(`);
  18496. genExpression(test, context);
  18497. needsParens && push(`)`);
  18498. }
  18499. else {
  18500. push(`(`);
  18501. genNode(test, context);
  18502. push(`)`);
  18503. }
  18504. needNewline && indent();
  18505. context.indentLevel++;
  18506. needNewline || push(` `);
  18507. push(`? `);
  18508. genNode(consequent, context);
  18509. context.indentLevel--;
  18510. needNewline && newline();
  18511. needNewline || push(` `);
  18512. push(`: `);
  18513. const isNested = alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */;
  18514. if (!isNested) {
  18515. context.indentLevel++;
  18516. }
  18517. genNode(alternate, context);
  18518. if (!isNested) {
  18519. context.indentLevel--;
  18520. }
  18521. needNewline && deindent(true /* without newline */);
  18522. }
  18523. function genCacheExpression(node, context) {
  18524. const { push, helper, indent, deindent, newline } = context;
  18525. push(`_cache[${node.index}] || (`);
  18526. if (node.isVNode) {
  18527. indent();
  18528. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  18529. newline();
  18530. }
  18531. push(`_cache[${node.index}] = `);
  18532. genNode(node.value, context);
  18533. if (node.isVNode) {
  18534. push(`,`);
  18535. newline();
  18536. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  18537. newline();
  18538. push(`_cache[${node.index}]`);
  18539. deindent();
  18540. }
  18541. push(`)`);
  18542. }
  18543. function genTemplateLiteral(node, context) {
  18544. const { push, indent, deindent } = context;
  18545. push('`');
  18546. const l = node.elements.length;
  18547. const multilines = l > 3;
  18548. for (let i = 0; i < l; i++) {
  18549. const e = node.elements[i];
  18550. if (isString$2(e)) {
  18551. push(e.replace(/(`|\$|\\)/g, '\\$1'));
  18552. }
  18553. else {
  18554. push('${');
  18555. if (multilines)
  18556. indent();
  18557. genNode(e, context);
  18558. if (multilines)
  18559. deindent();
  18560. push('}');
  18561. }
  18562. }
  18563. push('`');
  18564. }
  18565. function genIfStatement(node, context) {
  18566. const { push, indent, deindent } = context;
  18567. const { test, consequent, alternate } = node;
  18568. push(`if (`);
  18569. genNode(test, context);
  18570. push(`) {`);
  18571. indent();
  18572. genNode(consequent, context);
  18573. deindent();
  18574. push(`}`);
  18575. if (alternate) {
  18576. push(` else `);
  18577. if (alternate.type === 23 /* NodeTypes.JS_IF_STATEMENT */) {
  18578. genIfStatement(alternate, context);
  18579. }
  18580. else {
  18581. push(`{`);
  18582. indent();
  18583. genNode(alternate, context);
  18584. deindent();
  18585. push(`}`);
  18586. }
  18587. }
  18588. }
  18589. function genAssignmentExpression(node, context) {
  18590. genNode(node.left, context);
  18591. context.push(` = `);
  18592. genNode(node.right, context);
  18593. }
  18594. function genSequenceExpression(node, context) {
  18595. context.push(`(`);
  18596. genNodeList(node.expressions, context);
  18597. context.push(`)`);
  18598. }
  18599. function genReturnStatement({ returns }, context) {
  18600. context.push(`return `);
  18601. if (isArray$3(returns)) {
  18602. genNodeListAsArray(returns, context);
  18603. }
  18604. else {
  18605. genNode(returns, context);
  18606. }
  18607. }
  18608. // @ts-check
  18609. /** @typedef { import('estree').BaseNode} BaseNode */
  18610. /** @typedef {{
  18611. skip: () => void;
  18612. remove: () => void;
  18613. replace: (node: BaseNode) => void;
  18614. }} WalkerContext */
  18615. class WalkerBase {
  18616. constructor() {
  18617. /** @type {boolean} */
  18618. this.should_skip = false;
  18619. /** @type {boolean} */
  18620. this.should_remove = false;
  18621. /** @type {BaseNode | null} */
  18622. this.replacement = null;
  18623. /** @type {WalkerContext} */
  18624. this.context = {
  18625. skip: () => (this.should_skip = true),
  18626. remove: () => (this.should_remove = true),
  18627. replace: (node) => (this.replacement = node)
  18628. };
  18629. }
  18630. /**
  18631. *
  18632. * @param {any} parent
  18633. * @param {string} prop
  18634. * @param {number} index
  18635. * @param {BaseNode} node
  18636. */
  18637. replace(parent, prop, index, node) {
  18638. if (parent) {
  18639. if (index !== null) {
  18640. parent[prop][index] = node;
  18641. } else {
  18642. parent[prop] = node;
  18643. }
  18644. }
  18645. }
  18646. /**
  18647. *
  18648. * @param {any} parent
  18649. * @param {string} prop
  18650. * @param {number} index
  18651. */
  18652. remove(parent, prop, index) {
  18653. if (parent) {
  18654. if (index !== null) {
  18655. parent[prop].splice(index, 1);
  18656. } else {
  18657. delete parent[prop];
  18658. }
  18659. }
  18660. }
  18661. }
  18662. // @ts-check
  18663. /** @typedef { import('estree').BaseNode} BaseNode */
  18664. /** @typedef { import('./walker.js').WalkerContext} WalkerContext */
  18665. /** @typedef {(
  18666. * this: WalkerContext,
  18667. * node: BaseNode,
  18668. * parent: BaseNode,
  18669. * key: string,
  18670. * index: number
  18671. * ) => void} SyncHandler */
  18672. class SyncWalker extends WalkerBase {
  18673. /**
  18674. *
  18675. * @param {SyncHandler} enter
  18676. * @param {SyncHandler} leave
  18677. */
  18678. constructor(enter, leave) {
  18679. super();
  18680. /** @type {SyncHandler} */
  18681. this.enter = enter;
  18682. /** @type {SyncHandler} */
  18683. this.leave = leave;
  18684. }
  18685. /**
  18686. *
  18687. * @param {BaseNode} node
  18688. * @param {BaseNode} parent
  18689. * @param {string} [prop]
  18690. * @param {number} [index]
  18691. * @returns {BaseNode}
  18692. */
  18693. visit(node, parent, prop, index) {
  18694. if (node) {
  18695. if (this.enter) {
  18696. const _should_skip = this.should_skip;
  18697. const _should_remove = this.should_remove;
  18698. const _replacement = this.replacement;
  18699. this.should_skip = false;
  18700. this.should_remove = false;
  18701. this.replacement = null;
  18702. this.enter.call(this.context, node, parent, prop, index);
  18703. if (this.replacement) {
  18704. node = this.replacement;
  18705. this.replace(parent, prop, index, node);
  18706. }
  18707. if (this.should_remove) {
  18708. this.remove(parent, prop, index);
  18709. }
  18710. const skipped = this.should_skip;
  18711. const removed = this.should_remove;
  18712. this.should_skip = _should_skip;
  18713. this.should_remove = _should_remove;
  18714. this.replacement = _replacement;
  18715. if (skipped) return node;
  18716. if (removed) return null;
  18717. }
  18718. for (const key in node) {
  18719. const value = node[key];
  18720. if (typeof value !== "object") {
  18721. continue;
  18722. } else if (Array.isArray(value)) {
  18723. for (let i = 0; i < value.length; i += 1) {
  18724. if (value[i] !== null && typeof value[i].type === 'string') {
  18725. if (!this.visit(value[i], node, key, i)) {
  18726. // removed
  18727. i--;
  18728. }
  18729. }
  18730. }
  18731. } else if (value !== null && typeof value.type === "string") {
  18732. this.visit(value, node, key, null);
  18733. }
  18734. }
  18735. if (this.leave) {
  18736. const _replacement = this.replacement;
  18737. const _should_remove = this.should_remove;
  18738. this.replacement = null;
  18739. this.should_remove = false;
  18740. this.leave.call(this.context, node, parent, prop, index);
  18741. if (this.replacement) {
  18742. node = this.replacement;
  18743. this.replace(parent, prop, index, node);
  18744. }
  18745. if (this.should_remove) {
  18746. this.remove(parent, prop, index);
  18747. }
  18748. const removed = this.should_remove;
  18749. this.replacement = _replacement;
  18750. this.should_remove = _should_remove;
  18751. if (removed) return null;
  18752. }
  18753. }
  18754. return node;
  18755. }
  18756. }
  18757. // @ts-check
  18758. /** @typedef { import('estree').BaseNode} BaseNode */
  18759. /** @typedef { import('./sync.js').SyncHandler} SyncHandler */
  18760. /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
  18761. /**
  18762. *
  18763. * @param {BaseNode} ast
  18764. * @param {{
  18765. * enter?: SyncHandler
  18766. * leave?: SyncHandler
  18767. * }} walker
  18768. * @returns {BaseNode}
  18769. */
  18770. function walk$1(ast, { enter, leave }) {
  18771. const instance = new SyncWalker(enter, leave);
  18772. return instance.visit(ast, null);
  18773. }
  18774. function walkIdentifiers(root, onIdentifier, includeAll = false, parentStack = [], knownIds = Object.create(null)) {
  18775. const rootExp = root.type === 'Program' &&
  18776. root.body[0].type === 'ExpressionStatement' &&
  18777. root.body[0].expression;
  18778. walk$1(root, {
  18779. enter(node, parent) {
  18780. parent && parentStack.push(parent);
  18781. if (parent &&
  18782. parent.type.startsWith('TS') &&
  18783. parent.type !== 'TSAsExpression' &&
  18784. parent.type !== 'TSNonNullExpression' &&
  18785. parent.type !== 'TSTypeAssertion') {
  18786. return this.skip();
  18787. }
  18788. if (node.type === 'Identifier') {
  18789. const isLocal = !!knownIds[node.name];
  18790. const isRefed = isReferencedIdentifier(node, parent, parentStack);
  18791. if (includeAll || (isRefed && !isLocal)) {
  18792. onIdentifier(node, parent, parentStack, isRefed, isLocal);
  18793. }
  18794. }
  18795. else if (node.type === 'ObjectProperty' &&
  18796. parent.type === 'ObjectPattern') {
  18797. node.inPattern = true;
  18798. }
  18799. else if (isFunctionType(node)) {
  18800. // walk function expressions and add its arguments to known identifiers
  18801. // so that we don't prefix them
  18802. walkFunctionParams(node, id => markScopeIdentifier(node, id, knownIds));
  18803. }
  18804. else if (node.type === 'BlockStatement') {
  18805. // #3445 record block-level local variables
  18806. walkBlockDeclarations(node, id => markScopeIdentifier(node, id, knownIds));
  18807. }
  18808. },
  18809. leave(node, parent) {
  18810. parent && parentStack.pop();
  18811. if (node !== rootExp && node.scopeIds) {
  18812. for (const id of node.scopeIds) {
  18813. knownIds[id]--;
  18814. if (knownIds[id] === 0) {
  18815. delete knownIds[id];
  18816. }
  18817. }
  18818. }
  18819. }
  18820. });
  18821. }
  18822. function isReferencedIdentifier(id, parent, parentStack) {
  18823. if (!parent) {
  18824. return true;
  18825. }
  18826. // is a special keyword but parsed as identifier
  18827. if (id.name === 'arguments') {
  18828. return false;
  18829. }
  18830. if (isReferenced(id, parent)) {
  18831. return true;
  18832. }
  18833. // babel's isReferenced check returns false for ids being assigned to, so we
  18834. // need to cover those cases here
  18835. switch (parent.type) {
  18836. case 'AssignmentExpression':
  18837. case 'AssignmentPattern':
  18838. return true;
  18839. case 'ObjectPattern':
  18840. case 'ArrayPattern':
  18841. return isInDestructureAssignment(parent, parentStack);
  18842. }
  18843. return false;
  18844. }
  18845. function isInDestructureAssignment(parent, parentStack) {
  18846. if (parent &&
  18847. (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')) {
  18848. let i = parentStack.length;
  18849. while (i--) {
  18850. const p = parentStack[i];
  18851. if (p.type === 'AssignmentExpression') {
  18852. return true;
  18853. }
  18854. else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
  18855. break;
  18856. }
  18857. }
  18858. }
  18859. return false;
  18860. }
  18861. function walkFunctionParams(node, onIdent) {
  18862. for (const p of node.params) {
  18863. for (const id of extractIdentifiers(p)) {
  18864. onIdent(id);
  18865. }
  18866. }
  18867. }
  18868. function walkBlockDeclarations(block, onIdent) {
  18869. for (const stmt of block.body) {
  18870. if (stmt.type === 'VariableDeclaration') {
  18871. if (stmt.declare)
  18872. continue;
  18873. for (const decl of stmt.declarations) {
  18874. for (const id of extractIdentifiers(decl.id)) {
  18875. onIdent(id);
  18876. }
  18877. }
  18878. }
  18879. else if (stmt.type === 'FunctionDeclaration' ||
  18880. stmt.type === 'ClassDeclaration') {
  18881. if (stmt.declare || !stmt.id)
  18882. continue;
  18883. onIdent(stmt.id);
  18884. }
  18885. }
  18886. }
  18887. function extractIdentifiers(param, nodes = []) {
  18888. switch (param.type) {
  18889. case 'Identifier':
  18890. nodes.push(param);
  18891. break;
  18892. case 'MemberExpression':
  18893. let object = param;
  18894. while (object.type === 'MemberExpression') {
  18895. object = object.object;
  18896. }
  18897. nodes.push(object);
  18898. break;
  18899. case 'ObjectPattern':
  18900. for (const prop of param.properties) {
  18901. if (prop.type === 'RestElement') {
  18902. extractIdentifiers(prop.argument, nodes);
  18903. }
  18904. else {
  18905. extractIdentifiers(prop.value, nodes);
  18906. }
  18907. }
  18908. break;
  18909. case 'ArrayPattern':
  18910. param.elements.forEach(element => {
  18911. if (element)
  18912. extractIdentifiers(element, nodes);
  18913. });
  18914. break;
  18915. case 'RestElement':
  18916. extractIdentifiers(param.argument, nodes);
  18917. break;
  18918. case 'AssignmentPattern':
  18919. extractIdentifiers(param.left, nodes);
  18920. break;
  18921. }
  18922. return nodes;
  18923. }
  18924. function markScopeIdentifier(node, child, knownIds) {
  18925. const { name } = child;
  18926. if (node.scopeIds && node.scopeIds.has(name)) {
  18927. return;
  18928. }
  18929. if (name in knownIds) {
  18930. knownIds[name]++;
  18931. }
  18932. else {
  18933. knownIds[name] = 1;
  18934. }
  18935. (node.scopeIds || (node.scopeIds = new Set())).add(name);
  18936. }
  18937. const isFunctionType = (node) => {
  18938. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  18939. };
  18940. const isStaticProperty = (node) => node &&
  18941. (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
  18942. !node.computed;
  18943. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  18944. /**
  18945. * Copied from https://github.com/babel/babel/blob/main/packages/babel-types/src/validators/isReferenced.ts
  18946. * To avoid runtime dependency on @babel/types (which includes process references)
  18947. * This file should not change very often in babel but we may need to keep it
  18948. * up-to-date from time to time.
  18949. *
  18950. * https://github.com/babel/babel/blob/main/LICENSE
  18951. *
  18952. */
  18953. function isReferenced(node, parent, grandparent) {
  18954. switch (parent.type) {
  18955. // yes: PARENT[NODE]
  18956. // yes: NODE.child
  18957. // no: parent.NODE
  18958. case 'MemberExpression':
  18959. case 'OptionalMemberExpression':
  18960. if (parent.property === node) {
  18961. return !!parent.computed;
  18962. }
  18963. return parent.object === node;
  18964. case 'JSXMemberExpression':
  18965. return parent.object === node;
  18966. // no: let NODE = init;
  18967. // yes: let id = NODE;
  18968. case 'VariableDeclarator':
  18969. return parent.init === node;
  18970. // yes: () => NODE
  18971. // no: (NODE) => {}
  18972. case 'ArrowFunctionExpression':
  18973. return parent.body === node;
  18974. // no: class { #NODE; }
  18975. // no: class { get #NODE() {} }
  18976. // no: class { #NODE() {} }
  18977. // no: class { fn() { return this.#NODE; } }
  18978. case 'PrivateName':
  18979. return false;
  18980. // no: class { NODE() {} }
  18981. // yes: class { [NODE]() {} }
  18982. // no: class { foo(NODE) {} }
  18983. case 'ClassMethod':
  18984. case 'ClassPrivateMethod':
  18985. case 'ObjectMethod':
  18986. if (parent.key === node) {
  18987. return !!parent.computed;
  18988. }
  18989. return false;
  18990. // yes: { [NODE]: "" }
  18991. // no: { NODE: "" }
  18992. // depends: { NODE }
  18993. // depends: { key: NODE }
  18994. case 'ObjectProperty':
  18995. if (parent.key === node) {
  18996. return !!parent.computed;
  18997. }
  18998. // parent.value === node
  18999. return !grandparent || grandparent.type !== 'ObjectPattern';
  19000. // no: class { NODE = value; }
  19001. // yes: class { [NODE] = value; }
  19002. // yes: class { key = NODE; }
  19003. case 'ClassProperty':
  19004. if (parent.key === node) {
  19005. return !!parent.computed;
  19006. }
  19007. return true;
  19008. case 'ClassPrivateProperty':
  19009. return parent.key !== node;
  19010. // no: class NODE {}
  19011. // yes: class Foo extends NODE {}
  19012. case 'ClassDeclaration':
  19013. case 'ClassExpression':
  19014. return parent.superClass === node;
  19015. // yes: left = NODE;
  19016. // no: NODE = right;
  19017. case 'AssignmentExpression':
  19018. return parent.right === node;
  19019. // no: [NODE = foo] = [];
  19020. // yes: [foo = NODE] = [];
  19021. case 'AssignmentPattern':
  19022. return parent.right === node;
  19023. // no: NODE: for (;;) {}
  19024. case 'LabeledStatement':
  19025. return false;
  19026. // no: try {} catch (NODE) {}
  19027. case 'CatchClause':
  19028. return false;
  19029. // no: function foo(...NODE) {}
  19030. case 'RestElement':
  19031. return false;
  19032. case 'BreakStatement':
  19033. case 'ContinueStatement':
  19034. return false;
  19035. // no: function NODE() {}
  19036. // no: function foo(NODE) {}
  19037. case 'FunctionDeclaration':
  19038. case 'FunctionExpression':
  19039. return false;
  19040. // no: export NODE from "foo";
  19041. // no: export * as NODE from "foo";
  19042. case 'ExportNamespaceSpecifier':
  19043. case 'ExportDefaultSpecifier':
  19044. return false;
  19045. // no: export { foo as NODE };
  19046. // yes: export { NODE as foo };
  19047. // no: export { NODE as foo } from "foo";
  19048. case 'ExportSpecifier':
  19049. // @ts-expect-error
  19050. if (grandparent === null || grandparent === void 0 ? void 0 : grandparent.source) {
  19051. return false;
  19052. }
  19053. return parent.local === node;
  19054. // no: import NODE from "foo";
  19055. // no: import * as NODE from "foo";
  19056. // no: import { NODE as foo } from "foo";
  19057. // no: import { foo as NODE } from "foo";
  19058. // no: import NODE from "bar";
  19059. case 'ImportDefaultSpecifier':
  19060. case 'ImportNamespaceSpecifier':
  19061. case 'ImportSpecifier':
  19062. return false;
  19063. // no: import "foo" assert { NODE: "json" }
  19064. case 'ImportAttribute':
  19065. return false;
  19066. // no: <div NODE="foo" />
  19067. case 'JSXAttribute':
  19068. return false;
  19069. // no: [NODE] = [];
  19070. // no: ({ NODE }) = [];
  19071. case 'ObjectPattern':
  19072. case 'ArrayPattern':
  19073. return false;
  19074. // no: new.NODE
  19075. // no: NODE.target
  19076. case 'MetaProperty':
  19077. return false;
  19078. // yes: type X = { someProperty: NODE }
  19079. // no: type X = { NODE: OtherType }
  19080. case 'ObjectTypeProperty':
  19081. return parent.key !== node;
  19082. // yes: enum X { Foo = NODE }
  19083. // no: enum X { NODE }
  19084. case 'TSEnumMember':
  19085. return parent.id !== node;
  19086. // yes: { [NODE]: value }
  19087. // no: { NODE: value }
  19088. case 'TSPropertySignature':
  19089. if (parent.key === node) {
  19090. return !!parent.computed;
  19091. }
  19092. return true;
  19093. }
  19094. return true;
  19095. }
  19096. const isLiteralWhitelisted = /*#__PURE__*/ makeMap('true,false,null,this');
  19097. const transformExpression = (node, context) => {
  19098. if (node.type === 5 /* NodeTypes.INTERPOLATION */) {
  19099. node.content = processExpression(node.content, context);
  19100. }
  19101. else if (node.type === 1 /* NodeTypes.ELEMENT */) {
  19102. // handle directives on element
  19103. for (let i = 0; i < node.props.length; i++) {
  19104. const dir = node.props[i];
  19105. // do not process for v-on & v-for since they are special handled
  19106. if (dir.type === 7 /* NodeTypes.DIRECTIVE */ && dir.name !== 'for') {
  19107. const exp = dir.exp;
  19108. const arg = dir.arg;
  19109. // do not process exp if this is v-on:arg - we need special handling
  19110. // for wrapping inline statements.
  19111. if (exp &&
  19112. exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  19113. !(dir.name === 'on' && arg)) {
  19114. dir.exp = processExpression(exp, context,
  19115. // slot args must be processed as function params
  19116. dir.name === 'slot');
  19117. }
  19118. if (arg && arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !arg.isStatic) {
  19119. dir.arg = processExpression(arg, context);
  19120. }
  19121. }
  19122. }
  19123. }
  19124. };
  19125. // Important: since this function uses Node.js only dependencies, it should
  19126. // always be used with a leading !false check so that it can be
  19127. // tree-shaken from the browser build.
  19128. function processExpression(node, context,
  19129. // some expressions like v-slot props & v-for aliases should be parsed as
  19130. // function params
  19131. asParams = false,
  19132. // v-on handler values may contain multiple statements
  19133. asRawStatements = false, localVars = Object.create(context.identifiers)) {
  19134. if (!context.prefixIdentifiers || !node.content.trim()) {
  19135. return node;
  19136. }
  19137. const { inline, bindingMetadata } = context;
  19138. const rewriteIdentifier = (raw, parent, id) => {
  19139. const type = hasOwn(bindingMetadata, raw) && bindingMetadata[raw];
  19140. if (inline) {
  19141. // x = y
  19142. const isAssignmentLVal = parent && parent.type === 'AssignmentExpression' && parent.left === id;
  19143. // x++
  19144. const isUpdateArg = parent && parent.type === 'UpdateExpression' && parent.argument === id;
  19145. // ({ x } = y)
  19146. const isDestructureAssignment = parent && isInDestructureAssignment(parent, parentStack);
  19147. if (type === "setup-const" /* BindingTypes.SETUP_CONST */ ||
  19148. type === "setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */ ||
  19149. localVars[raw]) {
  19150. return raw;
  19151. }
  19152. else if (type === "setup-ref" /* BindingTypes.SETUP_REF */) {
  19153. return `${raw}.value`;
  19154. }
  19155. else if (type === "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */) {
  19156. // const binding that may or may not be ref
  19157. // if it's not a ref, then assignments don't make sense -
  19158. // so we ignore the non-ref assignment case and generate code
  19159. // that assumes the value to be a ref for more efficiency
  19160. return isAssignmentLVal || isUpdateArg || isDestructureAssignment
  19161. ? `${raw}.value`
  19162. : `${context.helperString(UNREF)}(${raw})`;
  19163. }
  19164. else if (type === "setup-let" /* BindingTypes.SETUP_LET */) {
  19165. if (isAssignmentLVal) {
  19166. // let binding.
  19167. // this is a bit more tricky as we need to cover the case where
  19168. // let is a local non-ref value, and we need to replicate the
  19169. // right hand side value.
  19170. // x = y --> isRef(x) ? x.value = y : x = y
  19171. const { right: rVal, operator } = parent;
  19172. const rExp = rawExp.slice(rVal.start - 1, rVal.end - 1);
  19173. const rExpString = stringifyExpression(processExpression(createSimpleExpression(rExp, false), context, false, false, knownIds));
  19174. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${raw}.value ${operator} ${rExpString} : ${raw}`;
  19175. }
  19176. else if (isUpdateArg) {
  19177. // make id replace parent in the code range so the raw update operator
  19178. // is removed
  19179. id.start = parent.start;
  19180. id.end = parent.end;
  19181. const { prefix: isPrefix, operator } = parent;
  19182. const prefix = isPrefix ? operator : ``;
  19183. const postfix = isPrefix ? `` : operator;
  19184. // let binding.
  19185. // x++ --> isRef(a) ? a.value++ : a++
  19186. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${prefix}${raw}.value${postfix} : ${prefix}${raw}${postfix}`;
  19187. }
  19188. else if (isDestructureAssignment) {
  19189. // TODO
  19190. // let binding in a destructure assignment - it's very tricky to
  19191. // handle both possible cases here without altering the original
  19192. // structure of the code, so we just assume it's not a ref here
  19193. // for now
  19194. return raw;
  19195. }
  19196. else {
  19197. return `${context.helperString(UNREF)}(${raw})`;
  19198. }
  19199. }
  19200. else if (type === "props" /* BindingTypes.PROPS */) {
  19201. // use __props which is generated by compileScript so in ts mode
  19202. // it gets correct type
  19203. return genPropsAccessExp(raw);
  19204. }
  19205. else if (type === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
  19206. // prop with a different local alias (from defineProps() destructure)
  19207. return genPropsAccessExp(bindingMetadata.__propsAliases[raw]);
  19208. }
  19209. }
  19210. else {
  19211. if (type && type.startsWith('setup')) {
  19212. // setup bindings in non-inline mode
  19213. return `$setup.${raw}`;
  19214. }
  19215. else if (type === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
  19216. return `$props['${bindingMetadata.__propsAliases[raw]}']`;
  19217. }
  19218. else if (type) {
  19219. return `$${type}.${raw}`;
  19220. }
  19221. }
  19222. // fallback to ctx
  19223. return `_ctx.${raw}`;
  19224. };
  19225. // fast path if expression is a simple identifier.
  19226. const rawExp = node.content;
  19227. // bail constant on parens (function invocation) and dot (member access)
  19228. const bailConstant = rawExp.indexOf(`(`) > -1 || rawExp.indexOf('.') > 0;
  19229. if (isSimpleIdentifier(rawExp)) {
  19230. const isScopeVarReference = context.identifiers[rawExp];
  19231. const isAllowedGlobal = isGloballyWhitelisted(rawExp);
  19232. const isLiteral = isLiteralWhitelisted(rawExp);
  19233. if (!asParams && !isScopeVarReference && !isAllowedGlobal && !isLiteral) {
  19234. // const bindings exposed from setup can be skipped for patching but
  19235. // cannot be hoisted to module scope
  19236. if (bindingMetadata[node.content] === "setup-const" /* BindingTypes.SETUP_CONST */) {
  19237. node.constType = 1 /* ConstantTypes.CAN_SKIP_PATCH */;
  19238. }
  19239. node.content = rewriteIdentifier(rawExp);
  19240. }
  19241. else if (!isScopeVarReference) {
  19242. if (isLiteral) {
  19243. node.constType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  19244. }
  19245. else {
  19246. node.constType = 2 /* ConstantTypes.CAN_HOIST */;
  19247. }
  19248. }
  19249. return node;
  19250. }
  19251. let ast;
  19252. // exp needs to be parsed differently:
  19253. // 1. Multiple inline statements (v-on, with presence of `;`): parse as raw
  19254. // exp, but make sure to pad with spaces for consistent ranges
  19255. // 2. Expressions: wrap with parens (for e.g. object expressions)
  19256. // 3. Function arguments (v-for, v-slot): place in a function argument position
  19257. const source = asRawStatements
  19258. ? ` ${rawExp} `
  19259. : `(${rawExp})${asParams ? `=>{}` : ``}`;
  19260. try {
  19261. ast = parse_1$1(source, {
  19262. plugins: context.expressionPlugins
  19263. }).program;
  19264. }
  19265. catch (e) {
  19266. context.onError(createCompilerError(45 /* ErrorCodes.X_INVALID_EXPRESSION */, node.loc, undefined, e.message));
  19267. return node;
  19268. }
  19269. const ids = [];
  19270. const parentStack = [];
  19271. const knownIds = Object.create(context.identifiers);
  19272. walkIdentifiers(ast, (node, parent, _, isReferenced, isLocal) => {
  19273. if (isStaticPropertyKey(node, parent)) {
  19274. return;
  19275. }
  19276. const needPrefix = isReferenced && canPrefix(node);
  19277. if (needPrefix && !isLocal) {
  19278. if (isStaticProperty(parent) && parent.shorthand) {
  19279. node.prefix = `${node.name}: `;
  19280. }
  19281. node.name = rewriteIdentifier(node.name, parent, node);
  19282. ids.push(node);
  19283. }
  19284. else {
  19285. // The identifier is considered constant unless it's pointing to a
  19286. // local scope variable (a v-for alias, or a v-slot prop)
  19287. if (!(needPrefix && isLocal) && !bailConstant) {
  19288. node.isConstant = true;
  19289. }
  19290. // also generate sub-expressions for other identifiers for better
  19291. // source map support. (except for property keys which are static)
  19292. ids.push(node);
  19293. }
  19294. }, true, // invoke on ALL identifiers
  19295. parentStack, knownIds);
  19296. // We break up the compound expression into an array of strings and sub
  19297. // expressions (for identifiers that have been prefixed). In codegen, if
  19298. // an ExpressionNode has the `.children` property, it will be used instead of
  19299. // `.content`.
  19300. const children = [];
  19301. ids.sort((a, b) => a.start - b.start);
  19302. ids.forEach((id, i) => {
  19303. // range is offset by -1 due to the wrapping parens when parsed
  19304. const start = id.start - 1;
  19305. const end = id.end - 1;
  19306. const last = ids[i - 1];
  19307. const leadingText = rawExp.slice(last ? last.end - 1 : 0, start);
  19308. if (leadingText.length || id.prefix) {
  19309. children.push(leadingText + (id.prefix || ``));
  19310. }
  19311. const source = rawExp.slice(start, end);
  19312. children.push(createSimpleExpression(id.name, false, {
  19313. source,
  19314. start: advancePositionWithClone(node.loc.start, source, start),
  19315. end: advancePositionWithClone(node.loc.start, source, end)
  19316. }, id.isConstant ? 3 /* ConstantTypes.CAN_STRINGIFY */ : 0 /* ConstantTypes.NOT_CONSTANT */));
  19317. if (i === ids.length - 1 && end < rawExp.length) {
  19318. children.push(rawExp.slice(end));
  19319. }
  19320. });
  19321. let ret;
  19322. if (children.length) {
  19323. ret = createCompoundExpression(children, node.loc);
  19324. }
  19325. else {
  19326. ret = node;
  19327. ret.constType = bailConstant
  19328. ? 0 /* ConstantTypes.NOT_CONSTANT */
  19329. : 3 /* ConstantTypes.CAN_STRINGIFY */;
  19330. }
  19331. ret.identifiers = Object.keys(knownIds);
  19332. return ret;
  19333. }
  19334. function canPrefix(id) {
  19335. // skip whitelisted globals
  19336. if (isGloballyWhitelisted(id.name)) {
  19337. return false;
  19338. }
  19339. // special case for webpack compilation
  19340. if (id.name === 'require') {
  19341. return false;
  19342. }
  19343. return true;
  19344. }
  19345. function stringifyExpression(exp) {
  19346. if (isString$2(exp)) {
  19347. return exp;
  19348. }
  19349. else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  19350. return exp.content;
  19351. }
  19352. else {
  19353. return exp.children
  19354. .map(stringifyExpression)
  19355. .join('');
  19356. }
  19357. }
  19358. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  19359. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  19360. // #1587: We need to dynamically increment the key based on the current
  19361. // node's sibling nodes, since chained v-if/else branches are
  19362. // rendered at the same depth
  19363. const siblings = context.parent.children;
  19364. let i = siblings.indexOf(ifNode);
  19365. let key = 0;
  19366. while (i-- >= 0) {
  19367. const sibling = siblings[i];
  19368. if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
  19369. key += sibling.branches.length;
  19370. }
  19371. }
  19372. // Exit callback. Complete the codegenNode when all children have been
  19373. // transformed.
  19374. return () => {
  19375. if (isRoot) {
  19376. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  19377. }
  19378. else {
  19379. // attach this branch's codegen node to the v-if root.
  19380. const parentCondition = getParentCondition(ifNode.codegenNode);
  19381. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  19382. }
  19383. };
  19384. });
  19385. });
  19386. // target-agnostic transform used for both Client and SSR
  19387. function processIf(node, dir, context, processCodegen) {
  19388. if (dir.name !== 'else' &&
  19389. (!dir.exp || !dir.exp.content.trim())) {
  19390. const loc = dir.exp ? dir.exp.loc : node.loc;
  19391. context.onError(createCompilerError(28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */, dir.loc));
  19392. dir.exp = createSimpleExpression(`true`, false, loc);
  19393. }
  19394. if (context.prefixIdentifiers && dir.exp) {
  19395. // dir.exp can only be simple expression because vIf transform is applied
  19396. // before expression transform.
  19397. dir.exp = processExpression(dir.exp, context);
  19398. }
  19399. if (dir.name === 'if') {
  19400. const branch = createIfBranch(node, dir);
  19401. const ifNode = {
  19402. type: 9 /* NodeTypes.IF */,
  19403. loc: node.loc,
  19404. branches: [branch]
  19405. };
  19406. context.replaceNode(ifNode);
  19407. if (processCodegen) {
  19408. return processCodegen(ifNode, branch, true);
  19409. }
  19410. }
  19411. else {
  19412. // locate the adjacent v-if
  19413. const siblings = context.parent.children;
  19414. const comments = [];
  19415. let i = siblings.indexOf(node);
  19416. while (i-- >= -1) {
  19417. const sibling = siblings[i];
  19418. if (sibling && sibling.type === 3 /* NodeTypes.COMMENT */) {
  19419. context.removeNode(sibling);
  19420. comments.unshift(sibling);
  19421. continue;
  19422. }
  19423. if (sibling &&
  19424. sibling.type === 2 /* NodeTypes.TEXT */ &&
  19425. !sibling.content.trim().length) {
  19426. context.removeNode(sibling);
  19427. continue;
  19428. }
  19429. if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
  19430. // Check if v-else was followed by v-else-if
  19431. if (dir.name === 'else-if' &&
  19432. sibling.branches[sibling.branches.length - 1].condition === undefined) {
  19433. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  19434. }
  19435. // move the node to the if node's branches
  19436. context.removeNode();
  19437. const branch = createIfBranch(node, dir);
  19438. if (comments.length &&
  19439. // #3619 ignore comments if the v-if is direct child of <transition>
  19440. !(context.parent &&
  19441. context.parent.type === 1 /* NodeTypes.ELEMENT */ &&
  19442. isBuiltInType(context.parent.tag, 'transition'))) {
  19443. branch.children = [...comments, ...branch.children];
  19444. }
  19445. // check if user is forcing same key on different branches
  19446. {
  19447. const key = branch.userKey;
  19448. if (key) {
  19449. sibling.branches.forEach(({ userKey }) => {
  19450. if (isSameKey(userKey, key)) {
  19451. context.onError(createCompilerError(29 /* ErrorCodes.X_V_IF_SAME_KEY */, branch.userKey.loc));
  19452. }
  19453. });
  19454. }
  19455. }
  19456. sibling.branches.push(branch);
  19457. const onExit = processCodegen && processCodegen(sibling, branch, false);
  19458. // since the branch was removed, it will not be traversed.
  19459. // make sure to traverse here.
  19460. traverseNode(branch, context);
  19461. // call on exit
  19462. if (onExit)
  19463. onExit();
  19464. // make sure to reset currentNode after traversal to indicate this
  19465. // node has been removed.
  19466. context.currentNode = null;
  19467. }
  19468. else {
  19469. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  19470. }
  19471. break;
  19472. }
  19473. }
  19474. }
  19475. function createIfBranch(node, dir) {
  19476. const isTemplateIf = node.tagType === 3 /* ElementTypes.TEMPLATE */;
  19477. return {
  19478. type: 10 /* NodeTypes.IF_BRANCH */,
  19479. loc: node.loc,
  19480. condition: dir.name === 'else' ? undefined : dir.exp,
  19481. children: isTemplateIf && !findDir(node, 'for') ? node.children : [node],
  19482. userKey: findProp(node, `key`),
  19483. isTemplateIf
  19484. };
  19485. }
  19486. function createCodegenNodeForBranch(branch, keyIndex, context) {
  19487. if (branch.condition) {
  19488. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  19489. // make sure to pass in asBlock: true so that the comment node call
  19490. // closes the current block.
  19491. createCallExpression(context.helper(CREATE_COMMENT), [
  19492. '"v-if"' ,
  19493. 'true'
  19494. ]));
  19495. }
  19496. else {
  19497. return createChildrenCodegenNode(branch, keyIndex, context);
  19498. }
  19499. }
  19500. function createChildrenCodegenNode(branch, keyIndex, context) {
  19501. const { helper } = context;
  19502. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* ConstantTypes.CAN_HOIST */));
  19503. const { children } = branch;
  19504. const firstChild = children[0];
  19505. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* NodeTypes.ELEMENT */;
  19506. if (needFragmentWrapper) {
  19507. if (children.length === 1 && firstChild.type === 11 /* NodeTypes.FOR */) {
  19508. // optimize away nested fragments when child is a ForNode
  19509. const vnodeCall = firstChild.codegenNode;
  19510. injectProp(vnodeCall, keyProperty, context);
  19511. return vnodeCall;
  19512. }
  19513. else {
  19514. let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
  19515. let patchFlagText = PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
  19516. // check if the fragment actually contains a single valid child with
  19517. // the rest being comments
  19518. if (!branch.isTemplateIf &&
  19519. children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
  19520. patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
  19521. patchFlagText += `, ${PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
  19522. }
  19523. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
  19524. }
  19525. }
  19526. else {
  19527. const ret = firstChild.codegenNode;
  19528. const vnodeCall = getMemoedVNodeCall(ret);
  19529. // Change createVNode to createBlock.
  19530. if (vnodeCall.type === 13 /* NodeTypes.VNODE_CALL */) {
  19531. makeBlock(vnodeCall, context);
  19532. }
  19533. // inject branch key
  19534. injectProp(vnodeCall, keyProperty, context);
  19535. return ret;
  19536. }
  19537. }
  19538. function isSameKey(a, b) {
  19539. if (!a || a.type !== b.type) {
  19540. return false;
  19541. }
  19542. if (a.type === 6 /* NodeTypes.ATTRIBUTE */) {
  19543. if (a.value.content !== b.value.content) {
  19544. return false;
  19545. }
  19546. }
  19547. else {
  19548. // directive
  19549. const exp = a.exp;
  19550. const branchExp = b.exp;
  19551. if (exp.type !== branchExp.type) {
  19552. return false;
  19553. }
  19554. if (exp.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  19555. exp.isStatic !== branchExp.isStatic ||
  19556. exp.content !== branchExp.content) {
  19557. return false;
  19558. }
  19559. }
  19560. return true;
  19561. }
  19562. function getParentCondition(node) {
  19563. while (true) {
  19564. if (node.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  19565. if (node.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  19566. node = node.alternate;
  19567. }
  19568. else {
  19569. return node;
  19570. }
  19571. }
  19572. else if (node.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */) {
  19573. node = node.value;
  19574. }
  19575. }
  19576. }
  19577. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  19578. const { helper, removeHelper } = context;
  19579. return processFor(node, dir, context, forNode => {
  19580. // create the loop render function expression now, and add the
  19581. // iterator on exit after all children have been traversed
  19582. const renderExp = createCallExpression(helper(RENDER_LIST), [
  19583. forNode.source
  19584. ]);
  19585. const isTemplate = isTemplateNode(node);
  19586. const memo = findDir(node, 'memo');
  19587. const keyProp = findProp(node, `key`);
  19588. const keyExp = keyProp &&
  19589. (keyProp.type === 6 /* NodeTypes.ATTRIBUTE */
  19590. ? createSimpleExpression(keyProp.value.content, true)
  19591. : keyProp.exp);
  19592. const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
  19593. if (isTemplate) {
  19594. // #2085 / #5288 process :key and v-memo expressions need to be
  19595. // processed on `<template v-for>`. In this case the node is discarded
  19596. // and never traversed so its binding expressions won't be processed
  19597. // by the normal transforms.
  19598. if (memo) {
  19599. memo.exp = processExpression(memo.exp, context);
  19600. }
  19601. if (keyProperty && keyProp.type !== 6 /* NodeTypes.ATTRIBUTE */) {
  19602. keyProperty.value = processExpression(keyProperty.value, context);
  19603. }
  19604. }
  19605. const isStableFragment = forNode.source.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  19606. forNode.source.constType > 0 /* ConstantTypes.NOT_CONSTANT */;
  19607. const fragmentFlag = isStableFragment
  19608. ? 64 /* PatchFlags.STABLE_FRAGMENT */
  19609. : keyProp
  19610. ? 128 /* PatchFlags.KEYED_FRAGMENT */
  19611. : 256 /* PatchFlags.UNKEYED_FRAGMENT */;
  19612. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
  19613. (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
  19614. return () => {
  19615. // finish the codegen now that all children have been traversed
  19616. let childBlock;
  19617. const { children } = forNode;
  19618. // check <template v-for> key placement
  19619. if (isTemplate) {
  19620. node.children.some(c => {
  19621. if (c.type === 1 /* NodeTypes.ELEMENT */) {
  19622. const key = findProp(c, 'key');
  19623. if (key) {
  19624. context.onError(createCompilerError(33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  19625. return true;
  19626. }
  19627. }
  19628. });
  19629. }
  19630. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* NodeTypes.ELEMENT */;
  19631. const slotOutlet = isSlotOutlet(node)
  19632. ? node
  19633. : isTemplate &&
  19634. node.children.length === 1 &&
  19635. isSlotOutlet(node.children[0])
  19636. ? node.children[0] // api-extractor somehow fails to infer this
  19637. : null;
  19638. if (slotOutlet) {
  19639. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  19640. childBlock = slotOutlet.codegenNode;
  19641. if (isTemplate && keyProperty) {
  19642. // <template v-for="..." :key="..."><slot/></template>
  19643. // we need to inject the key to the renderSlot() call.
  19644. // the props for renderSlot is passed as the 3rd argument.
  19645. injectProp(childBlock, keyProperty, context);
  19646. }
  19647. }
  19648. else if (needFragmentWrapper) {
  19649. // <template v-for="..."> with text or multi-elements
  19650. // should generate a fragment block for each loop
  19651. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* PatchFlags.STABLE_FRAGMENT */ +
  19652. (` /* ${PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */]} */`
  19653. ), undefined, undefined, true, undefined, false /* isComponent */);
  19654. }
  19655. else {
  19656. // Normal element v-for. Directly use the child's codegenNode
  19657. // but mark it as a block.
  19658. childBlock = children[0]
  19659. .codegenNode;
  19660. if (isTemplate && keyProperty) {
  19661. injectProp(childBlock, keyProperty, context);
  19662. }
  19663. if (childBlock.isBlock !== !isStableFragment) {
  19664. if (childBlock.isBlock) {
  19665. // switch from block to vnode
  19666. removeHelper(OPEN_BLOCK);
  19667. removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  19668. }
  19669. else {
  19670. // switch from vnode to block
  19671. removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  19672. }
  19673. }
  19674. childBlock.isBlock = !isStableFragment;
  19675. if (childBlock.isBlock) {
  19676. helper(OPEN_BLOCK);
  19677. helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  19678. }
  19679. else {
  19680. helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  19681. }
  19682. }
  19683. if (memo) {
  19684. const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
  19685. createSimpleExpression(`_cached`)
  19686. ]));
  19687. loop.body = createBlockStatement([
  19688. createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
  19689. createCompoundExpression([
  19690. `if (_cached`,
  19691. ...(keyExp ? [` && _cached.key === `, keyExp] : []),
  19692. ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
  19693. ]),
  19694. createCompoundExpression([`const _item = `, childBlock]),
  19695. createSimpleExpression(`_item.memo = _memo`),
  19696. createSimpleExpression(`return _item`)
  19697. ]);
  19698. renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
  19699. }
  19700. else {
  19701. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  19702. }
  19703. };
  19704. });
  19705. });
  19706. // target-agnostic transform used for both Client and SSR
  19707. function processFor(node, dir, context, processCodegen) {
  19708. if (!dir.exp) {
  19709. context.onError(createCompilerError(31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */, dir.loc));
  19710. return;
  19711. }
  19712. const parseResult = parseForExpression(
  19713. // can only be simple expression because vFor transform is applied
  19714. // before expression transform.
  19715. dir.exp, context);
  19716. if (!parseResult) {
  19717. context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  19718. return;
  19719. }
  19720. const { addIdentifiers, removeIdentifiers, scopes } = context;
  19721. const { source, value, key, index } = parseResult;
  19722. const forNode = {
  19723. type: 11 /* NodeTypes.FOR */,
  19724. loc: dir.loc,
  19725. source,
  19726. valueAlias: value,
  19727. keyAlias: key,
  19728. objectIndexAlias: index,
  19729. parseResult,
  19730. children: isTemplateNode(node) ? node.children : [node]
  19731. };
  19732. context.replaceNode(forNode);
  19733. // bookkeeping
  19734. scopes.vFor++;
  19735. if (context.prefixIdentifiers) {
  19736. // scope management
  19737. // inject identifiers to context
  19738. value && addIdentifiers(value);
  19739. key && addIdentifiers(key);
  19740. index && addIdentifiers(index);
  19741. }
  19742. const onExit = processCodegen && processCodegen(forNode);
  19743. return () => {
  19744. scopes.vFor--;
  19745. if (context.prefixIdentifiers) {
  19746. value && removeIdentifiers(value);
  19747. key && removeIdentifiers(key);
  19748. index && removeIdentifiers(index);
  19749. }
  19750. if (onExit)
  19751. onExit();
  19752. };
  19753. }
  19754. const forAliasRE$1 = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  19755. // This regex doesn't cover the case if key or index aliases have destructuring,
  19756. // but those do not make sense in the first place, so this works in practice.
  19757. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  19758. const stripParensRE = /^\(|\)$/g;
  19759. function parseForExpression(input, context) {
  19760. const loc = input.loc;
  19761. const exp = input.content;
  19762. const inMatch = exp.match(forAliasRE$1);
  19763. if (!inMatch)
  19764. return;
  19765. const [, LHS, RHS] = inMatch;
  19766. const result = {
  19767. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  19768. value: undefined,
  19769. key: undefined,
  19770. index: undefined
  19771. };
  19772. if (context.prefixIdentifiers) {
  19773. result.source = processExpression(result.source, context);
  19774. }
  19775. let valueContent = LHS.trim().replace(stripParensRE, '').trim();
  19776. const trimmedOffset = LHS.indexOf(valueContent);
  19777. const iteratorMatch = valueContent.match(forIteratorRE);
  19778. if (iteratorMatch) {
  19779. valueContent = valueContent.replace(forIteratorRE, '').trim();
  19780. const keyContent = iteratorMatch[1].trim();
  19781. let keyOffset;
  19782. if (keyContent) {
  19783. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  19784. result.key = createAliasExpression(loc, keyContent, keyOffset);
  19785. if (context.prefixIdentifiers) {
  19786. result.key = processExpression(result.key, context, true);
  19787. }
  19788. }
  19789. if (iteratorMatch[2]) {
  19790. const indexContent = iteratorMatch[2].trim();
  19791. if (indexContent) {
  19792. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  19793. ? keyOffset + keyContent.length
  19794. : trimmedOffset + valueContent.length));
  19795. if (context.prefixIdentifiers) {
  19796. result.index = processExpression(result.index, context, true);
  19797. }
  19798. }
  19799. }
  19800. }
  19801. if (valueContent) {
  19802. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  19803. if (context.prefixIdentifiers) {
  19804. result.value = processExpression(result.value, context, true);
  19805. }
  19806. }
  19807. return result;
  19808. }
  19809. function createAliasExpression(range, content, offset) {
  19810. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  19811. }
  19812. function createForLoopParams({ value, key, index }, memoArgs = []) {
  19813. return createParamsList([value, key, index, ...memoArgs]);
  19814. }
  19815. function createParamsList(args) {
  19816. let i = args.length;
  19817. while (i--) {
  19818. if (args[i])
  19819. break;
  19820. }
  19821. return args
  19822. .slice(0, i + 1)
  19823. .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
  19824. }
  19825. const defaultFallback = createSimpleExpression(`undefined`, false);
  19826. // A NodeTransform that:
  19827. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  19828. // by transformExpression. This is only applied in non-browser builds with
  19829. // { prefixIdentifiers: true }.
  19830. // 2. Track v-slot depths so that we know a slot is inside another slot.
  19831. // Note the exit callback is executed before buildSlots() on the same node,
  19832. // so only nested slots see positive numbers.
  19833. const trackSlotScopes = (node, context) => {
  19834. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  19835. (node.tagType === 1 /* ElementTypes.COMPONENT */ ||
  19836. node.tagType === 3 /* ElementTypes.TEMPLATE */)) {
  19837. // We are only checking non-empty v-slot here
  19838. // since we only care about slots that introduce scope variables.
  19839. const vSlot = findDir(node, 'slot');
  19840. if (vSlot) {
  19841. const slotProps = vSlot.exp;
  19842. if (context.prefixIdentifiers) {
  19843. slotProps && context.addIdentifiers(slotProps);
  19844. }
  19845. context.scopes.vSlot++;
  19846. return () => {
  19847. if (context.prefixIdentifiers) {
  19848. slotProps && context.removeIdentifiers(slotProps);
  19849. }
  19850. context.scopes.vSlot--;
  19851. };
  19852. }
  19853. }
  19854. };
  19855. // A NodeTransform that tracks scope identifiers for scoped slots with v-for.
  19856. // This transform is only applied in non-browser builds with { prefixIdentifiers: true }
  19857. const trackVForSlotScopes = (node, context) => {
  19858. let vFor;
  19859. if (isTemplateNode(node) &&
  19860. node.props.some(isVSlot) &&
  19861. (vFor = findDir(node, 'for'))) {
  19862. const result = (vFor.parseResult = parseForExpression(vFor.exp, context));
  19863. if (result) {
  19864. const { value, key, index } = result;
  19865. const { addIdentifiers, removeIdentifiers } = context;
  19866. value && addIdentifiers(value);
  19867. key && addIdentifiers(key);
  19868. index && addIdentifiers(index);
  19869. return () => {
  19870. value && removeIdentifiers(value);
  19871. key && removeIdentifiers(key);
  19872. index && removeIdentifiers(index);
  19873. };
  19874. }
  19875. }
  19876. };
  19877. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  19878. // Instead of being a DirectiveTransform, v-slot processing is called during
  19879. // transformElement to build the slots object for a component.
  19880. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  19881. context.helper(WITH_CTX);
  19882. const { children, loc } = node;
  19883. const slotsProperties = [];
  19884. const dynamicSlots = [];
  19885. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  19886. // since it likely uses a scope variable.
  19887. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  19888. // with `prefixIdentifiers: true`, this can be further optimized to make
  19889. // it dynamic only when the slot actually uses the scope variables.
  19890. if (!context.ssr && context.prefixIdentifiers) {
  19891. hasDynamicSlots = hasScopeRef(node, context.identifiers);
  19892. }
  19893. // 1. Check for slot with slotProps on component itself.
  19894. // <Comp v-slot="{ prop }"/>
  19895. const onComponentSlot = findDir(node, 'slot', true);
  19896. if (onComponentSlot) {
  19897. const { arg, exp } = onComponentSlot;
  19898. if (arg && !isStaticExp(arg)) {
  19899. hasDynamicSlots = true;
  19900. }
  19901. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  19902. }
  19903. // 2. Iterate through children and check for template slots
  19904. // <template v-slot:foo="{ prop }">
  19905. let hasTemplateSlots = false;
  19906. let hasNamedDefaultSlot = false;
  19907. const implicitDefaultChildren = [];
  19908. const seenSlotNames = new Set();
  19909. let conditionalBranchIndex = 0;
  19910. for (let i = 0; i < children.length; i++) {
  19911. const slotElement = children[i];
  19912. let slotDir;
  19913. if (!isTemplateNode(slotElement) ||
  19914. !(slotDir = findDir(slotElement, 'slot', true))) {
  19915. // not a <template v-slot>, skip.
  19916. if (slotElement.type !== 3 /* NodeTypes.COMMENT */) {
  19917. implicitDefaultChildren.push(slotElement);
  19918. }
  19919. continue;
  19920. }
  19921. if (onComponentSlot) {
  19922. // already has on-component slot - this is incorrect usage.
  19923. context.onError(createCompilerError(37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  19924. break;
  19925. }
  19926. hasTemplateSlots = true;
  19927. const { children: slotChildren, loc: slotLoc } = slotElement;
  19928. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  19929. // check if name is dynamic.
  19930. let staticSlotName;
  19931. if (isStaticExp(slotName)) {
  19932. staticSlotName = slotName ? slotName.content : `default`;
  19933. }
  19934. else {
  19935. hasDynamicSlots = true;
  19936. }
  19937. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  19938. // check if this slot is conditional (v-if/v-for)
  19939. let vIf;
  19940. let vElse;
  19941. let vFor;
  19942. if ((vIf = findDir(slotElement, 'if'))) {
  19943. hasDynamicSlots = true;
  19944. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback));
  19945. }
  19946. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  19947. // find adjacent v-if
  19948. let j = i;
  19949. let prev;
  19950. while (j--) {
  19951. prev = children[j];
  19952. if (prev.type !== 3 /* NodeTypes.COMMENT */) {
  19953. break;
  19954. }
  19955. }
  19956. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  19957. // remove node
  19958. children.splice(i, 1);
  19959. i--;
  19960. // attach this slot to previous conditional
  19961. let conditional = dynamicSlots[dynamicSlots.length - 1];
  19962. while (conditional.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  19963. conditional = conditional.alternate;
  19964. }
  19965. conditional.alternate = vElse.exp
  19966. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback)
  19967. : buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++);
  19968. }
  19969. else {
  19970. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  19971. }
  19972. }
  19973. else if ((vFor = findDir(slotElement, 'for'))) {
  19974. hasDynamicSlots = true;
  19975. const parseResult = vFor.parseResult ||
  19976. parseForExpression(vFor.exp, context);
  19977. if (parseResult) {
  19978. // Render the dynamic slots as an array and add it to the createSlot()
  19979. // args. The runtime knows how to handle it appropriately.
  19980. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  19981. parseResult.source,
  19982. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  19983. ]));
  19984. }
  19985. else {
  19986. context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  19987. }
  19988. }
  19989. else {
  19990. // check duplicate static names
  19991. if (staticSlotName) {
  19992. if (seenSlotNames.has(staticSlotName)) {
  19993. context.onError(createCompilerError(38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  19994. continue;
  19995. }
  19996. seenSlotNames.add(staticSlotName);
  19997. if (staticSlotName === 'default') {
  19998. hasNamedDefaultSlot = true;
  19999. }
  20000. }
  20001. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  20002. }
  20003. }
  20004. if (!onComponentSlot) {
  20005. const buildDefaultSlotProperty = (props, children) => {
  20006. const fn = buildSlotFn(props, children, loc);
  20007. return createObjectProperty(`default`, fn);
  20008. };
  20009. if (!hasTemplateSlots) {
  20010. // implicit default slot (on component)
  20011. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  20012. }
  20013. else if (implicitDefaultChildren.length &&
  20014. // #3766
  20015. // with whitespace: 'preserve', whitespaces between slots will end up in
  20016. // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
  20017. implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
  20018. // implicit default slot (mixed with named slots)
  20019. if (hasNamedDefaultSlot) {
  20020. context.onError(createCompilerError(39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  20021. }
  20022. else {
  20023. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  20024. }
  20025. }
  20026. }
  20027. const slotFlag = hasDynamicSlots
  20028. ? 2 /* SlotFlags.DYNAMIC */
  20029. : hasForwardedSlots(node.children)
  20030. ? 3 /* SlotFlags.FORWARDED */
  20031. : 1 /* SlotFlags.STABLE */;
  20032. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  20033. // 2 = compiled but dynamic = can skip normalization, but must run diff
  20034. // 1 = compiled and static = can skip normalization AND diff as optimized
  20035. createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
  20036. if (dynamicSlots.length) {
  20037. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  20038. slots,
  20039. createArrayExpression(dynamicSlots)
  20040. ]);
  20041. }
  20042. return {
  20043. slots,
  20044. hasDynamicSlots
  20045. };
  20046. }
  20047. function buildDynamicSlot(name, fn, index) {
  20048. const props = [
  20049. createObjectProperty(`name`, name),
  20050. createObjectProperty(`fn`, fn)
  20051. ];
  20052. if (index != null) {
  20053. props.push(createObjectProperty(`key`, createSimpleExpression(String(index), true)));
  20054. }
  20055. return createObjectExpression(props);
  20056. }
  20057. function hasForwardedSlots(children) {
  20058. for (let i = 0; i < children.length; i++) {
  20059. const child = children[i];
  20060. switch (child.type) {
  20061. case 1 /* NodeTypes.ELEMENT */:
  20062. if (child.tagType === 2 /* ElementTypes.SLOT */ ||
  20063. hasForwardedSlots(child.children)) {
  20064. return true;
  20065. }
  20066. break;
  20067. case 9 /* NodeTypes.IF */:
  20068. if (hasForwardedSlots(child.branches))
  20069. return true;
  20070. break;
  20071. case 10 /* NodeTypes.IF_BRANCH */:
  20072. case 11 /* NodeTypes.FOR */:
  20073. if (hasForwardedSlots(child.children))
  20074. return true;
  20075. break;
  20076. }
  20077. }
  20078. return false;
  20079. }
  20080. function isNonWhitespaceContent(node) {
  20081. if (node.type !== 2 /* NodeTypes.TEXT */ && node.type !== 12 /* NodeTypes.TEXT_CALL */)
  20082. return true;
  20083. return node.type === 2 /* NodeTypes.TEXT */
  20084. ? !!node.content.trim()
  20085. : isNonWhitespaceContent(node.content);
  20086. }
  20087. // some directive transforms (e.g. v-model) may return a symbol for runtime
  20088. // import, which should be used instead of a resolveDirective call.
  20089. const directiveImportMap = new WeakMap();
  20090. // generate a JavaScript AST for this element's codegen
  20091. const transformElement = (node, context) => {
  20092. // perform the work on exit, after all child expressions have been
  20093. // processed and merged.
  20094. return function postTransformElement() {
  20095. node = context.currentNode;
  20096. if (!(node.type === 1 /* NodeTypes.ELEMENT */ &&
  20097. (node.tagType === 0 /* ElementTypes.ELEMENT */ ||
  20098. node.tagType === 1 /* ElementTypes.COMPONENT */))) {
  20099. return;
  20100. }
  20101. const { tag, props } = node;
  20102. const isComponent = node.tagType === 1 /* ElementTypes.COMPONENT */;
  20103. // The goal of the transform is to create a codegenNode implementing the
  20104. // VNodeCall interface.
  20105. let vnodeTag = isComponent
  20106. ? resolveComponentType(node, context)
  20107. : `"${tag}"`;
  20108. const isDynamicComponent = isObject$2(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  20109. let vnodeProps;
  20110. let vnodeChildren;
  20111. let vnodePatchFlag;
  20112. let patchFlag = 0;
  20113. let vnodeDynamicProps;
  20114. let dynamicPropNames;
  20115. let vnodeDirectives;
  20116. let shouldUseBlock =
  20117. // dynamic component may resolve to plain elements
  20118. isDynamicComponent ||
  20119. vnodeTag === TELEPORT ||
  20120. vnodeTag === SUSPENSE ||
  20121. (!isComponent &&
  20122. // <svg> and <foreignObject> must be forced into blocks so that block
  20123. // updates inside get proper isSVG flag at runtime. (#639, #643)
  20124. // This is technically web-specific, but splitting the logic out of core
  20125. // leads to too much unnecessary complexity.
  20126. (tag === 'svg' || tag === 'foreignObject'));
  20127. // props
  20128. if (props.length > 0) {
  20129. const propsBuildResult = buildProps(node, context, undefined, isComponent, isDynamicComponent);
  20130. vnodeProps = propsBuildResult.props;
  20131. patchFlag = propsBuildResult.patchFlag;
  20132. dynamicPropNames = propsBuildResult.dynamicPropNames;
  20133. const directives = propsBuildResult.directives;
  20134. vnodeDirectives =
  20135. directives && directives.length
  20136. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  20137. : undefined;
  20138. if (propsBuildResult.shouldUseBlock) {
  20139. shouldUseBlock = true;
  20140. }
  20141. }
  20142. // children
  20143. if (node.children.length > 0) {
  20144. if (vnodeTag === KEEP_ALIVE) {
  20145. // Although a built-in component, we compile KeepAlive with raw children
  20146. // instead of slot functions so that it can be used inside Transition
  20147. // or other Transition-wrapping HOCs.
  20148. // To ensure correct updates with block optimizations, we need to:
  20149. // 1. Force keep-alive into a block. This avoids its children being
  20150. // collected by a parent block.
  20151. shouldUseBlock = true;
  20152. // 2. Force keep-alive to always be updated, since it uses raw children.
  20153. patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  20154. if (node.children.length > 1) {
  20155. context.onError(createCompilerError(46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */, {
  20156. start: node.children[0].loc.start,
  20157. end: node.children[node.children.length - 1].loc.end,
  20158. source: ''
  20159. }));
  20160. }
  20161. }
  20162. const shouldBuildAsSlots = isComponent &&
  20163. // Teleport is not a real component and has dedicated runtime handling
  20164. vnodeTag !== TELEPORT &&
  20165. // explained above.
  20166. vnodeTag !== KEEP_ALIVE;
  20167. if (shouldBuildAsSlots) {
  20168. const { slots, hasDynamicSlots } = buildSlots(node, context);
  20169. vnodeChildren = slots;
  20170. if (hasDynamicSlots) {
  20171. patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  20172. }
  20173. }
  20174. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  20175. const child = node.children[0];
  20176. const type = child.type;
  20177. // check for dynamic text children
  20178. const hasDynamicTextChild = type === 5 /* NodeTypes.INTERPOLATION */ ||
  20179. type === 8 /* NodeTypes.COMPOUND_EXPRESSION */;
  20180. if (hasDynamicTextChild &&
  20181. getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
  20182. patchFlag |= 1 /* PatchFlags.TEXT */;
  20183. }
  20184. // pass directly if the only child is a text node
  20185. // (plain / interpolation / expression)
  20186. if (hasDynamicTextChild || type === 2 /* NodeTypes.TEXT */) {
  20187. vnodeChildren = child;
  20188. }
  20189. else {
  20190. vnodeChildren = node.children;
  20191. }
  20192. }
  20193. else {
  20194. vnodeChildren = node.children;
  20195. }
  20196. }
  20197. // patchFlag & dynamicPropNames
  20198. if (patchFlag !== 0) {
  20199. {
  20200. if (patchFlag < 0) {
  20201. // special flags (negative and mutually exclusive)
  20202. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  20203. }
  20204. else {
  20205. // bitwise flags
  20206. const flagNames = Object.keys(PatchFlagNames)
  20207. .map(Number)
  20208. .filter(n => n > 0 && patchFlag & n)
  20209. .map(n => PatchFlagNames[n])
  20210. .join(`, `);
  20211. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  20212. }
  20213. }
  20214. if (dynamicPropNames && dynamicPropNames.length) {
  20215. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  20216. }
  20217. }
  20218. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
  20219. };
  20220. };
  20221. function resolveComponentType(node, context, ssr = false) {
  20222. let { tag } = node;
  20223. // 1. dynamic component
  20224. const isExplicitDynamic = isComponentTag(tag);
  20225. const isProp = findProp(node, 'is');
  20226. if (isProp) {
  20227. if (isExplicitDynamic ||
  20228. (false )) {
  20229. const exp = isProp.type === 6 /* NodeTypes.ATTRIBUTE */
  20230. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  20231. : isProp.exp;
  20232. if (exp) {
  20233. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  20234. exp
  20235. ]);
  20236. }
  20237. }
  20238. else if (isProp.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  20239. isProp.value.content.startsWith('vue:')) {
  20240. // <button is="vue:xxx">
  20241. // if not <component>, only is value that starts with "vue:" will be
  20242. // treated as component by the parse phase and reach here, unless it's
  20243. // compat mode where all is values are considered components
  20244. tag = isProp.value.content.slice(4);
  20245. }
  20246. }
  20247. // 1.5 v-is (TODO: Deprecate)
  20248. const isDir = !isExplicitDynamic && findDir(node, 'is');
  20249. if (isDir && isDir.exp) {
  20250. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  20251. isDir.exp
  20252. ]);
  20253. }
  20254. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  20255. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  20256. if (builtIn) {
  20257. // built-ins are simply fallthroughs / have special handling during ssr
  20258. // so we don't need to import their runtime equivalents
  20259. if (!ssr)
  20260. context.helper(builtIn);
  20261. return builtIn;
  20262. }
  20263. // 3. user component (from setup bindings)
  20264. // this is skipped in browser build since browser builds do not perform
  20265. // binding analysis.
  20266. {
  20267. const fromSetup = resolveSetupReference(tag, context);
  20268. if (fromSetup) {
  20269. return fromSetup;
  20270. }
  20271. const dotIndex = tag.indexOf('.');
  20272. if (dotIndex > 0) {
  20273. const ns = resolveSetupReference(tag.slice(0, dotIndex), context);
  20274. if (ns) {
  20275. return ns + tag.slice(dotIndex);
  20276. }
  20277. }
  20278. }
  20279. // 4. Self referencing component (inferred from filename)
  20280. if (context.selfName &&
  20281. capitalize$1(camelize(tag)) === context.selfName) {
  20282. context.helper(RESOLVE_COMPONENT);
  20283. // codegen.ts has special check for __self postfix when generating
  20284. // component imports, which will pass additional `maybeSelfReference` flag
  20285. // to `resolveComponent`.
  20286. context.components.add(tag + `__self`);
  20287. return toValidAssetId(tag, `component`);
  20288. }
  20289. // 5. user component (resolve)
  20290. context.helper(RESOLVE_COMPONENT);
  20291. context.components.add(tag);
  20292. return toValidAssetId(tag, `component`);
  20293. }
  20294. function resolveSetupReference(name, context) {
  20295. const bindings = context.bindingMetadata;
  20296. if (!bindings || bindings.__isScriptSetup === false) {
  20297. return;
  20298. }
  20299. const camelName = camelize(name);
  20300. const PascalName = capitalize$1(camelName);
  20301. const checkType = (type) => {
  20302. if (bindings[name] === type) {
  20303. return name;
  20304. }
  20305. if (bindings[camelName] === type) {
  20306. return camelName;
  20307. }
  20308. if (bindings[PascalName] === type) {
  20309. return PascalName;
  20310. }
  20311. };
  20312. const fromConst = checkType("setup-const" /* BindingTypes.SETUP_CONST */) ||
  20313. checkType("setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */);
  20314. if (fromConst) {
  20315. return context.inline
  20316. ? // in inline mode, const setup bindings (e.g. imports) can be used as-is
  20317. fromConst
  20318. : `$setup[${JSON.stringify(fromConst)}]`;
  20319. }
  20320. const fromMaybeRef = checkType("setup-let" /* BindingTypes.SETUP_LET */) ||
  20321. checkType("setup-ref" /* BindingTypes.SETUP_REF */) ||
  20322. checkType("setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */);
  20323. if (fromMaybeRef) {
  20324. return context.inline
  20325. ? // setup scope bindings that may be refs need to be unrefed
  20326. `${context.helperString(UNREF)}(${fromMaybeRef})`
  20327. : `$setup[${JSON.stringify(fromMaybeRef)}]`;
  20328. }
  20329. }
  20330. function buildProps(node, context, props = node.props, isComponent, isDynamicComponent, ssr = false) {
  20331. const { tag, loc: elementLoc, children } = node;
  20332. let properties = [];
  20333. const mergeArgs = [];
  20334. const runtimeDirectives = [];
  20335. const hasChildren = children.length > 0;
  20336. let shouldUseBlock = false;
  20337. // patchFlag analysis
  20338. let patchFlag = 0;
  20339. let hasRef = false;
  20340. let hasClassBinding = false;
  20341. let hasStyleBinding = false;
  20342. let hasHydrationEventBinding = false;
  20343. let hasDynamicKeys = false;
  20344. let hasVnodeHook = false;
  20345. const dynamicPropNames = [];
  20346. const pushMergeArg = (arg) => {
  20347. if (properties.length) {
  20348. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  20349. properties = [];
  20350. }
  20351. if (arg)
  20352. mergeArgs.push(arg);
  20353. };
  20354. const analyzePatchFlag = ({ key, value }) => {
  20355. if (isStaticExp(key)) {
  20356. const name = key.content;
  20357. const isEventHandler = isOn(name);
  20358. if (isEventHandler &&
  20359. (!isComponent || isDynamicComponent) &&
  20360. // omit the flag for click handlers because hydration gives click
  20361. // dedicated fast path.
  20362. name.toLowerCase() !== 'onclick' &&
  20363. // omit v-model handlers
  20364. name !== 'onUpdate:modelValue' &&
  20365. // omit onVnodeXXX hooks
  20366. !isReservedProp(name)) {
  20367. hasHydrationEventBinding = true;
  20368. }
  20369. if (isEventHandler && isReservedProp(name)) {
  20370. hasVnodeHook = true;
  20371. }
  20372. if (value.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */ ||
  20373. ((value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  20374. value.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) &&
  20375. getConstantType(value, context) > 0)) {
  20376. // skip if the prop is a cached handler or has constant value
  20377. return;
  20378. }
  20379. if (name === 'ref') {
  20380. hasRef = true;
  20381. }
  20382. else if (name === 'class') {
  20383. hasClassBinding = true;
  20384. }
  20385. else if (name === 'style') {
  20386. hasStyleBinding = true;
  20387. }
  20388. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  20389. dynamicPropNames.push(name);
  20390. }
  20391. // treat the dynamic class and style binding of the component as dynamic props
  20392. if (isComponent &&
  20393. (name === 'class' || name === 'style') &&
  20394. !dynamicPropNames.includes(name)) {
  20395. dynamicPropNames.push(name);
  20396. }
  20397. }
  20398. else {
  20399. hasDynamicKeys = true;
  20400. }
  20401. };
  20402. for (let i = 0; i < props.length; i++) {
  20403. // static attribute
  20404. const prop = props[i];
  20405. if (prop.type === 6 /* NodeTypes.ATTRIBUTE */) {
  20406. const { loc, name, value } = prop;
  20407. let isStatic = true;
  20408. if (name === 'ref') {
  20409. hasRef = true;
  20410. if (context.scopes.vFor > 0) {
  20411. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  20412. }
  20413. // in inline mode there is no setupState object, so we can't use string
  20414. // keys to set the ref. Instead, we need to transform it to pass the
  20415. // actual ref instead.
  20416. if (value && context.inline) {
  20417. const binding = context.bindingMetadata[value.content];
  20418. if (binding === "setup-let" /* BindingTypes.SETUP_LET */ ||
  20419. binding === "setup-ref" /* BindingTypes.SETUP_REF */ ||
  20420. binding === "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */) {
  20421. isStatic = false;
  20422. properties.push(createObjectProperty(createSimpleExpression('ref_key', true), createSimpleExpression(value.content, true, value.loc)));
  20423. }
  20424. }
  20425. }
  20426. // skip is on <component>, or is="vue:xxx"
  20427. if (name === 'is' &&
  20428. (isComponentTag(tag) ||
  20429. (value && value.content.startsWith('vue:')) ||
  20430. (false ))) {
  20431. continue;
  20432. }
  20433. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
  20434. }
  20435. else {
  20436. // directives
  20437. const { name, arg, exp, loc } = prop;
  20438. const isVBind = name === 'bind';
  20439. const isVOn = name === 'on';
  20440. // skip v-slot - it is handled by its dedicated transform.
  20441. if (name === 'slot') {
  20442. if (!isComponent) {
  20443. context.onError(createCompilerError(40 /* ErrorCodes.X_V_SLOT_MISPLACED */, loc));
  20444. }
  20445. continue;
  20446. }
  20447. // skip v-once/v-memo - they are handled by dedicated transforms.
  20448. if (name === 'once' || name === 'memo') {
  20449. continue;
  20450. }
  20451. // skip v-is and :is on <component>
  20452. if (name === 'is' ||
  20453. (isVBind &&
  20454. isStaticArgOf(arg, 'is') &&
  20455. (isComponentTag(tag) ||
  20456. (false )))) {
  20457. continue;
  20458. }
  20459. // skip v-on in SSR compilation
  20460. if (isVOn && ssr) {
  20461. continue;
  20462. }
  20463. if (
  20464. // #938: elements with dynamic keys should be forced into blocks
  20465. (isVBind && isStaticArgOf(arg, 'key')) ||
  20466. // inline before-update hooks need to force block so that it is invoked
  20467. // before children
  20468. (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
  20469. shouldUseBlock = true;
  20470. }
  20471. if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
  20472. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  20473. }
  20474. // special case for v-bind and v-on with no argument
  20475. if (!arg && (isVBind || isVOn)) {
  20476. hasDynamicKeys = true;
  20477. if (exp) {
  20478. if (isVBind) {
  20479. // have to merge early for compat build check
  20480. pushMergeArg();
  20481. mergeArgs.push(exp);
  20482. }
  20483. else {
  20484. // v-on="obj" -> toHandlers(obj)
  20485. pushMergeArg({
  20486. type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
  20487. loc,
  20488. callee: context.helper(TO_HANDLERS),
  20489. arguments: isComponent ? [exp] : [exp, `true`]
  20490. });
  20491. }
  20492. }
  20493. else {
  20494. context.onError(createCompilerError(isVBind
  20495. ? 34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */
  20496. : 35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
  20497. }
  20498. continue;
  20499. }
  20500. const directiveTransform = context.directiveTransforms[name];
  20501. if (directiveTransform) {
  20502. // has built-in directive transform.
  20503. const { props, needRuntime } = directiveTransform(prop, node, context);
  20504. !ssr && props.forEach(analyzePatchFlag);
  20505. if (isVOn && arg && !isStaticExp(arg)) {
  20506. pushMergeArg(createObjectExpression(props, elementLoc));
  20507. }
  20508. else {
  20509. properties.push(...props);
  20510. }
  20511. if (needRuntime) {
  20512. runtimeDirectives.push(prop);
  20513. if (isSymbol$1(needRuntime)) {
  20514. directiveImportMap.set(prop, needRuntime);
  20515. }
  20516. }
  20517. }
  20518. else if (!isBuiltInDirective(name)) {
  20519. // no built-in transform, this is a user custom directive.
  20520. runtimeDirectives.push(prop);
  20521. // custom dirs may use beforeUpdate so they need to force blocks
  20522. // to ensure before-update gets called before children update
  20523. if (hasChildren) {
  20524. shouldUseBlock = true;
  20525. }
  20526. }
  20527. }
  20528. }
  20529. let propsExpression = undefined;
  20530. // has v-bind="object" or v-on="object", wrap with mergeProps
  20531. if (mergeArgs.length) {
  20532. // close up any not-yet-merged props
  20533. pushMergeArg();
  20534. if (mergeArgs.length > 1) {
  20535. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  20536. }
  20537. else {
  20538. // single v-bind with nothing else - no need for a mergeProps call
  20539. propsExpression = mergeArgs[0];
  20540. }
  20541. }
  20542. else if (properties.length) {
  20543. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  20544. }
  20545. // patchFlag analysis
  20546. if (hasDynamicKeys) {
  20547. patchFlag |= 16 /* PatchFlags.FULL_PROPS */;
  20548. }
  20549. else {
  20550. if (hasClassBinding && !isComponent) {
  20551. patchFlag |= 2 /* PatchFlags.CLASS */;
  20552. }
  20553. if (hasStyleBinding && !isComponent) {
  20554. patchFlag |= 4 /* PatchFlags.STYLE */;
  20555. }
  20556. if (dynamicPropNames.length) {
  20557. patchFlag |= 8 /* PatchFlags.PROPS */;
  20558. }
  20559. if (hasHydrationEventBinding) {
  20560. patchFlag |= 32 /* PatchFlags.HYDRATE_EVENTS */;
  20561. }
  20562. }
  20563. if (!shouldUseBlock &&
  20564. (patchFlag === 0 || patchFlag === 32 /* PatchFlags.HYDRATE_EVENTS */) &&
  20565. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  20566. patchFlag |= 512 /* PatchFlags.NEED_PATCH */;
  20567. }
  20568. // pre-normalize props, SSR is skipped for now
  20569. if (!context.inSSR && propsExpression) {
  20570. switch (propsExpression.type) {
  20571. case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
  20572. // means that there is no v-bind,
  20573. // but still need to deal with dynamic key binding
  20574. let classKeyIndex = -1;
  20575. let styleKeyIndex = -1;
  20576. let hasDynamicKey = false;
  20577. for (let i = 0; i < propsExpression.properties.length; i++) {
  20578. const key = propsExpression.properties[i].key;
  20579. if (isStaticExp(key)) {
  20580. if (key.content === 'class') {
  20581. classKeyIndex = i;
  20582. }
  20583. else if (key.content === 'style') {
  20584. styleKeyIndex = i;
  20585. }
  20586. }
  20587. else if (!key.isHandlerKey) {
  20588. hasDynamicKey = true;
  20589. }
  20590. }
  20591. const classProp = propsExpression.properties[classKeyIndex];
  20592. const styleProp = propsExpression.properties[styleKeyIndex];
  20593. // no dynamic key
  20594. if (!hasDynamicKey) {
  20595. if (classProp && !isStaticExp(classProp.value)) {
  20596. classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
  20597. }
  20598. if (styleProp &&
  20599. // the static style is compiled into an object,
  20600. // so use `hasStyleBinding` to ensure that it is a dynamic style binding
  20601. (hasStyleBinding ||
  20602. (styleProp.value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  20603. styleProp.value.content.trim()[0] === `[`) ||
  20604. // v-bind:style and style both exist,
  20605. // v-bind:style with static literal object
  20606. styleProp.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */)) {
  20607. styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
  20608. }
  20609. }
  20610. else {
  20611. // dynamic key binding, wrap with `normalizeProps`
  20612. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
  20613. }
  20614. break;
  20615. case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
  20616. // mergeProps call, do nothing
  20617. break;
  20618. default:
  20619. // single v-bind
  20620. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
  20621. createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
  20622. propsExpression
  20623. ])
  20624. ]);
  20625. break;
  20626. }
  20627. }
  20628. return {
  20629. props: propsExpression,
  20630. directives: runtimeDirectives,
  20631. patchFlag,
  20632. dynamicPropNames,
  20633. shouldUseBlock
  20634. };
  20635. }
  20636. // Dedupe props in an object literal.
  20637. // Literal duplicated attributes would have been warned during the parse phase,
  20638. // however, it's possible to encounter duplicated `onXXX` handlers with different
  20639. // modifiers. We also need to merge static and dynamic class / style attributes.
  20640. // - onXXX handlers / style: merge into array
  20641. // - class: merge into single expression with concatenation
  20642. function dedupeProperties(properties) {
  20643. const knownProps = new Map();
  20644. const deduped = [];
  20645. for (let i = 0; i < properties.length; i++) {
  20646. const prop = properties[i];
  20647. // dynamic keys are always allowed
  20648. if (prop.key.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  20649. deduped.push(prop);
  20650. continue;
  20651. }
  20652. const name = prop.key.content;
  20653. const existing = knownProps.get(name);
  20654. if (existing) {
  20655. if (name === 'style' || name === 'class' || isOn(name)) {
  20656. mergeAsArray(existing, prop);
  20657. }
  20658. // unexpected duplicate, should have emitted error during parse
  20659. }
  20660. else {
  20661. knownProps.set(name, prop);
  20662. deduped.push(prop);
  20663. }
  20664. }
  20665. return deduped;
  20666. }
  20667. function mergeAsArray(existing, incoming) {
  20668. if (existing.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */) {
  20669. existing.value.elements.push(incoming.value);
  20670. }
  20671. else {
  20672. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  20673. }
  20674. }
  20675. function buildDirectiveArgs(dir, context) {
  20676. const dirArgs = [];
  20677. const runtime = directiveImportMap.get(dir);
  20678. if (runtime) {
  20679. // built-in directive with runtime
  20680. dirArgs.push(context.helperString(runtime));
  20681. }
  20682. else {
  20683. // user directive.
  20684. // see if we have directives exposed via <script setup>
  20685. const fromSetup = resolveSetupReference('v-' + dir.name, context);
  20686. if (fromSetup) {
  20687. dirArgs.push(fromSetup);
  20688. }
  20689. else {
  20690. // inject statement for resolving directive
  20691. context.helper(RESOLVE_DIRECTIVE);
  20692. context.directives.add(dir.name);
  20693. dirArgs.push(toValidAssetId(dir.name, `directive`));
  20694. }
  20695. }
  20696. const { loc } = dir;
  20697. if (dir.exp)
  20698. dirArgs.push(dir.exp);
  20699. if (dir.arg) {
  20700. if (!dir.exp) {
  20701. dirArgs.push(`void 0`);
  20702. }
  20703. dirArgs.push(dir.arg);
  20704. }
  20705. if (Object.keys(dir.modifiers).length) {
  20706. if (!dir.arg) {
  20707. if (!dir.exp) {
  20708. dirArgs.push(`void 0`);
  20709. }
  20710. dirArgs.push(`void 0`);
  20711. }
  20712. const trueExpression = createSimpleExpression(`true`, false, loc);
  20713. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  20714. }
  20715. return createArrayExpression(dirArgs, dir.loc);
  20716. }
  20717. function stringifyDynamicPropNames(props) {
  20718. let propsNamesString = `[`;
  20719. for (let i = 0, l = props.length; i < l; i++) {
  20720. propsNamesString += JSON.stringify(props[i]);
  20721. if (i < l - 1)
  20722. propsNamesString += ', ';
  20723. }
  20724. return propsNamesString + `]`;
  20725. }
  20726. function isComponentTag(tag) {
  20727. return tag === 'component' || tag === 'Component';
  20728. }
  20729. const transformSlotOutlet = (node, context) => {
  20730. if (isSlotOutlet(node)) {
  20731. const { children, loc } = node;
  20732. const { slotName, slotProps } = processSlotOutlet(node, context);
  20733. const slotArgs = [
  20734. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  20735. slotName,
  20736. '{}',
  20737. 'undefined',
  20738. 'true'
  20739. ];
  20740. let expectedLen = 2;
  20741. if (slotProps) {
  20742. slotArgs[2] = slotProps;
  20743. expectedLen = 3;
  20744. }
  20745. if (children.length) {
  20746. slotArgs[3] = createFunctionExpression([], children, false, false, loc);
  20747. expectedLen = 4;
  20748. }
  20749. if (context.scopeId && !context.slotted) {
  20750. expectedLen = 5;
  20751. }
  20752. slotArgs.splice(expectedLen); // remove unused arguments
  20753. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  20754. }
  20755. };
  20756. function processSlotOutlet(node, context) {
  20757. let slotName = `"default"`;
  20758. let slotProps = undefined;
  20759. const nonNameProps = [];
  20760. for (let i = 0; i < node.props.length; i++) {
  20761. const p = node.props[i];
  20762. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  20763. if (p.value) {
  20764. if (p.name === 'name') {
  20765. slotName = JSON.stringify(p.value.content);
  20766. }
  20767. else {
  20768. p.name = camelize(p.name);
  20769. nonNameProps.push(p);
  20770. }
  20771. }
  20772. }
  20773. else {
  20774. if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
  20775. if (p.exp)
  20776. slotName = p.exp;
  20777. }
  20778. else {
  20779. if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
  20780. p.arg.content = camelize(p.arg.content);
  20781. }
  20782. nonNameProps.push(p);
  20783. }
  20784. }
  20785. }
  20786. if (nonNameProps.length > 0) {
  20787. const { props, directives } = buildProps(node, context, nonNameProps, false, false);
  20788. slotProps = props;
  20789. if (directives.length) {
  20790. context.onError(createCompilerError(36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  20791. }
  20792. }
  20793. return {
  20794. slotName,
  20795. slotProps
  20796. };
  20797. }
  20798. const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*(:[^=]+)?=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
  20799. const transformOn$1 = (dir, node, context, augmentor) => {
  20800. const { loc, modifiers, arg } = dir;
  20801. if (!dir.exp && !modifiers.length) {
  20802. context.onError(createCompilerError(35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
  20803. }
  20804. let eventName;
  20805. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  20806. if (arg.isStatic) {
  20807. let rawName = arg.content;
  20808. // TODO deprecate @vnodeXXX usage
  20809. if (rawName.startsWith('vue:')) {
  20810. rawName = `vnode-${rawName.slice(4)}`;
  20811. }
  20812. const eventString = node.tagType !== 0 /* ElementTypes.ELEMENT */ ||
  20813. rawName.startsWith('vnode') ||
  20814. !/[A-Z]/.test(rawName)
  20815. ? // for non-element and vnode lifecycle event listeners, auto convert
  20816. // it to camelCase. See issue #2249
  20817. toHandlerKey(camelize(rawName))
  20818. : // preserve case for plain element listeners that have uppercase
  20819. // letters, as these may be custom elements' custom events
  20820. `on:${rawName}`;
  20821. eventName = createSimpleExpression(eventString, true, arg.loc);
  20822. }
  20823. else {
  20824. // #2388
  20825. eventName = createCompoundExpression([
  20826. `${context.helperString(TO_HANDLER_KEY)}(`,
  20827. arg,
  20828. `)`
  20829. ]);
  20830. }
  20831. }
  20832. else {
  20833. // already a compound expression.
  20834. eventName = arg;
  20835. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  20836. eventName.children.push(`)`);
  20837. }
  20838. // handler processing
  20839. let exp = dir.exp;
  20840. if (exp && !exp.content.trim()) {
  20841. exp = undefined;
  20842. }
  20843. let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
  20844. if (exp) {
  20845. const isMemberExp = isMemberExpression(exp.content, context);
  20846. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  20847. const hasMultipleStatements = exp.content.includes(`;`);
  20848. // process the expression since it's been skipped
  20849. if (context.prefixIdentifiers) {
  20850. isInlineStatement && context.addIdentifiers(`$event`);
  20851. exp = dir.exp = processExpression(exp, context, false, hasMultipleStatements);
  20852. isInlineStatement && context.removeIdentifiers(`$event`);
  20853. // with scope analysis, the function is hoistable if it has no reference
  20854. // to scope variables.
  20855. shouldCache =
  20856. context.cacheHandlers &&
  20857. // unnecessary to cache inside v-once
  20858. !context.inVOnce &&
  20859. // runtime constants don't need to be cached
  20860. // (this is analyzed by compileScript in SFC <script setup>)
  20861. !(exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && exp.constType > 0) &&
  20862. // #1541 bail if this is a member exp handler passed to a component -
  20863. // we need to use the original function to preserve arity,
  20864. // e.g. <transition> relies on checking cb.length to determine
  20865. // transition end handling. Inline function is ok since its arity
  20866. // is preserved even when cached.
  20867. !(isMemberExp && node.tagType === 1 /* ElementTypes.COMPONENT */) &&
  20868. // bail if the function references closure variables (v-for, v-slot)
  20869. // it must be passed fresh to avoid stale values.
  20870. !hasScopeRef(exp, context.identifiers);
  20871. // If the expression is optimizable and is a member expression pointing
  20872. // to a function, turn it into invocation (and wrap in an arrow function
  20873. // below) so that it always accesses the latest value when called - thus
  20874. // avoiding the need to be patched.
  20875. if (shouldCache && isMemberExp) {
  20876. if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  20877. exp.content = `${exp.content} && ${exp.content}(...args)`;
  20878. }
  20879. else {
  20880. exp.children = [...exp.children, ` && `, ...exp.children, `(...args)`];
  20881. }
  20882. }
  20883. }
  20884. if (isInlineStatement || (shouldCache && isMemberExp)) {
  20885. // wrap inline statement in a function expression
  20886. exp = createCompoundExpression([
  20887. `${isInlineStatement
  20888. ? context.isTS
  20889. ? `($event: any)`
  20890. : `$event`
  20891. : `${context.isTS ? `\n//@ts-ignore\n` : ``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  20892. exp,
  20893. hasMultipleStatements ? `}` : `)`
  20894. ]);
  20895. }
  20896. }
  20897. let ret = {
  20898. props: [
  20899. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  20900. ]
  20901. };
  20902. // apply extended compiler augmentor
  20903. if (augmentor) {
  20904. ret = augmentor(ret);
  20905. }
  20906. if (shouldCache) {
  20907. // cache handlers so that it's always the same handler being passed down.
  20908. // this avoids unnecessary re-renders when users use inline handlers on
  20909. // components.
  20910. ret.props[0].value = context.cache(ret.props[0].value);
  20911. }
  20912. // mark the key as handler for props normalization check
  20913. ret.props.forEach(p => (p.key.isHandlerKey = true));
  20914. return ret;
  20915. };
  20916. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  20917. // codegen for the entire props object. This transform here is only for v-bind
  20918. // *with* args.
  20919. const transformBind = (dir, _node, context) => {
  20920. const { exp, modifiers, loc } = dir;
  20921. const arg = dir.arg;
  20922. if (arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  20923. arg.children.unshift(`(`);
  20924. arg.children.push(`) || ""`);
  20925. }
  20926. else if (!arg.isStatic) {
  20927. arg.content = `${arg.content} || ""`;
  20928. }
  20929. // .sync is replaced by v-model:arg
  20930. if (modifiers.includes('camel')) {
  20931. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  20932. if (arg.isStatic) {
  20933. arg.content = camelize(arg.content);
  20934. }
  20935. else {
  20936. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  20937. }
  20938. }
  20939. else {
  20940. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  20941. arg.children.push(`)`);
  20942. }
  20943. }
  20944. if (!context.inSSR) {
  20945. if (modifiers.includes('prop')) {
  20946. injectPrefix(arg, '.');
  20947. }
  20948. if (modifiers.includes('attr')) {
  20949. injectPrefix(arg, '^');
  20950. }
  20951. }
  20952. if (!exp ||
  20953. (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  20954. context.onError(createCompilerError(34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */, loc));
  20955. return {
  20956. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  20957. };
  20958. }
  20959. return {
  20960. props: [createObjectProperty(arg, exp)]
  20961. };
  20962. };
  20963. const injectPrefix = (arg, prefix) => {
  20964. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  20965. if (arg.isStatic) {
  20966. arg.content = prefix + arg.content;
  20967. }
  20968. else {
  20969. arg.content = `\`${prefix}\${${arg.content}}\``;
  20970. }
  20971. }
  20972. else {
  20973. arg.children.unshift(`'${prefix}' + (`);
  20974. arg.children.push(`)`);
  20975. }
  20976. };
  20977. // Merge adjacent text nodes and expressions into a single expression
  20978. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  20979. const transformText = (node, context) => {
  20980. if (node.type === 0 /* NodeTypes.ROOT */ ||
  20981. node.type === 1 /* NodeTypes.ELEMENT */ ||
  20982. node.type === 11 /* NodeTypes.FOR */ ||
  20983. node.type === 10 /* NodeTypes.IF_BRANCH */) {
  20984. // perform the transform on node exit so that all expressions have already
  20985. // been processed.
  20986. return () => {
  20987. const children = node.children;
  20988. let currentContainer = undefined;
  20989. let hasText = false;
  20990. for (let i = 0; i < children.length; i++) {
  20991. const child = children[i];
  20992. if (isText$1(child)) {
  20993. hasText = true;
  20994. for (let j = i + 1; j < children.length; j++) {
  20995. const next = children[j];
  20996. if (isText$1(next)) {
  20997. if (!currentContainer) {
  20998. currentContainer = children[i] = createCompoundExpression([child], child.loc);
  20999. }
  21000. // merge adjacent text node into current
  21001. currentContainer.children.push(` + `, next);
  21002. children.splice(j, 1);
  21003. j--;
  21004. }
  21005. else {
  21006. currentContainer = undefined;
  21007. break;
  21008. }
  21009. }
  21010. }
  21011. }
  21012. if (!hasText ||
  21013. // if this is a plain element with a single text child, leave it
  21014. // as-is since the runtime has dedicated fast path for this by directly
  21015. // setting textContent of the element.
  21016. // for component root it's always normalized anyway.
  21017. (children.length === 1 &&
  21018. (node.type === 0 /* NodeTypes.ROOT */ ||
  21019. (node.type === 1 /* NodeTypes.ELEMENT */ &&
  21020. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  21021. // #3756
  21022. // custom directives can potentially add DOM elements arbitrarily,
  21023. // we need to avoid setting textContent of the element at runtime
  21024. // to avoid accidentally overwriting the DOM elements added
  21025. // by the user through custom directives.
  21026. !node.props.find(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  21027. !context.directiveTransforms[p.name]) &&
  21028. // in compat mode, <template> tags with no special directives
  21029. // will be rendered as a fragment so its children must be
  21030. // converted into vnodes.
  21031. !(false ))))) {
  21032. return;
  21033. }
  21034. // pre-convert text nodes into createTextVNode(text) calls to avoid
  21035. // runtime normalization.
  21036. for (let i = 0; i < children.length; i++) {
  21037. const child = children[i];
  21038. if (isText$1(child) || child.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  21039. const callArgs = [];
  21040. // createTextVNode defaults to single whitespace, so if it is a
  21041. // single space the code could be an empty call to save bytes.
  21042. if (child.type !== 2 /* NodeTypes.TEXT */ || child.content !== ' ') {
  21043. callArgs.push(child);
  21044. }
  21045. // mark dynamic text with flag so it gets patched inside a block
  21046. if (!context.ssr &&
  21047. getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
  21048. callArgs.push(1 /* PatchFlags.TEXT */ +
  21049. (` /* ${PatchFlagNames[1 /* PatchFlags.TEXT */]} */` ));
  21050. }
  21051. children[i] = {
  21052. type: 12 /* NodeTypes.TEXT_CALL */,
  21053. content: child,
  21054. loc: child.loc,
  21055. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  21056. };
  21057. }
  21058. }
  21059. };
  21060. }
  21061. };
  21062. const seen$1 = new WeakSet();
  21063. const transformOnce = (node, context) => {
  21064. if (node.type === 1 /* NodeTypes.ELEMENT */ && findDir(node, 'once', true)) {
  21065. if (seen$1.has(node) || context.inVOnce) {
  21066. return;
  21067. }
  21068. seen$1.add(node);
  21069. context.inVOnce = true;
  21070. context.helper(SET_BLOCK_TRACKING);
  21071. return () => {
  21072. context.inVOnce = false;
  21073. const cur = context.currentNode;
  21074. if (cur.codegenNode) {
  21075. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  21076. }
  21077. };
  21078. }
  21079. };
  21080. const transformModel$1 = (dir, node, context) => {
  21081. const { exp, arg } = dir;
  21082. if (!exp) {
  21083. context.onError(createCompilerError(41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */, dir.loc));
  21084. return createTransformProps();
  21085. }
  21086. const rawExp = exp.loc.source;
  21087. const expString = exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ? exp.content : rawExp;
  21088. // im SFC <script setup> inline mode, the exp may have been transformed into
  21089. // _unref(exp)
  21090. const bindingType = context.bindingMetadata[rawExp];
  21091. // check props
  21092. if (bindingType === "props" /* BindingTypes.PROPS */ ||
  21093. bindingType === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
  21094. context.onError(createCompilerError(44 /* ErrorCodes.X_V_MODEL_ON_PROPS */, exp.loc));
  21095. return createTransformProps();
  21096. }
  21097. const maybeRef = context.inline &&
  21098. (bindingType === "setup-let" /* BindingTypes.SETUP_LET */ ||
  21099. bindingType === "setup-ref" /* BindingTypes.SETUP_REF */ ||
  21100. bindingType === "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */);
  21101. if (!expString.trim() ||
  21102. (!isMemberExpression(expString, context) && !maybeRef)) {
  21103. context.onError(createCompilerError(42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  21104. return createTransformProps();
  21105. }
  21106. if (context.prefixIdentifiers &&
  21107. isSimpleIdentifier(expString) &&
  21108. context.identifiers[expString]) {
  21109. context.onError(createCompilerError(43 /* ErrorCodes.X_V_MODEL_ON_SCOPE_VARIABLE */, exp.loc));
  21110. return createTransformProps();
  21111. }
  21112. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  21113. const eventName = arg
  21114. ? isStaticExp(arg)
  21115. ? `onUpdate:${camelize(arg.content)}`
  21116. : createCompoundExpression(['"onUpdate:" + ', arg])
  21117. : `onUpdate:modelValue`;
  21118. let assignmentExp;
  21119. const eventArg = context.isTS ? `($event: any)` : `$event`;
  21120. if (maybeRef) {
  21121. if (bindingType === "setup-ref" /* BindingTypes.SETUP_REF */) {
  21122. // v-model used on known ref.
  21123. assignmentExp = createCompoundExpression([
  21124. `${eventArg} => ((`,
  21125. createSimpleExpression(rawExp, false, exp.loc),
  21126. `).value = $event)`
  21127. ]);
  21128. }
  21129. else {
  21130. // v-model used on a potentially ref binding in <script setup> inline mode.
  21131. // the assignment needs to check whether the binding is actually a ref.
  21132. const altAssignment = bindingType === "setup-let" /* BindingTypes.SETUP_LET */ ? `${rawExp} = $event` : `null`;
  21133. assignmentExp = createCompoundExpression([
  21134. `${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? (`,
  21135. createSimpleExpression(rawExp, false, exp.loc),
  21136. `).value = $event : ${altAssignment})`
  21137. ]);
  21138. }
  21139. }
  21140. else {
  21141. assignmentExp = createCompoundExpression([
  21142. `${eventArg} => ((`,
  21143. exp,
  21144. `) = $event)`
  21145. ]);
  21146. }
  21147. const props = [
  21148. // modelValue: foo
  21149. createObjectProperty(propName, dir.exp),
  21150. // "onUpdate:modelValue": $event => (foo = $event)
  21151. createObjectProperty(eventName, assignmentExp)
  21152. ];
  21153. // cache v-model handler if applicable (when it doesn't refer any scope vars)
  21154. if (context.prefixIdentifiers &&
  21155. !context.inVOnce &&
  21156. context.cacheHandlers &&
  21157. !hasScopeRef(exp, context.identifiers)) {
  21158. props[1].value = context.cache(props[1].value);
  21159. }
  21160. // modelModifiers: { foo: true, "bar-baz": true }
  21161. if (dir.modifiers.length && node.tagType === 1 /* ElementTypes.COMPONENT */) {
  21162. const modifiers = dir.modifiers
  21163. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  21164. .join(`, `);
  21165. const modifiersKey = arg
  21166. ? isStaticExp(arg)
  21167. ? `${arg.content}Modifiers`
  21168. : createCompoundExpression([arg, ' + "Modifiers"'])
  21169. : `modelModifiers`;
  21170. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* ConstantTypes.CAN_HOIST */)));
  21171. }
  21172. return createTransformProps(props);
  21173. };
  21174. function createTransformProps(props = []) {
  21175. return { props };
  21176. }
  21177. const seen = new WeakSet();
  21178. const transformMemo = (node, context) => {
  21179. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  21180. const dir = findDir(node, 'memo');
  21181. if (!dir || seen.has(node)) {
  21182. return;
  21183. }
  21184. seen.add(node);
  21185. return () => {
  21186. const codegenNode = node.codegenNode ||
  21187. context.currentNode.codegenNode;
  21188. if (codegenNode && codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  21189. // non-component sub tree should be turned into a block
  21190. if (node.tagType !== 1 /* ElementTypes.COMPONENT */) {
  21191. makeBlock(codegenNode, context);
  21192. }
  21193. node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
  21194. dir.exp,
  21195. createFunctionExpression(undefined, codegenNode),
  21196. `_cache`,
  21197. String(context.cached++)
  21198. ]);
  21199. }
  21200. };
  21201. }
  21202. };
  21203. function getBaseTransformPreset(prefixIdentifiers) {
  21204. return [
  21205. [
  21206. transformOnce,
  21207. transformIf,
  21208. transformMemo,
  21209. transformFor,
  21210. ...([]),
  21211. ...(prefixIdentifiers
  21212. ? [
  21213. // order is important
  21214. trackVForSlotScopes,
  21215. transformExpression
  21216. ]
  21217. : []),
  21218. transformSlotOutlet,
  21219. transformElement,
  21220. trackSlotScopes,
  21221. transformText
  21222. ],
  21223. {
  21224. on: transformOn$1,
  21225. bind: transformBind,
  21226. model: transformModel$1
  21227. }
  21228. ];
  21229. }
  21230. // we name it `baseCompile` so that higher order compilers like
  21231. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  21232. function baseCompile(template, options = {}) {
  21233. const onError = options.onError || defaultOnError;
  21234. const isModuleMode = options.mode === 'module';
  21235. const prefixIdentifiers = (options.prefixIdentifiers === true || isModuleMode);
  21236. if (!prefixIdentifiers && options.cacheHandlers) {
  21237. onError(createCompilerError(49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */));
  21238. }
  21239. if (options.scopeId && !isModuleMode) {
  21240. onError(createCompilerError(50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */));
  21241. }
  21242. const ast = isString$2(template) ? baseParse(template, options) : template;
  21243. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(prefixIdentifiers);
  21244. if (options.isTS) {
  21245. const { expressionPlugins } = options;
  21246. if (!expressionPlugins || !expressionPlugins.includes('typescript')) {
  21247. options.expressionPlugins = [...(expressionPlugins || []), 'typescript'];
  21248. }
  21249. }
  21250. transform$1(ast, extend({}, options, {
  21251. prefixIdentifiers,
  21252. nodeTransforms: [
  21253. ...nodeTransforms,
  21254. ...(options.nodeTransforms || []) // user transforms
  21255. ],
  21256. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  21257. )
  21258. }));
  21259. return generate(ast, extend({}, options, {
  21260. prefixIdentifiers
  21261. }));
  21262. }
  21263. const noopDirectiveTransform = () => ({ props: [] });
  21264. const V_MODEL_RADIO = Symbol(`vModelRadio` );
  21265. const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
  21266. const V_MODEL_TEXT = Symbol(`vModelText` );
  21267. const V_MODEL_SELECT = Symbol(`vModelSelect` );
  21268. const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
  21269. const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
  21270. const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
  21271. const V_SHOW = Symbol(`vShow` );
  21272. const TRANSITION = Symbol(`Transition` );
  21273. const TRANSITION_GROUP = Symbol(`TransitionGroup` );
  21274. registerRuntimeHelpers({
  21275. [V_MODEL_RADIO]: `vModelRadio`,
  21276. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  21277. [V_MODEL_TEXT]: `vModelText`,
  21278. [V_MODEL_SELECT]: `vModelSelect`,
  21279. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  21280. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  21281. [V_ON_WITH_KEYS]: `withKeys`,
  21282. [V_SHOW]: `vShow`,
  21283. [TRANSITION]: `Transition`,
  21284. [TRANSITION_GROUP]: `TransitionGroup`
  21285. });
  21286. var namedCharacterReferences = {
  21287. GT: ">",
  21288. gt: ">",
  21289. LT: "<",
  21290. lt: "<",
  21291. "ac;": "∾",
  21292. "af;": "⁡",
  21293. AMP: "&",
  21294. amp: "&",
  21295. "ap;": "≈",
  21296. "DD;": "ⅅ",
  21297. "dd;": "ⅆ",
  21298. deg: "°",
  21299. "ee;": "ⅇ",
  21300. "eg;": "⪚",
  21301. "el;": "⪙",
  21302. ETH: "Ð",
  21303. eth: "ð",
  21304. "gE;": "≧",
  21305. "ge;": "≥",
  21306. "Gg;": "⋙",
  21307. "gg;": "≫",
  21308. "gl;": "≷",
  21309. "GT;": ">",
  21310. "Gt;": "≫",
  21311. "gt;": ">",
  21312. "ic;": "⁣",
  21313. "ii;": "ⅈ",
  21314. "Im;": "ℑ",
  21315. "in;": "∈",
  21316. "it;": "⁢",
  21317. "lE;": "≦",
  21318. "le;": "≤",
  21319. "lg;": "≶",
  21320. "Ll;": "⋘",
  21321. "ll;": "≪",
  21322. "LT;": "<",
  21323. "Lt;": "≪",
  21324. "lt;": "<",
  21325. "mp;": "∓",
  21326. "Mu;": "Μ",
  21327. "mu;": "μ",
  21328. "ne;": "≠",
  21329. "ni;": "∋",
  21330. not: "¬",
  21331. "Nu;": "Ν",
  21332. "nu;": "ν",
  21333. "Or;": "⩔",
  21334. "or;": "∨",
  21335. "oS;": "Ⓢ",
  21336. "Pi;": "Π",
  21337. "pi;": "π",
  21338. "pm;": "±",
  21339. "Pr;": "⪻",
  21340. "pr;": "≺",
  21341. "Re;": "ℜ",
  21342. REG: "®",
  21343. reg: "®",
  21344. "rx;": "℞",
  21345. "Sc;": "⪼",
  21346. "sc;": "≻",
  21347. shy: "­",
  21348. uml: "¨",
  21349. "wp;": "℘",
  21350. "wr;": "≀",
  21351. "Xi;": "Ξ",
  21352. "xi;": "ξ",
  21353. yen: "¥",
  21354. "acd;": "∿",
  21355. "acE;": "∾̳",
  21356. "Acy;": "А",
  21357. "acy;": "а",
  21358. "Afr;": "𝔄",
  21359. "afr;": "𝔞",
  21360. "AMP;": "&",
  21361. "amp;": "&",
  21362. "And;": "⩓",
  21363. "and;": "∧",
  21364. "ang;": "∠",
  21365. "apE;": "⩰",
  21366. "ape;": "≊",
  21367. "ast;": "*",
  21368. Auml: "Ä",
  21369. auml: "ä",
  21370. "Bcy;": "Б",
  21371. "bcy;": "б",
  21372. "Bfr;": "𝔅",
  21373. "bfr;": "𝔟",
  21374. "bne;": "=⃥",
  21375. "bot;": "⊥",
  21376. "Cap;": "⋒",
  21377. "cap;": "∩",
  21378. cent: "¢",
  21379. "Cfr;": "ℭ",
  21380. "cfr;": "𝔠",
  21381. "Chi;": "Χ",
  21382. "chi;": "χ",
  21383. "cir;": "○",
  21384. COPY: "©",
  21385. copy: "©",
  21386. "Cup;": "⋓",
  21387. "cup;": "∪",
  21388. "Dcy;": "Д",
  21389. "dcy;": "д",
  21390. "deg;": "°",
  21391. "Del;": "∇",
  21392. "Dfr;": "𝔇",
  21393. "dfr;": "𝔡",
  21394. "die;": "¨",
  21395. "div;": "÷",
  21396. "Dot;": "¨",
  21397. "dot;": "˙",
  21398. "Ecy;": "Э",
  21399. "ecy;": "э",
  21400. "Efr;": "𝔈",
  21401. "efr;": "𝔢",
  21402. "egs;": "⪖",
  21403. "ell;": "ℓ",
  21404. "els;": "⪕",
  21405. "ENG;": "Ŋ",
  21406. "eng;": "ŋ",
  21407. "Eta;": "Η",
  21408. "eta;": "η",
  21409. "ETH;": "Ð",
  21410. "eth;": "ð",
  21411. Euml: "Ë",
  21412. euml: "ë",
  21413. "Fcy;": "Ф",
  21414. "fcy;": "ф",
  21415. "Ffr;": "𝔉",
  21416. "ffr;": "𝔣",
  21417. "gap;": "⪆",
  21418. "Gcy;": "Г",
  21419. "gcy;": "г",
  21420. "gEl;": "⪌",
  21421. "gel;": "⋛",
  21422. "geq;": "≥",
  21423. "ges;": "⩾",
  21424. "Gfr;": "𝔊",
  21425. "gfr;": "𝔤",
  21426. "ggg;": "⋙",
  21427. "gla;": "⪥",
  21428. "glE;": "⪒",
  21429. "glj;": "⪤",
  21430. "gnE;": "≩",
  21431. "gne;": "⪈",
  21432. "Hat;": "^",
  21433. "Hfr;": "ℌ",
  21434. "hfr;": "𝔥",
  21435. "Icy;": "И",
  21436. "icy;": "и",
  21437. "iff;": "⇔",
  21438. "Ifr;": "ℑ",
  21439. "ifr;": "𝔦",
  21440. "Int;": "∬",
  21441. "int;": "∫",
  21442. Iuml: "Ï",
  21443. iuml: "ï",
  21444. "Jcy;": "Й",
  21445. "jcy;": "й",
  21446. "Jfr;": "𝔍",
  21447. "jfr;": "𝔧",
  21448. "Kcy;": "К",
  21449. "kcy;": "к",
  21450. "Kfr;": "𝔎",
  21451. "kfr;": "𝔨",
  21452. "lap;": "⪅",
  21453. "lat;": "⪫",
  21454. "Lcy;": "Л",
  21455. "lcy;": "л",
  21456. "lEg;": "⪋",
  21457. "leg;": "⋚",
  21458. "leq;": "≤",
  21459. "les;": "⩽",
  21460. "Lfr;": "𝔏",
  21461. "lfr;": "𝔩",
  21462. "lgE;": "⪑",
  21463. "lnE;": "≨",
  21464. "lne;": "⪇",
  21465. "loz;": "◊",
  21466. "lrm;": "‎",
  21467. "Lsh;": "↰",
  21468. "lsh;": "↰",
  21469. macr: "¯",
  21470. "Map;": "⤅",
  21471. "map;": "↦",
  21472. "Mcy;": "М",
  21473. "mcy;": "м",
  21474. "Mfr;": "𝔐",
  21475. "mfr;": "𝔪",
  21476. "mho;": "℧",
  21477. "mid;": "∣",
  21478. "nap;": "≉",
  21479. nbsp: " ",
  21480. "Ncy;": "Н",
  21481. "ncy;": "н",
  21482. "Nfr;": "𝔑",
  21483. "nfr;": "𝔫",
  21484. "ngE;": "≧̸",
  21485. "nge;": "≱",
  21486. "nGg;": "⋙̸",
  21487. "nGt;": "≫⃒",
  21488. "ngt;": "≯",
  21489. "nis;": "⋼",
  21490. "niv;": "∋",
  21491. "nlE;": "≦̸",
  21492. "nle;": "≰",
  21493. "nLl;": "⋘̸",
  21494. "nLt;": "≪⃒",
  21495. "nlt;": "≮",
  21496. "Not;": "⫬",
  21497. "not;": "¬",
  21498. "npr;": "⊀",
  21499. "nsc;": "⊁",
  21500. "num;": "#",
  21501. "Ocy;": "О",
  21502. "ocy;": "о",
  21503. "Ofr;": "𝔒",
  21504. "ofr;": "𝔬",
  21505. "ogt;": "⧁",
  21506. "ohm;": "Ω",
  21507. "olt;": "⧀",
  21508. "ord;": "⩝",
  21509. ordf: "ª",
  21510. ordm: "º",
  21511. "orv;": "⩛",
  21512. Ouml: "Ö",
  21513. ouml: "ö",
  21514. "par;": "∥",
  21515. para: "¶",
  21516. "Pcy;": "П",
  21517. "pcy;": "п",
  21518. "Pfr;": "𝔓",
  21519. "pfr;": "𝔭",
  21520. "Phi;": "Φ",
  21521. "phi;": "φ",
  21522. "piv;": "ϖ",
  21523. "prE;": "⪳",
  21524. "pre;": "⪯",
  21525. "Psi;": "Ψ",
  21526. "psi;": "ψ",
  21527. "Qfr;": "𝔔",
  21528. "qfr;": "𝔮",
  21529. QUOT: "\"",
  21530. quot: "\"",
  21531. "Rcy;": "Р",
  21532. "rcy;": "р",
  21533. "REG;": "®",
  21534. "reg;": "®",
  21535. "Rfr;": "ℜ",
  21536. "rfr;": "𝔯",
  21537. "Rho;": "Ρ",
  21538. "rho;": "ρ",
  21539. "rlm;": "‏",
  21540. "Rsh;": "↱",
  21541. "rsh;": "↱",
  21542. "scE;": "⪴",
  21543. "sce;": "⪰",
  21544. "Scy;": "С",
  21545. "scy;": "с",
  21546. sect: "§",
  21547. "Sfr;": "𝔖",
  21548. "sfr;": "𝔰",
  21549. "shy;": "­",
  21550. "sim;": "∼",
  21551. "smt;": "⪪",
  21552. "sol;": "/",
  21553. "squ;": "□",
  21554. "Sub;": "⋐",
  21555. "sub;": "⊂",
  21556. "Sum;": "∑",
  21557. "sum;": "∑",
  21558. "Sup;": "⋑",
  21559. "sup;": "⊃",
  21560. sup1: "¹",
  21561. sup2: "²",
  21562. sup3: "³",
  21563. "Tab;": "\t",
  21564. "Tau;": "Τ",
  21565. "tau;": "τ",
  21566. "Tcy;": "Т",
  21567. "tcy;": "т",
  21568. "Tfr;": "𝔗",
  21569. "tfr;": "𝔱",
  21570. "top;": "⊤",
  21571. "Ucy;": "У",
  21572. "ucy;": "у",
  21573. "Ufr;": "𝔘",
  21574. "ufr;": "𝔲",
  21575. "uml;": "¨",
  21576. Uuml: "Ü",
  21577. uuml: "ü",
  21578. "Vcy;": "В",
  21579. "vcy;": "в",
  21580. "Vee;": "⋁",
  21581. "vee;": "∨",
  21582. "Vfr;": "𝔙",
  21583. "vfr;": "𝔳",
  21584. "Wfr;": "𝔚",
  21585. "wfr;": "𝔴",
  21586. "Xfr;": "𝔛",
  21587. "xfr;": "𝔵",
  21588. "Ycy;": "Ы",
  21589. "ycy;": "ы",
  21590. "yen;": "¥",
  21591. "Yfr;": "𝔜",
  21592. "yfr;": "𝔶",
  21593. yuml: "ÿ",
  21594. "Zcy;": "З",
  21595. "zcy;": "з",
  21596. "Zfr;": "ℨ",
  21597. "zfr;": "𝔷",
  21598. "zwj;": "‍",
  21599. Acirc: "Â",
  21600. acirc: "â",
  21601. acute: "´",
  21602. AElig: "Æ",
  21603. aelig: "æ",
  21604. "andd;": "⩜",
  21605. "andv;": "⩚",
  21606. "ange;": "⦤",
  21607. "Aopf;": "𝔸",
  21608. "aopf;": "𝕒",
  21609. "apid;": "≋",
  21610. "apos;": "'",
  21611. Aring: "Å",
  21612. aring: "å",
  21613. "Ascr;": "𝒜",
  21614. "ascr;": "𝒶",
  21615. "Auml;": "Ä",
  21616. "auml;": "ä",
  21617. "Barv;": "⫧",
  21618. "bbrk;": "⎵",
  21619. "Beta;": "Β",
  21620. "beta;": "β",
  21621. "beth;": "ℶ",
  21622. "bNot;": "⫭",
  21623. "bnot;": "⌐",
  21624. "Bopf;": "𝔹",
  21625. "bopf;": "𝕓",
  21626. "boxH;": "═",
  21627. "boxh;": "─",
  21628. "boxV;": "║",
  21629. "boxv;": "│",
  21630. "Bscr;": "ℬ",
  21631. "bscr;": "𝒷",
  21632. "bsim;": "∽",
  21633. "bsol;": "\\",
  21634. "bull;": "•",
  21635. "bump;": "≎",
  21636. "caps;": "∩︀",
  21637. "Cdot;": "Ċ",
  21638. "cdot;": "ċ",
  21639. cedil: "¸",
  21640. "cent;": "¢",
  21641. "CHcy;": "Ч",
  21642. "chcy;": "ч",
  21643. "circ;": "ˆ",
  21644. "cirE;": "⧃",
  21645. "cire;": "≗",
  21646. "comp;": "∁",
  21647. "cong;": "≅",
  21648. "Copf;": "ℂ",
  21649. "copf;": "𝕔",
  21650. "COPY;": "©",
  21651. "copy;": "©",
  21652. "Cscr;": "𝒞",
  21653. "cscr;": "𝒸",
  21654. "csub;": "⫏",
  21655. "csup;": "⫐",
  21656. "cups;": "∪︀",
  21657. "Darr;": "↡",
  21658. "dArr;": "⇓",
  21659. "darr;": "↓",
  21660. "dash;": "‐",
  21661. "dHar;": "⥥",
  21662. "diam;": "⋄",
  21663. "DJcy;": "Ђ",
  21664. "djcy;": "ђ",
  21665. "Dopf;": "𝔻",
  21666. "dopf;": "𝕕",
  21667. "Dscr;": "𝒟",
  21668. "dscr;": "𝒹",
  21669. "DScy;": "Ѕ",
  21670. "dscy;": "ѕ",
  21671. "dsol;": "⧶",
  21672. "dtri;": "▿",
  21673. "DZcy;": "Џ",
  21674. "dzcy;": "џ",
  21675. "ecir;": "≖",
  21676. Ecirc: "Ê",
  21677. ecirc: "ê",
  21678. "Edot;": "Ė",
  21679. "eDot;": "≑",
  21680. "edot;": "ė",
  21681. "emsp;": " ",
  21682. "ensp;": " ",
  21683. "Eopf;": "𝔼",
  21684. "eopf;": "𝕖",
  21685. "epar;": "⋕",
  21686. "epsi;": "ε",
  21687. "Escr;": "ℰ",
  21688. "escr;": "ℯ",
  21689. "Esim;": "⩳",
  21690. "esim;": "≂",
  21691. "Euml;": "Ë",
  21692. "euml;": "ë",
  21693. "euro;": "€",
  21694. "excl;": "!",
  21695. "flat;": "♭",
  21696. "fnof;": "ƒ",
  21697. "Fopf;": "𝔽",
  21698. "fopf;": "𝕗",
  21699. "fork;": "⋔",
  21700. "Fscr;": "ℱ",
  21701. "fscr;": "𝒻",
  21702. "Gdot;": "Ġ",
  21703. "gdot;": "ġ",
  21704. "geqq;": "≧",
  21705. "gesl;": "⋛︀",
  21706. "GJcy;": "Ѓ",
  21707. "gjcy;": "ѓ",
  21708. "gnap;": "⪊",
  21709. "gneq;": "⪈",
  21710. "Gopf;": "𝔾",
  21711. "gopf;": "𝕘",
  21712. "Gscr;": "𝒢",
  21713. "gscr;": "ℊ",
  21714. "gsim;": "≳",
  21715. "gtcc;": "⪧",
  21716. "gvnE;": "≩︀",
  21717. "half;": "½",
  21718. "hArr;": "⇔",
  21719. "harr;": "↔",
  21720. "hbar;": "ℏ",
  21721. "Hopf;": "ℍ",
  21722. "hopf;": "𝕙",
  21723. "Hscr;": "ℋ",
  21724. "hscr;": "𝒽",
  21725. Icirc: "Î",
  21726. icirc: "î",
  21727. "Idot;": "İ",
  21728. "IEcy;": "Е",
  21729. "iecy;": "е",
  21730. iexcl: "¡",
  21731. "imof;": "⊷",
  21732. "IOcy;": "Ё",
  21733. "iocy;": "ё",
  21734. "Iopf;": "𝕀",
  21735. "iopf;": "𝕚",
  21736. "Iota;": "Ι",
  21737. "iota;": "ι",
  21738. "Iscr;": "ℐ",
  21739. "iscr;": "𝒾",
  21740. "isin;": "∈",
  21741. "Iuml;": "Ï",
  21742. "iuml;": "ï",
  21743. "Jopf;": "𝕁",
  21744. "jopf;": "𝕛",
  21745. "Jscr;": "𝒥",
  21746. "jscr;": "𝒿",
  21747. "KHcy;": "Х",
  21748. "khcy;": "х",
  21749. "KJcy;": "Ќ",
  21750. "kjcy;": "ќ",
  21751. "Kopf;": "𝕂",
  21752. "kopf;": "𝕜",
  21753. "Kscr;": "𝒦",
  21754. "kscr;": "𝓀",
  21755. "Lang;": "⟪",
  21756. "lang;": "⟨",
  21757. laquo: "«",
  21758. "Larr;": "↞",
  21759. "lArr;": "⇐",
  21760. "larr;": "←",
  21761. "late;": "⪭",
  21762. "lcub;": "{",
  21763. "ldca;": "⤶",
  21764. "ldsh;": "↲",
  21765. "leqq;": "≦",
  21766. "lesg;": "⋚︀",
  21767. "lHar;": "⥢",
  21768. "LJcy;": "Љ",
  21769. "ljcy;": "љ",
  21770. "lnap;": "⪉",
  21771. "lneq;": "⪇",
  21772. "Lopf;": "𝕃",
  21773. "lopf;": "𝕝",
  21774. "lozf;": "⧫",
  21775. "lpar;": "(",
  21776. "Lscr;": "ℒ",
  21777. "lscr;": "𝓁",
  21778. "lsim;": "≲",
  21779. "lsqb;": "[",
  21780. "ltcc;": "⪦",
  21781. "ltri;": "◃",
  21782. "lvnE;": "≨︀",
  21783. "macr;": "¯",
  21784. "male;": "♂",
  21785. "malt;": "✠",
  21786. micro: "µ",
  21787. "mlcp;": "⫛",
  21788. "mldr;": "…",
  21789. "Mopf;": "𝕄",
  21790. "mopf;": "𝕞",
  21791. "Mscr;": "ℳ",
  21792. "mscr;": "𝓂",
  21793. "nang;": "∠⃒",
  21794. "napE;": "⩰̸",
  21795. "nbsp;": " ",
  21796. "ncap;": "⩃",
  21797. "ncup;": "⩂",
  21798. "ngeq;": "≱",
  21799. "nges;": "⩾̸",
  21800. "ngtr;": "≯",
  21801. "nGtv;": "≫̸",
  21802. "nisd;": "⋺",
  21803. "NJcy;": "Њ",
  21804. "njcy;": "њ",
  21805. "nldr;": "‥",
  21806. "nleq;": "≰",
  21807. "nles;": "⩽̸",
  21808. "nLtv;": "≪̸",
  21809. "nmid;": "∤",
  21810. "Nopf;": "ℕ",
  21811. "nopf;": "𝕟",
  21812. "npar;": "∦",
  21813. "npre;": "⪯̸",
  21814. "nsce;": "⪰̸",
  21815. "Nscr;": "𝒩",
  21816. "nscr;": "𝓃",
  21817. "nsim;": "≁",
  21818. "nsub;": "⊄",
  21819. "nsup;": "⊅",
  21820. "ntgl;": "≹",
  21821. "ntlg;": "≸",
  21822. "nvap;": "≍⃒",
  21823. "nvge;": "≥⃒",
  21824. "nvgt;": ">⃒",
  21825. "nvle;": "≤⃒",
  21826. "nvlt;": "<⃒",
  21827. "oast;": "⊛",
  21828. "ocir;": "⊚",
  21829. Ocirc: "Ô",
  21830. ocirc: "ô",
  21831. "odiv;": "⨸",
  21832. "odot;": "⊙",
  21833. "ogon;": "˛",
  21834. "oint;": "∮",
  21835. "omid;": "⦶",
  21836. "Oopf;": "𝕆",
  21837. "oopf;": "𝕠",
  21838. "opar;": "⦷",
  21839. "ordf;": "ª",
  21840. "ordm;": "º",
  21841. "oror;": "⩖",
  21842. "Oscr;": "𝒪",
  21843. "oscr;": "ℴ",
  21844. "osol;": "⊘",
  21845. "Ouml;": "Ö",
  21846. "ouml;": "ö",
  21847. "para;": "¶",
  21848. "part;": "∂",
  21849. "perp;": "⊥",
  21850. "phiv;": "ϕ",
  21851. "plus;": "+",
  21852. "Popf;": "ℙ",
  21853. "popf;": "𝕡",
  21854. pound: "£",
  21855. "prap;": "⪷",
  21856. "prec;": "≺",
  21857. "prnE;": "⪵",
  21858. "prod;": "∏",
  21859. "prop;": "∝",
  21860. "Pscr;": "𝒫",
  21861. "pscr;": "𝓅",
  21862. "qint;": "⨌",
  21863. "Qopf;": "ℚ",
  21864. "qopf;": "𝕢",
  21865. "Qscr;": "𝒬",
  21866. "qscr;": "𝓆",
  21867. "QUOT;": "\"",
  21868. "quot;": "\"",
  21869. "race;": "∽̱",
  21870. "Rang;": "⟫",
  21871. "rang;": "⟩",
  21872. raquo: "»",
  21873. "Rarr;": "↠",
  21874. "rArr;": "⇒",
  21875. "rarr;": "→",
  21876. "rcub;": "}",
  21877. "rdca;": "⤷",
  21878. "rdsh;": "↳",
  21879. "real;": "ℜ",
  21880. "rect;": "▭",
  21881. "rHar;": "⥤",
  21882. "rhov;": "ϱ",
  21883. "ring;": "˚",
  21884. "Ropf;": "ℝ",
  21885. "ropf;": "𝕣",
  21886. "rpar;": ")",
  21887. "Rscr;": "ℛ",
  21888. "rscr;": "𝓇",
  21889. "rsqb;": "]",
  21890. "rtri;": "▹",
  21891. "scap;": "⪸",
  21892. "scnE;": "⪶",
  21893. "sdot;": "⋅",
  21894. "sect;": "§",
  21895. "semi;": ";",
  21896. "sext;": "✶",
  21897. "SHcy;": "Ш",
  21898. "shcy;": "ш",
  21899. "sime;": "≃",
  21900. "simg;": "⪞",
  21901. "siml;": "⪝",
  21902. "smid;": "∣",
  21903. "smte;": "⪬",
  21904. "solb;": "⧄",
  21905. "Sopf;": "𝕊",
  21906. "sopf;": "𝕤",
  21907. "spar;": "∥",
  21908. "Sqrt;": "√",
  21909. "squf;": "▪",
  21910. "Sscr;": "𝒮",
  21911. "sscr;": "𝓈",
  21912. "Star;": "⋆",
  21913. "star;": "☆",
  21914. "subE;": "⫅",
  21915. "sube;": "⊆",
  21916. "succ;": "≻",
  21917. "sung;": "♪",
  21918. "sup1;": "¹",
  21919. "sup2;": "²",
  21920. "sup3;": "³",
  21921. "supE;": "⫆",
  21922. "supe;": "⊇",
  21923. szlig: "ß",
  21924. "tbrk;": "⎴",
  21925. "tdot;": "⃛",
  21926. THORN: "Þ",
  21927. thorn: "þ",
  21928. times: "×",
  21929. "tint;": "∭",
  21930. "toea;": "⤨",
  21931. "Topf;": "𝕋",
  21932. "topf;": "𝕥",
  21933. "tosa;": "⤩",
  21934. "trie;": "≜",
  21935. "Tscr;": "𝒯",
  21936. "tscr;": "𝓉",
  21937. "TScy;": "Ц",
  21938. "tscy;": "ц",
  21939. "Uarr;": "↟",
  21940. "uArr;": "⇑",
  21941. "uarr;": "↑",
  21942. Ucirc: "Û",
  21943. ucirc: "û",
  21944. "uHar;": "⥣",
  21945. "Uopf;": "𝕌",
  21946. "uopf;": "𝕦",
  21947. "Upsi;": "ϒ",
  21948. "upsi;": "υ",
  21949. "Uscr;": "𝒰",
  21950. "uscr;": "𝓊",
  21951. "utri;": "▵",
  21952. "Uuml;": "Ü",
  21953. "uuml;": "ü",
  21954. "vArr;": "⇕",
  21955. "varr;": "↕",
  21956. "Vbar;": "⫫",
  21957. "vBar;": "⫨",
  21958. "Vert;": "‖",
  21959. "vert;": "|",
  21960. "Vopf;": "𝕍",
  21961. "vopf;": "𝕧",
  21962. "Vscr;": "𝒱",
  21963. "vscr;": "𝓋",
  21964. "Wopf;": "𝕎",
  21965. "wopf;": "𝕨",
  21966. "Wscr;": "𝒲",
  21967. "wscr;": "𝓌",
  21968. "xcap;": "⋂",
  21969. "xcup;": "⋃",
  21970. "xmap;": "⟼",
  21971. "xnis;": "⋻",
  21972. "Xopf;": "𝕏",
  21973. "xopf;": "𝕩",
  21974. "Xscr;": "𝒳",
  21975. "xscr;": "𝓍",
  21976. "xvee;": "⋁",
  21977. "YAcy;": "Я",
  21978. "yacy;": "я",
  21979. "YIcy;": "Ї",
  21980. "yicy;": "ї",
  21981. "Yopf;": "𝕐",
  21982. "yopf;": "𝕪",
  21983. "Yscr;": "𝒴",
  21984. "yscr;": "𝓎",
  21985. "YUcy;": "Ю",
  21986. "yucy;": "ю",
  21987. "Yuml;": "Ÿ",
  21988. "yuml;": "ÿ",
  21989. "Zdot;": "Ż",
  21990. "zdot;": "ż",
  21991. "Zeta;": "Ζ",
  21992. "zeta;": "ζ",
  21993. "ZHcy;": "Ж",
  21994. "zhcy;": "ж",
  21995. "Zopf;": "ℤ",
  21996. "zopf;": "𝕫",
  21997. "Zscr;": "𝒵",
  21998. "zscr;": "𝓏",
  21999. "zwnj;": "‌",
  22000. Aacute: "Á",
  22001. aacute: "á",
  22002. "Acirc;": "Â",
  22003. "acirc;": "â",
  22004. "acute;": "´",
  22005. "AElig;": "Æ",
  22006. "aelig;": "æ",
  22007. Agrave: "À",
  22008. agrave: "à",
  22009. "aleph;": "ℵ",
  22010. "Alpha;": "Α",
  22011. "alpha;": "α",
  22012. "Amacr;": "Ā",
  22013. "amacr;": "ā",
  22014. "amalg;": "⨿",
  22015. "angle;": "∠",
  22016. "angrt;": "∟",
  22017. "angst;": "Å",
  22018. "Aogon;": "Ą",
  22019. "aogon;": "ą",
  22020. "Aring;": "Å",
  22021. "aring;": "å",
  22022. "asymp;": "≈",
  22023. Atilde: "Ã",
  22024. atilde: "ã",
  22025. "awint;": "⨑",
  22026. "bcong;": "≌",
  22027. "bdquo;": "„",
  22028. "bepsi;": "϶",
  22029. "blank;": "␣",
  22030. "blk12;": "▒",
  22031. "blk14;": "░",
  22032. "blk34;": "▓",
  22033. "block;": "█",
  22034. "boxDL;": "╗",
  22035. "boxDl;": "╖",
  22036. "boxdL;": "╕",
  22037. "boxdl;": "┐",
  22038. "boxDR;": "╔",
  22039. "boxDr;": "╓",
  22040. "boxdR;": "╒",
  22041. "boxdr;": "┌",
  22042. "boxHD;": "╦",
  22043. "boxHd;": "╤",
  22044. "boxhD;": "╥",
  22045. "boxhd;": "┬",
  22046. "boxHU;": "╩",
  22047. "boxHu;": "╧",
  22048. "boxhU;": "╨",
  22049. "boxhu;": "┴",
  22050. "boxUL;": "╝",
  22051. "boxUl;": "╜",
  22052. "boxuL;": "╛",
  22053. "boxul;": "┘",
  22054. "boxUR;": "╚",
  22055. "boxUr;": "╙",
  22056. "boxuR;": "╘",
  22057. "boxur;": "└",
  22058. "boxVH;": "╬",
  22059. "boxVh;": "╫",
  22060. "boxvH;": "╪",
  22061. "boxvh;": "┼",
  22062. "boxVL;": "╣",
  22063. "boxVl;": "╢",
  22064. "boxvL;": "╡",
  22065. "boxvl;": "┤",
  22066. "boxVR;": "╠",
  22067. "boxVr;": "╟",
  22068. "boxvR;": "╞",
  22069. "boxvr;": "├",
  22070. "Breve;": "˘",
  22071. "breve;": "˘",
  22072. brvbar: "¦",
  22073. "bsemi;": "⁏",
  22074. "bsime;": "⋍",
  22075. "bsolb;": "⧅",
  22076. "bumpE;": "⪮",
  22077. "bumpe;": "≏",
  22078. "caret;": "⁁",
  22079. "caron;": "ˇ",
  22080. "ccaps;": "⩍",
  22081. Ccedil: "Ç",
  22082. ccedil: "ç",
  22083. "Ccirc;": "Ĉ",
  22084. "ccirc;": "ĉ",
  22085. "ccups;": "⩌",
  22086. "cedil;": "¸",
  22087. "check;": "✓",
  22088. "clubs;": "♣",
  22089. "Colon;": "∷",
  22090. "colon;": ":",
  22091. "comma;": ",",
  22092. "crarr;": "↵",
  22093. "Cross;": "⨯",
  22094. "cross;": "✗",
  22095. "csube;": "⫑",
  22096. "csupe;": "⫒",
  22097. "ctdot;": "⋯",
  22098. "cuepr;": "⋞",
  22099. "cuesc;": "⋟",
  22100. "cupor;": "⩅",
  22101. curren: "¤",
  22102. "cuvee;": "⋎",
  22103. "cuwed;": "⋏",
  22104. "cwint;": "∱",
  22105. "Dashv;": "⫤",
  22106. "dashv;": "⊣",
  22107. "dblac;": "˝",
  22108. "ddarr;": "⇊",
  22109. "Delta;": "Δ",
  22110. "delta;": "δ",
  22111. "dharl;": "⇃",
  22112. "dharr;": "⇂",
  22113. "diams;": "♦",
  22114. "disin;": "⋲",
  22115. divide: "÷",
  22116. "doteq;": "≐",
  22117. "dtdot;": "⋱",
  22118. "dtrif;": "▾",
  22119. "duarr;": "⇵",
  22120. "duhar;": "⥯",
  22121. Eacute: "É",
  22122. eacute: "é",
  22123. "Ecirc;": "Ê",
  22124. "ecirc;": "ê",
  22125. "eDDot;": "⩷",
  22126. "efDot;": "≒",
  22127. Egrave: "È",
  22128. egrave: "è",
  22129. "Emacr;": "Ē",
  22130. "emacr;": "ē",
  22131. "empty;": "∅",
  22132. "Eogon;": "Ę",
  22133. "eogon;": "ę",
  22134. "eplus;": "⩱",
  22135. "epsiv;": "ϵ",
  22136. "eqsim;": "≂",
  22137. "Equal;": "⩵",
  22138. "equiv;": "≡",
  22139. "erarr;": "⥱",
  22140. "erDot;": "≓",
  22141. "esdot;": "≐",
  22142. "exist;": "∃",
  22143. "fflig;": "ff",
  22144. "filig;": "fi",
  22145. "fjlig;": "fj",
  22146. "fllig;": "fl",
  22147. "fltns;": "▱",
  22148. "forkv;": "⫙",
  22149. frac12: "½",
  22150. frac14: "¼",
  22151. frac34: "¾",
  22152. "frasl;": "⁄",
  22153. "frown;": "⌢",
  22154. "Gamma;": "Γ",
  22155. "gamma;": "γ",
  22156. "Gcirc;": "Ĝ",
  22157. "gcirc;": "ĝ",
  22158. "gescc;": "⪩",
  22159. "gimel;": "ℷ",
  22160. "gneqq;": "≩",
  22161. "gnsim;": "⋧",
  22162. "grave;": "`",
  22163. "gsime;": "⪎",
  22164. "gsiml;": "⪐",
  22165. "gtcir;": "⩺",
  22166. "gtdot;": "⋗",
  22167. "Hacek;": "ˇ",
  22168. "harrw;": "↭",
  22169. "Hcirc;": "Ĥ",
  22170. "hcirc;": "ĥ",
  22171. "hoarr;": "⇿",
  22172. Iacute: "Í",
  22173. iacute: "í",
  22174. "Icirc;": "Î",
  22175. "icirc;": "î",
  22176. "iexcl;": "¡",
  22177. Igrave: "Ì",
  22178. igrave: "ì",
  22179. "iiint;": "∭",
  22180. "iiota;": "℩",
  22181. "IJlig;": "IJ",
  22182. "ijlig;": "ij",
  22183. "Imacr;": "Ī",
  22184. "imacr;": "ī",
  22185. "image;": "ℑ",
  22186. "imath;": "ı",
  22187. "imped;": "Ƶ",
  22188. "infin;": "∞",
  22189. "Iogon;": "Į",
  22190. "iogon;": "į",
  22191. "iprod;": "⨼",
  22192. iquest: "¿",
  22193. "isinE;": "⋹",
  22194. "isins;": "⋴",
  22195. "isinv;": "∈",
  22196. "Iukcy;": "І",
  22197. "iukcy;": "і",
  22198. "Jcirc;": "Ĵ",
  22199. "jcirc;": "ĵ",
  22200. "jmath;": "ȷ",
  22201. "Jukcy;": "Є",
  22202. "jukcy;": "є",
  22203. "Kappa;": "Κ",
  22204. "kappa;": "κ",
  22205. "lAarr;": "⇚",
  22206. "langd;": "⦑",
  22207. "laquo;": "«",
  22208. "larrb;": "⇤",
  22209. "lates;": "⪭︀",
  22210. "lBarr;": "⤎",
  22211. "lbarr;": "⤌",
  22212. "lbbrk;": "❲",
  22213. "lbrke;": "⦋",
  22214. "lceil;": "⌈",
  22215. "ldquo;": "“",
  22216. "lescc;": "⪨",
  22217. "lhard;": "↽",
  22218. "lharu;": "↼",
  22219. "lhblk;": "▄",
  22220. "llarr;": "⇇",
  22221. "lltri;": "◺",
  22222. "lneqq;": "≨",
  22223. "lnsim;": "⋦",
  22224. "loang;": "⟬",
  22225. "loarr;": "⇽",
  22226. "lobrk;": "⟦",
  22227. "lopar;": "⦅",
  22228. "lrarr;": "⇆",
  22229. "lrhar;": "⇋",
  22230. "lrtri;": "⊿",
  22231. "lsime;": "⪍",
  22232. "lsimg;": "⪏",
  22233. "lsquo;": "‘",
  22234. "ltcir;": "⩹",
  22235. "ltdot;": "⋖",
  22236. "ltrie;": "⊴",
  22237. "ltrif;": "◂",
  22238. "mdash;": "—",
  22239. "mDDot;": "∺",
  22240. "micro;": "µ",
  22241. middot: "·",
  22242. "minus;": "−",
  22243. "mumap;": "⊸",
  22244. "nabla;": "∇",
  22245. "napid;": "≋̸",
  22246. "napos;": "ʼn",
  22247. "natur;": "♮",
  22248. "nbump;": "≎̸",
  22249. "ncong;": "≇",
  22250. "ndash;": "–",
  22251. "neArr;": "⇗",
  22252. "nearr;": "↗",
  22253. "nedot;": "≐̸",
  22254. "nesim;": "≂̸",
  22255. "ngeqq;": "≧̸",
  22256. "ngsim;": "≵",
  22257. "nhArr;": "⇎",
  22258. "nharr;": "↮",
  22259. "nhpar;": "⫲",
  22260. "nlArr;": "⇍",
  22261. "nlarr;": "↚",
  22262. "nleqq;": "≦̸",
  22263. "nless;": "≮",
  22264. "nlsim;": "≴",
  22265. "nltri;": "⋪",
  22266. "notin;": "∉",
  22267. "notni;": "∌",
  22268. "npart;": "∂̸",
  22269. "nprec;": "⊀",
  22270. "nrArr;": "⇏",
  22271. "nrarr;": "↛",
  22272. "nrtri;": "⋫",
  22273. "nsime;": "≄",
  22274. "nsmid;": "∤",
  22275. "nspar;": "∦",
  22276. "nsubE;": "⫅̸",
  22277. "nsube;": "⊈",
  22278. "nsucc;": "⊁",
  22279. "nsupE;": "⫆̸",
  22280. "nsupe;": "⊉",
  22281. Ntilde: "Ñ",
  22282. ntilde: "ñ",
  22283. "numsp;": " ",
  22284. "nvsim;": "∼⃒",
  22285. "nwArr;": "⇖",
  22286. "nwarr;": "↖",
  22287. Oacute: "Ó",
  22288. oacute: "ó",
  22289. "Ocirc;": "Ô",
  22290. "ocirc;": "ô",
  22291. "odash;": "⊝",
  22292. "OElig;": "Œ",
  22293. "oelig;": "œ",
  22294. "ofcir;": "⦿",
  22295. Ograve: "Ò",
  22296. ograve: "ò",
  22297. "ohbar;": "⦵",
  22298. "olarr;": "↺",
  22299. "olcir;": "⦾",
  22300. "oline;": "‾",
  22301. "Omacr;": "Ō",
  22302. "omacr;": "ō",
  22303. "Omega;": "Ω",
  22304. "omega;": "ω",
  22305. "operp;": "⦹",
  22306. "oplus;": "⊕",
  22307. "orarr;": "↻",
  22308. "order;": "ℴ",
  22309. Oslash: "Ø",
  22310. oslash: "ø",
  22311. Otilde: "Õ",
  22312. otilde: "õ",
  22313. "ovbar;": "⌽",
  22314. "parsl;": "⫽",
  22315. "phone;": "☎",
  22316. "plusb;": "⊞",
  22317. "pluse;": "⩲",
  22318. plusmn: "±",
  22319. "pound;": "£",
  22320. "prcue;": "≼",
  22321. "Prime;": "″",
  22322. "prime;": "′",
  22323. "prnap;": "⪹",
  22324. "prsim;": "≾",
  22325. "quest;": "?",
  22326. "rAarr;": "⇛",
  22327. "radic;": "√",
  22328. "rangd;": "⦒",
  22329. "range;": "⦥",
  22330. "raquo;": "»",
  22331. "rarrb;": "⇥",
  22332. "rarrc;": "⤳",
  22333. "rarrw;": "↝",
  22334. "ratio;": "∶",
  22335. "RBarr;": "⤐",
  22336. "rBarr;": "⤏",
  22337. "rbarr;": "⤍",
  22338. "rbbrk;": "❳",
  22339. "rbrke;": "⦌",
  22340. "rceil;": "⌉",
  22341. "rdquo;": "”",
  22342. "reals;": "ℝ",
  22343. "rhard;": "⇁",
  22344. "rharu;": "⇀",
  22345. "rlarr;": "⇄",
  22346. "rlhar;": "⇌",
  22347. "rnmid;": "⫮",
  22348. "roang;": "⟭",
  22349. "roarr;": "⇾",
  22350. "robrk;": "⟧",
  22351. "ropar;": "⦆",
  22352. "rrarr;": "⇉",
  22353. "rsquo;": "’",
  22354. "rtrie;": "⊵",
  22355. "rtrif;": "▸",
  22356. "sbquo;": "‚",
  22357. "sccue;": "≽",
  22358. "Scirc;": "Ŝ",
  22359. "scirc;": "ŝ",
  22360. "scnap;": "⪺",
  22361. "scsim;": "≿",
  22362. "sdotb;": "⊡",
  22363. "sdote;": "⩦",
  22364. "seArr;": "⇘",
  22365. "searr;": "↘",
  22366. "setmn;": "∖",
  22367. "sharp;": "♯",
  22368. "Sigma;": "Σ",
  22369. "sigma;": "σ",
  22370. "simeq;": "≃",
  22371. "simgE;": "⪠",
  22372. "simlE;": "⪟",
  22373. "simne;": "≆",
  22374. "slarr;": "←",
  22375. "smile;": "⌣",
  22376. "smtes;": "⪬︀",
  22377. "sqcap;": "⊓",
  22378. "sqcup;": "⊔",
  22379. "sqsub;": "⊏",
  22380. "sqsup;": "⊐",
  22381. "srarr;": "→",
  22382. "starf;": "★",
  22383. "strns;": "¯",
  22384. "subnE;": "⫋",
  22385. "subne;": "⊊",
  22386. "supnE;": "⫌",
  22387. "supne;": "⊋",
  22388. "swArr;": "⇙",
  22389. "swarr;": "↙",
  22390. "szlig;": "ß",
  22391. "Theta;": "Θ",
  22392. "theta;": "θ",
  22393. "thkap;": "≈",
  22394. "THORN;": "Þ",
  22395. "thorn;": "þ",
  22396. "Tilde;": "∼",
  22397. "tilde;": "˜",
  22398. "times;": "×",
  22399. "TRADE;": "™",
  22400. "trade;": "™",
  22401. "trisb;": "⧍",
  22402. "TSHcy;": "Ћ",
  22403. "tshcy;": "ћ",
  22404. "twixt;": "≬",
  22405. Uacute: "Ú",
  22406. uacute: "ú",
  22407. "Ubrcy;": "Ў",
  22408. "ubrcy;": "ў",
  22409. "Ucirc;": "Û",
  22410. "ucirc;": "û",
  22411. "udarr;": "⇅",
  22412. "udhar;": "⥮",
  22413. Ugrave: "Ù",
  22414. ugrave: "ù",
  22415. "uharl;": "↿",
  22416. "uharr;": "↾",
  22417. "uhblk;": "▀",
  22418. "ultri;": "◸",
  22419. "Umacr;": "Ū",
  22420. "umacr;": "ū",
  22421. "Union;": "⋃",
  22422. "Uogon;": "Ų",
  22423. "uogon;": "ų",
  22424. "uplus;": "⊎",
  22425. "upsih;": "ϒ",
  22426. "UpTee;": "⊥",
  22427. "Uring;": "Ů",
  22428. "uring;": "ů",
  22429. "urtri;": "◹",
  22430. "utdot;": "⋰",
  22431. "utrif;": "▴",
  22432. "uuarr;": "⇈",
  22433. "varpi;": "ϖ",
  22434. "vBarv;": "⫩",
  22435. "VDash;": "⊫",
  22436. "Vdash;": "⊩",
  22437. "vDash;": "⊨",
  22438. "vdash;": "⊢",
  22439. "veeeq;": "≚",
  22440. "vltri;": "⊲",
  22441. "vnsub;": "⊂⃒",
  22442. "vnsup;": "⊃⃒",
  22443. "vprop;": "∝",
  22444. "vrtri;": "⊳",
  22445. "Wcirc;": "Ŵ",
  22446. "wcirc;": "ŵ",
  22447. "Wedge;": "⋀",
  22448. "wedge;": "∧",
  22449. "xcirc;": "◯",
  22450. "xdtri;": "▽",
  22451. "xhArr;": "⟺",
  22452. "xharr;": "⟷",
  22453. "xlArr;": "⟸",
  22454. "xlarr;": "⟵",
  22455. "xodot;": "⨀",
  22456. "xrArr;": "⟹",
  22457. "xrarr;": "⟶",
  22458. "xutri;": "△",
  22459. Yacute: "Ý",
  22460. yacute: "ý",
  22461. "Ycirc;": "Ŷ",
  22462. "ycirc;": "ŷ",
  22463. "Aacute;": "Á",
  22464. "aacute;": "á",
  22465. "Abreve;": "Ă",
  22466. "abreve;": "ă",
  22467. "Agrave;": "À",
  22468. "agrave;": "à",
  22469. "andand;": "⩕",
  22470. "angmsd;": "∡",
  22471. "angsph;": "∢",
  22472. "apacir;": "⩯",
  22473. "approx;": "≈",
  22474. "Assign;": "≔",
  22475. "Atilde;": "Ã",
  22476. "atilde;": "ã",
  22477. "barvee;": "⊽",
  22478. "Barwed;": "⌆",
  22479. "barwed;": "⌅",
  22480. "becaus;": "∵",
  22481. "bernou;": "ℬ",
  22482. "bigcap;": "⋂",
  22483. "bigcup;": "⋃",
  22484. "bigvee;": "⋁",
  22485. "bkarow;": "⤍",
  22486. "bottom;": "⊥",
  22487. "bowtie;": "⋈",
  22488. "boxbox;": "⧉",
  22489. "bprime;": "‵",
  22490. "brvbar;": "¦",
  22491. "bullet;": "•",
  22492. "Bumpeq;": "≎",
  22493. "bumpeq;": "≏",
  22494. "Cacute;": "Ć",
  22495. "cacute;": "ć",
  22496. "capand;": "⩄",
  22497. "capcap;": "⩋",
  22498. "capcup;": "⩇",
  22499. "capdot;": "⩀",
  22500. "Ccaron;": "Č",
  22501. "ccaron;": "č",
  22502. "Ccedil;": "Ç",
  22503. "ccedil;": "ç",
  22504. "circeq;": "≗",
  22505. "cirmid;": "⫯",
  22506. "Colone;": "⩴",
  22507. "colone;": "≔",
  22508. "commat;": "@",
  22509. "compfn;": "∘",
  22510. "Conint;": "∯",
  22511. "conint;": "∮",
  22512. "coprod;": "∐",
  22513. "copysr;": "℗",
  22514. "cularr;": "↶",
  22515. "CupCap;": "≍",
  22516. "cupcap;": "⩆",
  22517. "cupcup;": "⩊",
  22518. "cupdot;": "⊍",
  22519. "curarr;": "↷",
  22520. "curren;": "¤",
  22521. "cylcty;": "⌭",
  22522. "Dagger;": "‡",
  22523. "dagger;": "†",
  22524. "daleth;": "ℸ",
  22525. "Dcaron;": "Ď",
  22526. "dcaron;": "ď",
  22527. "dfisht;": "⥿",
  22528. "divide;": "÷",
  22529. "divonx;": "⋇",
  22530. "dlcorn;": "⌞",
  22531. "dlcrop;": "⌍",
  22532. "dollar;": "$",
  22533. "DotDot;": "⃜",
  22534. "drcorn;": "⌟",
  22535. "drcrop;": "⌌",
  22536. "Dstrok;": "Đ",
  22537. "dstrok;": "đ",
  22538. "Eacute;": "É",
  22539. "eacute;": "é",
  22540. "easter;": "⩮",
  22541. "Ecaron;": "Ě",
  22542. "ecaron;": "ě",
  22543. "ecolon;": "≕",
  22544. "Egrave;": "È",
  22545. "egrave;": "è",
  22546. "egsdot;": "⪘",
  22547. "elsdot;": "⪗",
  22548. "emptyv;": "∅",
  22549. "emsp13;": " ",
  22550. "emsp14;": " ",
  22551. "eparsl;": "⧣",
  22552. "eqcirc;": "≖",
  22553. "equals;": "=",
  22554. "equest;": "≟",
  22555. "Exists;": "∃",
  22556. "female;": "♀",
  22557. "ffilig;": "ffi",
  22558. "ffllig;": "ffl",
  22559. "ForAll;": "∀",
  22560. "forall;": "∀",
  22561. "frac12;": "½",
  22562. "frac13;": "⅓",
  22563. "frac14;": "¼",
  22564. "frac15;": "⅕",
  22565. "frac16;": "⅙",
  22566. "frac18;": "⅛",
  22567. "frac23;": "⅔",
  22568. "frac25;": "⅖",
  22569. "frac34;": "¾",
  22570. "frac35;": "⅗",
  22571. "frac38;": "⅜",
  22572. "frac45;": "⅘",
  22573. "frac56;": "⅚",
  22574. "frac58;": "⅝",
  22575. "frac78;": "⅞",
  22576. "gacute;": "ǵ",
  22577. "Gammad;": "Ϝ",
  22578. "gammad;": "ϝ",
  22579. "Gbreve;": "Ğ",
  22580. "gbreve;": "ğ",
  22581. "Gcedil;": "Ģ",
  22582. "gesdot;": "⪀",
  22583. "gesles;": "⪔",
  22584. "gtlPar;": "⦕",
  22585. "gtrarr;": "⥸",
  22586. "gtrdot;": "⋗",
  22587. "gtrsim;": "≳",
  22588. "hairsp;": " ",
  22589. "hamilt;": "ℋ",
  22590. "HARDcy;": "Ъ",
  22591. "hardcy;": "ъ",
  22592. "hearts;": "♥",
  22593. "hellip;": "…",
  22594. "hercon;": "⊹",
  22595. "homtht;": "∻",
  22596. "horbar;": "―",
  22597. "hslash;": "ℏ",
  22598. "Hstrok;": "Ħ",
  22599. "hstrok;": "ħ",
  22600. "hybull;": "⁃",
  22601. "hyphen;": "‐",
  22602. "Iacute;": "Í",
  22603. "iacute;": "í",
  22604. "Igrave;": "Ì",
  22605. "igrave;": "ì",
  22606. "iiiint;": "⨌",
  22607. "iinfin;": "⧜",
  22608. "incare;": "℅",
  22609. "inodot;": "ı",
  22610. "intcal;": "⊺",
  22611. "iquest;": "¿",
  22612. "isinsv;": "⋳",
  22613. "Itilde;": "Ĩ",
  22614. "itilde;": "ĩ",
  22615. "Jsercy;": "Ј",
  22616. "jsercy;": "ј",
  22617. "kappav;": "ϰ",
  22618. "Kcedil;": "Ķ",
  22619. "kcedil;": "ķ",
  22620. "kgreen;": "ĸ",
  22621. "Lacute;": "Ĺ",
  22622. "lacute;": "ĺ",
  22623. "lagran;": "ℒ",
  22624. "Lambda;": "Λ",
  22625. "lambda;": "λ",
  22626. "langle;": "⟨",
  22627. "larrfs;": "⤝",
  22628. "larrhk;": "↩",
  22629. "larrlp;": "↫",
  22630. "larrpl;": "⤹",
  22631. "larrtl;": "↢",
  22632. "lAtail;": "⤛",
  22633. "latail;": "⤙",
  22634. "lbrace;": "{",
  22635. "lbrack;": "[",
  22636. "Lcaron;": "Ľ",
  22637. "lcaron;": "ľ",
  22638. "Lcedil;": "Ļ",
  22639. "lcedil;": "ļ",
  22640. "ldquor;": "„",
  22641. "lesdot;": "⩿",
  22642. "lesges;": "⪓",
  22643. "lfisht;": "⥼",
  22644. "lfloor;": "⌊",
  22645. "lharul;": "⥪",
  22646. "llhard;": "⥫",
  22647. "Lmidot;": "Ŀ",
  22648. "lmidot;": "ŀ",
  22649. "lmoust;": "⎰",
  22650. "loplus;": "⨭",
  22651. "lowast;": "∗",
  22652. "lowbar;": "_",
  22653. "lparlt;": "⦓",
  22654. "lrhard;": "⥭",
  22655. "lsaquo;": "‹",
  22656. "lsquor;": "‚",
  22657. "Lstrok;": "Ł",
  22658. "lstrok;": "ł",
  22659. "lthree;": "⋋",
  22660. "ltimes;": "⋉",
  22661. "ltlarr;": "⥶",
  22662. "ltrPar;": "⦖",
  22663. "mapsto;": "↦",
  22664. "marker;": "▮",
  22665. "mcomma;": "⨩",
  22666. "midast;": "*",
  22667. "midcir;": "⫰",
  22668. "middot;": "·",
  22669. "minusb;": "⊟",
  22670. "minusd;": "∸",
  22671. "mnplus;": "∓",
  22672. "models;": "⊧",
  22673. "mstpos;": "∾",
  22674. "Nacute;": "Ń",
  22675. "nacute;": "ń",
  22676. "nbumpe;": "≏̸",
  22677. "Ncaron;": "Ň",
  22678. "ncaron;": "ň",
  22679. "Ncedil;": "Ņ",
  22680. "ncedil;": "ņ",
  22681. "nearhk;": "⤤",
  22682. "nequiv;": "≢",
  22683. "nesear;": "⤨",
  22684. "nexist;": "∄",
  22685. "nltrie;": "⋬",
  22686. "notinE;": "⋹̸",
  22687. "nparsl;": "⫽⃥",
  22688. "nprcue;": "⋠",
  22689. "nrarrc;": "⤳̸",
  22690. "nrarrw;": "↝̸",
  22691. "nrtrie;": "⋭",
  22692. "nsccue;": "⋡",
  22693. "nsimeq;": "≄",
  22694. "Ntilde;": "Ñ",
  22695. "ntilde;": "ñ",
  22696. "numero;": "№",
  22697. "nVDash;": "⊯",
  22698. "nVdash;": "⊮",
  22699. "nvDash;": "⊭",
  22700. "nvdash;": "⊬",
  22701. "nvHarr;": "⤄",
  22702. "nvlArr;": "⤂",
  22703. "nvrArr;": "⤃",
  22704. "nwarhk;": "⤣",
  22705. "nwnear;": "⤧",
  22706. "Oacute;": "Ó",
  22707. "oacute;": "ó",
  22708. "Odblac;": "Ő",
  22709. "odblac;": "ő",
  22710. "odsold;": "⦼",
  22711. "Ograve;": "Ò",
  22712. "ograve;": "ò",
  22713. "ominus;": "⊖",
  22714. "origof;": "⊶",
  22715. "Oslash;": "Ø",
  22716. "oslash;": "ø",
  22717. "Otilde;": "Õ",
  22718. "otilde;": "õ",
  22719. "Otimes;": "⨷",
  22720. "otimes;": "⊗",
  22721. "parsim;": "⫳",
  22722. "percnt;": "%",
  22723. "period;": ".",
  22724. "permil;": "‰",
  22725. "phmmat;": "ℳ",
  22726. "planck;": "ℏ",
  22727. "plankv;": "ℏ",
  22728. "plusdo;": "∔",
  22729. "plusdu;": "⨥",
  22730. "plusmn;": "±",
  22731. "preceq;": "⪯",
  22732. "primes;": "ℙ",
  22733. "prnsim;": "⋨",
  22734. "propto;": "∝",
  22735. "prurel;": "⊰",
  22736. "puncsp;": " ",
  22737. "qprime;": "⁗",
  22738. "Racute;": "Ŕ",
  22739. "racute;": "ŕ",
  22740. "rangle;": "⟩",
  22741. "rarrap;": "⥵",
  22742. "rarrfs;": "⤞",
  22743. "rarrhk;": "↪",
  22744. "rarrlp;": "↬",
  22745. "rarrpl;": "⥅",
  22746. "Rarrtl;": "⤖",
  22747. "rarrtl;": "↣",
  22748. "rAtail;": "⤜",
  22749. "ratail;": "⤚",
  22750. "rbrace;": "}",
  22751. "rbrack;": "]",
  22752. "Rcaron;": "Ř",
  22753. "rcaron;": "ř",
  22754. "Rcedil;": "Ŗ",
  22755. "rcedil;": "ŗ",
  22756. "rdquor;": "”",
  22757. "rfisht;": "⥽",
  22758. "rfloor;": "⌋",
  22759. "rharul;": "⥬",
  22760. "rmoust;": "⎱",
  22761. "roplus;": "⨮",
  22762. "rpargt;": "⦔",
  22763. "rsaquo;": "›",
  22764. "rsquor;": "’",
  22765. "rthree;": "⋌",
  22766. "rtimes;": "⋊",
  22767. "Sacute;": "Ś",
  22768. "sacute;": "ś",
  22769. "Scaron;": "Š",
  22770. "scaron;": "š",
  22771. "Scedil;": "Ş",
  22772. "scedil;": "ş",
  22773. "scnsim;": "⋩",
  22774. "searhk;": "⤥",
  22775. "seswar;": "⤩",
  22776. "sfrown;": "⌢",
  22777. "SHCHcy;": "Щ",
  22778. "shchcy;": "щ",
  22779. "sigmaf;": "ς",
  22780. "sigmav;": "ς",
  22781. "simdot;": "⩪",
  22782. "smashp;": "⨳",
  22783. "SOFTcy;": "Ь",
  22784. "softcy;": "ь",
  22785. "solbar;": "⌿",
  22786. "spades;": "♠",
  22787. "sqcaps;": "⊓︀",
  22788. "sqcups;": "⊔︀",
  22789. "sqsube;": "⊑",
  22790. "sqsupe;": "⊒",
  22791. "Square;": "□",
  22792. "square;": "□",
  22793. "squarf;": "▪",
  22794. "ssetmn;": "∖",
  22795. "ssmile;": "⌣",
  22796. "sstarf;": "⋆",
  22797. "subdot;": "⪽",
  22798. "Subset;": "⋐",
  22799. "subset;": "⊂",
  22800. "subsim;": "⫇",
  22801. "subsub;": "⫕",
  22802. "subsup;": "⫓",
  22803. "succeq;": "⪰",
  22804. "supdot;": "⪾",
  22805. "Supset;": "⋑",
  22806. "supset;": "⊃",
  22807. "supsim;": "⫈",
  22808. "supsub;": "⫔",
  22809. "supsup;": "⫖",
  22810. "swarhk;": "⤦",
  22811. "swnwar;": "⤪",
  22812. "target;": "⌖",
  22813. "Tcaron;": "Ť",
  22814. "tcaron;": "ť",
  22815. "Tcedil;": "Ţ",
  22816. "tcedil;": "ţ",
  22817. "telrec;": "⌕",
  22818. "there4;": "∴",
  22819. "thetav;": "ϑ",
  22820. "thinsp;": " ",
  22821. "thksim;": "∼",
  22822. "timesb;": "⊠",
  22823. "timesd;": "⨰",
  22824. "topbot;": "⌶",
  22825. "topcir;": "⫱",
  22826. "tprime;": "‴",
  22827. "tridot;": "◬",
  22828. "Tstrok;": "Ŧ",
  22829. "tstrok;": "ŧ",
  22830. "Uacute;": "Ú",
  22831. "uacute;": "ú",
  22832. "Ubreve;": "Ŭ",
  22833. "ubreve;": "ŭ",
  22834. "Udblac;": "Ű",
  22835. "udblac;": "ű",
  22836. "ufisht;": "⥾",
  22837. "Ugrave;": "Ù",
  22838. "ugrave;": "ù",
  22839. "ulcorn;": "⌜",
  22840. "ulcrop;": "⌏",
  22841. "urcorn;": "⌝",
  22842. "urcrop;": "⌎",
  22843. "Utilde;": "Ũ",
  22844. "utilde;": "ũ",
  22845. "vangrt;": "⦜",
  22846. "varphi;": "ϕ",
  22847. "varrho;": "ϱ",
  22848. "Vdashl;": "⫦",
  22849. "veebar;": "⊻",
  22850. "vellip;": "⋮",
  22851. "Verbar;": "‖",
  22852. "verbar;": "|",
  22853. "vsubnE;": "⫋︀",
  22854. "vsubne;": "⊊︀",
  22855. "vsupnE;": "⫌︀",
  22856. "vsupne;": "⊋︀",
  22857. "Vvdash;": "⊪",
  22858. "wedbar;": "⩟",
  22859. "wedgeq;": "≙",
  22860. "weierp;": "℘",
  22861. "wreath;": "≀",
  22862. "xoplus;": "⨁",
  22863. "xotime;": "⨂",
  22864. "xsqcup;": "⨆",
  22865. "xuplus;": "⨄",
  22866. "xwedge;": "⋀",
  22867. "Yacute;": "Ý",
  22868. "yacute;": "ý",
  22869. "Zacute;": "Ź",
  22870. "zacute;": "ź",
  22871. "Zcaron;": "Ž",
  22872. "zcaron;": "ž",
  22873. "zeetrf;": "ℨ",
  22874. "alefsym;": "ℵ",
  22875. "angrtvb;": "⊾",
  22876. "angzarr;": "⍼",
  22877. "asympeq;": "≍",
  22878. "backsim;": "∽",
  22879. "Because;": "∵",
  22880. "because;": "∵",
  22881. "bemptyv;": "⦰",
  22882. "between;": "≬",
  22883. "bigcirc;": "◯",
  22884. "bigodot;": "⨀",
  22885. "bigstar;": "★",
  22886. "bnequiv;": "≡⃥",
  22887. "boxplus;": "⊞",
  22888. "Cayleys;": "ℭ",
  22889. "Cconint;": "∰",
  22890. "ccupssm;": "⩐",
  22891. "Cedilla;": "¸",
  22892. "cemptyv;": "⦲",
  22893. "cirscir;": "⧂",
  22894. "coloneq;": "≔",
  22895. "congdot;": "⩭",
  22896. "cudarrl;": "⤸",
  22897. "cudarrr;": "⤵",
  22898. "cularrp;": "⤽",
  22899. "curarrm;": "⤼",
  22900. "dbkarow;": "⤏",
  22901. "ddagger;": "‡",
  22902. "ddotseq;": "⩷",
  22903. "demptyv;": "⦱",
  22904. "Diamond;": "⋄",
  22905. "diamond;": "⋄",
  22906. "digamma;": "ϝ",
  22907. "dotplus;": "∔",
  22908. "DownTee;": "⊤",
  22909. "dwangle;": "⦦",
  22910. "Element;": "∈",
  22911. "Epsilon;": "Ε",
  22912. "epsilon;": "ε",
  22913. "eqcolon;": "≕",
  22914. "equivDD;": "⩸",
  22915. "gesdoto;": "⪂",
  22916. "gtquest;": "⩼",
  22917. "gtrless;": "≷",
  22918. "harrcir;": "⥈",
  22919. "Implies;": "⇒",
  22920. "intprod;": "⨼",
  22921. "isindot;": "⋵",
  22922. "larrbfs;": "⤟",
  22923. "larrsim;": "⥳",
  22924. "lbrksld;": "⦏",
  22925. "lbrkslu;": "⦍",
  22926. "ldrdhar;": "⥧",
  22927. "LeftTee;": "⊣",
  22928. "lesdoto;": "⪁",
  22929. "lessdot;": "⋖",
  22930. "lessgtr;": "≶",
  22931. "lesssim;": "≲",
  22932. "lotimes;": "⨴",
  22933. "lozenge;": "◊",
  22934. "ltquest;": "⩻",
  22935. "luruhar;": "⥦",
  22936. "maltese;": "✠",
  22937. "minusdu;": "⨪",
  22938. "napprox;": "≉",
  22939. "natural;": "♮",
  22940. "nearrow;": "↗",
  22941. "NewLine;": "\n",
  22942. "nexists;": "∄",
  22943. "NoBreak;": "⁠",
  22944. "notinva;": "∉",
  22945. "notinvb;": "⋷",
  22946. "notinvc;": "⋶",
  22947. "NotLess;": "≮",
  22948. "notniva;": "∌",
  22949. "notnivb;": "⋾",
  22950. "notnivc;": "⋽",
  22951. "npolint;": "⨔",
  22952. "npreceq;": "⪯̸",
  22953. "nsqsube;": "⋢",
  22954. "nsqsupe;": "⋣",
  22955. "nsubset;": "⊂⃒",
  22956. "nsucceq;": "⪰̸",
  22957. "nsupset;": "⊃⃒",
  22958. "nvinfin;": "⧞",
  22959. "nvltrie;": "⊴⃒",
  22960. "nvrtrie;": "⊵⃒",
  22961. "nwarrow;": "↖",
  22962. "olcross;": "⦻",
  22963. "Omicron;": "Ο",
  22964. "omicron;": "ο",
  22965. "orderof;": "ℴ",
  22966. "orslope;": "⩗",
  22967. "OverBar;": "‾",
  22968. "pertenk;": "‱",
  22969. "planckh;": "ℎ",
  22970. "pluscir;": "⨢",
  22971. "plussim;": "⨦",
  22972. "plustwo;": "⨧",
  22973. "precsim;": "≾",
  22974. "Product;": "∏",
  22975. "quatint;": "⨖",
  22976. "questeq;": "≟",
  22977. "rarrbfs;": "⤠",
  22978. "rarrsim;": "⥴",
  22979. "rbrksld;": "⦎",
  22980. "rbrkslu;": "⦐",
  22981. "rdldhar;": "⥩",
  22982. "realine;": "ℛ",
  22983. "rotimes;": "⨵",
  22984. "ruluhar;": "⥨",
  22985. "searrow;": "↘",
  22986. "simplus;": "⨤",
  22987. "simrarr;": "⥲",
  22988. "subedot;": "⫃",
  22989. "submult;": "⫁",
  22990. "subplus;": "⪿",
  22991. "subrarr;": "⥹",
  22992. "succsim;": "≿",
  22993. "supdsub;": "⫘",
  22994. "supedot;": "⫄",
  22995. "suphsol;": "⟉",
  22996. "suphsub;": "⫗",
  22997. "suplarr;": "⥻",
  22998. "supmult;": "⫂",
  22999. "supplus;": "⫀",
  23000. "swarrow;": "↙",
  23001. "topfork;": "⫚",
  23002. "triplus;": "⨹",
  23003. "tritime;": "⨻",
  23004. "UpArrow;": "↑",
  23005. "Uparrow;": "⇑",
  23006. "uparrow;": "↑",
  23007. "Upsilon;": "Υ",
  23008. "upsilon;": "υ",
  23009. "uwangle;": "⦧",
  23010. "vzigzag;": "⦚",
  23011. "zigrarr;": "⇝",
  23012. "andslope;": "⩘",
  23013. "angmsdaa;": "⦨",
  23014. "angmsdab;": "⦩",
  23015. "angmsdac;": "⦪",
  23016. "angmsdad;": "⦫",
  23017. "angmsdae;": "⦬",
  23018. "angmsdaf;": "⦭",
  23019. "angmsdag;": "⦮",
  23020. "angmsdah;": "⦯",
  23021. "angrtvbd;": "⦝",
  23022. "approxeq;": "≊",
  23023. "awconint;": "∳",
  23024. "backcong;": "≌",
  23025. "barwedge;": "⌅",
  23026. "bbrktbrk;": "⎶",
  23027. "bigoplus;": "⨁",
  23028. "bigsqcup;": "⨆",
  23029. "biguplus;": "⨄",
  23030. "bigwedge;": "⋀",
  23031. "boxminus;": "⊟",
  23032. "boxtimes;": "⊠",
  23033. "bsolhsub;": "⟈",
  23034. "capbrcup;": "⩉",
  23035. "circledR;": "®",
  23036. "circledS;": "Ⓢ",
  23037. "cirfnint;": "⨐",
  23038. "clubsuit;": "♣",
  23039. "cupbrcap;": "⩈",
  23040. "curlyvee;": "⋎",
  23041. "cwconint;": "∲",
  23042. "DDotrahd;": "⤑",
  23043. "doteqdot;": "≑",
  23044. "DotEqual;": "≐",
  23045. "dotminus;": "∸",
  23046. "drbkarow;": "⤐",
  23047. "dzigrarr;": "⟿",
  23048. "elinters;": "⏧",
  23049. "emptyset;": "∅",
  23050. "eqvparsl;": "⧥",
  23051. "fpartint;": "⨍",
  23052. "geqslant;": "⩾",
  23053. "gesdotol;": "⪄",
  23054. "gnapprox;": "⪊",
  23055. "hksearow;": "⤥",
  23056. "hkswarow;": "⤦",
  23057. "imagline;": "ℐ",
  23058. "imagpart;": "ℑ",
  23059. "infintie;": "⧝",
  23060. "integers;": "ℤ",
  23061. "Integral;": "∫",
  23062. "intercal;": "⊺",
  23063. "intlarhk;": "⨗",
  23064. "laemptyv;": "⦴",
  23065. "ldrushar;": "⥋",
  23066. "leqslant;": "⩽",
  23067. "lesdotor;": "⪃",
  23068. "LessLess;": "⪡",
  23069. "llcorner;": "⌞",
  23070. "lnapprox;": "⪉",
  23071. "lrcorner;": "⌟",
  23072. "lurdshar;": "⥊",
  23073. "mapstoup;": "↥",
  23074. "multimap;": "⊸",
  23075. "naturals;": "ℕ",
  23076. "ncongdot;": "⩭̸",
  23077. "NotEqual;": "≠",
  23078. "notindot;": "⋵̸",
  23079. "NotTilde;": "≁",
  23080. "otimesas;": "⨶",
  23081. "parallel;": "∥",
  23082. "PartialD;": "∂",
  23083. "plusacir;": "⨣",
  23084. "pointint;": "⨕",
  23085. "Precedes;": "≺",
  23086. "precneqq;": "⪵",
  23087. "precnsim;": "⋨",
  23088. "profalar;": "⌮",
  23089. "profline;": "⌒",
  23090. "profsurf;": "⌓",
  23091. "raemptyv;": "⦳",
  23092. "realpart;": "ℜ",
  23093. "RightTee;": "⊢",
  23094. "rppolint;": "⨒",
  23095. "rtriltri;": "⧎",
  23096. "scpolint;": "⨓",
  23097. "setminus;": "∖",
  23098. "shortmid;": "∣",
  23099. "smeparsl;": "⧤",
  23100. "sqsubset;": "⊏",
  23101. "sqsupset;": "⊐",
  23102. "subseteq;": "⊆",
  23103. "Succeeds;": "≻",
  23104. "succneqq;": "⪶",
  23105. "succnsim;": "⋩",
  23106. "SuchThat;": "∋",
  23107. "Superset;": "⊃",
  23108. "supseteq;": "⊇",
  23109. "thetasym;": "ϑ",
  23110. "thicksim;": "∼",
  23111. "timesbar;": "⨱",
  23112. "triangle;": "▵",
  23113. "triminus;": "⨺",
  23114. "trpezium;": "⏢",
  23115. "Uarrocir;": "⥉",
  23116. "ulcorner;": "⌜",
  23117. "UnderBar;": "_",
  23118. "urcorner;": "⌝",
  23119. "varkappa;": "ϰ",
  23120. "varsigma;": "ς",
  23121. "vartheta;": "ϑ",
  23122. "backprime;": "‵",
  23123. "backsimeq;": "⋍",
  23124. "Backslash;": "∖",
  23125. "bigotimes;": "⨂",
  23126. "CenterDot;": "·",
  23127. "centerdot;": "·",
  23128. "checkmark;": "✓",
  23129. "CircleDot;": "⊙",
  23130. "complexes;": "ℂ",
  23131. "Congruent;": "≡",
  23132. "Coproduct;": "∐",
  23133. "dotsquare;": "⊡",
  23134. "DoubleDot;": "¨",
  23135. "DownArrow;": "↓",
  23136. "Downarrow;": "⇓",
  23137. "downarrow;": "↓",
  23138. "DownBreve;": "̑",
  23139. "gtrapprox;": "⪆",
  23140. "gtreqless;": "⋛",
  23141. "gvertneqq;": "≩︀",
  23142. "heartsuit;": "♥",
  23143. "HumpEqual;": "≏",
  23144. "LeftArrow;": "←",
  23145. "Leftarrow;": "⇐",
  23146. "leftarrow;": "←",
  23147. "LeftFloor;": "⌊",
  23148. "lesseqgtr;": "⋚",
  23149. "LessTilde;": "≲",
  23150. "lvertneqq;": "≨︀",
  23151. "Mellintrf;": "ℳ",
  23152. "MinusPlus;": "∓",
  23153. "ngeqslant;": "⩾̸",
  23154. "nleqslant;": "⩽̸",
  23155. "NotCupCap;": "≭",
  23156. "NotExists;": "∄",
  23157. "NotSubset;": "⊂⃒",
  23158. "nparallel;": "∦",
  23159. "nshortmid;": "∤",
  23160. "nsubseteq;": "⊈",
  23161. "nsupseteq;": "⊉",
  23162. "OverBrace;": "⏞",
  23163. "pitchfork;": "⋔",
  23164. "PlusMinus;": "±",
  23165. "rationals;": "ℚ",
  23166. "spadesuit;": "♠",
  23167. "subseteqq;": "⫅",
  23168. "subsetneq;": "⊊",
  23169. "supseteqq;": "⫆",
  23170. "supsetneq;": "⊋",
  23171. "Therefore;": "∴",
  23172. "therefore;": "∴",
  23173. "ThinSpace;": " ",
  23174. "triangleq;": "≜",
  23175. "TripleDot;": "⃛",
  23176. "UnionPlus;": "⊎",
  23177. "varpropto;": "∝",
  23178. "Bernoullis;": "ℬ",
  23179. "circledast;": "⊛",
  23180. "CirclePlus;": "⊕",
  23181. "complement;": "∁",
  23182. "curlywedge;": "⋏",
  23183. "eqslantgtr;": "⪖",
  23184. "EqualTilde;": "≂",
  23185. "Fouriertrf;": "ℱ",
  23186. "gtreqqless;": "⪌",
  23187. "ImaginaryI;": "ⅈ",
  23188. "Laplacetrf;": "ℒ",
  23189. "LeftVector;": "↼",
  23190. "lessapprox;": "⪅",
  23191. "lesseqqgtr;": "⪋",
  23192. "Lleftarrow;": "⇚",
  23193. "lmoustache;": "⎰",
  23194. "longmapsto;": "⟼",
  23195. "mapstodown;": "↧",
  23196. "mapstoleft;": "↤",
  23197. "nLeftarrow;": "⇍",
  23198. "nleftarrow;": "↚",
  23199. "NotElement;": "∉",
  23200. "NotGreater;": "≯",
  23201. "nsubseteqq;": "⫅̸",
  23202. "nsupseteqq;": "⫆̸",
  23203. "precapprox;": "⪷",
  23204. "Proportion;": "∷",
  23205. "RightArrow;": "→",
  23206. "Rightarrow;": "⇒",
  23207. "rightarrow;": "→",
  23208. "RightFloor;": "⌋",
  23209. "rmoustache;": "⎱",
  23210. "sqsubseteq;": "⊑",
  23211. "sqsupseteq;": "⊒",
  23212. "subsetneqq;": "⫋",
  23213. "succapprox;": "⪸",
  23214. "supsetneqq;": "⫌",
  23215. "ThickSpace;": "  ",
  23216. "TildeEqual;": "≃",
  23217. "TildeTilde;": "≈",
  23218. "UnderBrace;": "⏟",
  23219. "UpArrowBar;": "⤒",
  23220. "UpTeeArrow;": "↥",
  23221. "upuparrows;": "⇈",
  23222. "varepsilon;": "ϵ",
  23223. "varnothing;": "∅",
  23224. "backepsilon;": "϶",
  23225. "blacksquare;": "▪",
  23226. "circledcirc;": "⊚",
  23227. "circleddash;": "⊝",
  23228. "CircleMinus;": "⊖",
  23229. "CircleTimes;": "⊗",
  23230. "curlyeqprec;": "⋞",
  23231. "curlyeqsucc;": "⋟",
  23232. "diamondsuit;": "♦",
  23233. "eqslantless;": "⪕",
  23234. "Equilibrium;": "⇌",
  23235. "expectation;": "ℰ",
  23236. "GreaterLess;": "≷",
  23237. "LeftCeiling;": "⌈",
  23238. "LessGreater;": "≶",
  23239. "MediumSpace;": " ",
  23240. "NotLessLess;": "≪̸",
  23241. "NotPrecedes;": "⊀",
  23242. "NotSucceeds;": "⊁",
  23243. "NotSuperset;": "⊃⃒",
  23244. "nRightarrow;": "⇏",
  23245. "nrightarrow;": "↛",
  23246. "OverBracket;": "⎴",
  23247. "preccurlyeq;": "≼",
  23248. "precnapprox;": "⪹",
  23249. "quaternions;": "ℍ",
  23250. "RightVector;": "⇀",
  23251. "Rrightarrow;": "⇛",
  23252. "RuleDelayed;": "⧴",
  23253. "SmallCircle;": "∘",
  23254. "SquareUnion;": "⊔",
  23255. "straightphi;": "ϕ",
  23256. "SubsetEqual;": "⊆",
  23257. "succcurlyeq;": "≽",
  23258. "succnapprox;": "⪺",
  23259. "thickapprox;": "≈",
  23260. "UpDownArrow;": "↕",
  23261. "Updownarrow;": "⇕",
  23262. "updownarrow;": "↕",
  23263. "VerticalBar;": "∣",
  23264. "blacklozenge;": "⧫",
  23265. "DownArrowBar;": "⤓",
  23266. "DownTeeArrow;": "↧",
  23267. "ExponentialE;": "ⅇ",
  23268. "exponentiale;": "ⅇ",
  23269. "GreaterEqual;": "≥",
  23270. "GreaterTilde;": "≳",
  23271. "HilbertSpace;": "ℋ",
  23272. "HumpDownHump;": "≎",
  23273. "Intersection;": "⋂",
  23274. "LeftArrowBar;": "⇤",
  23275. "LeftTeeArrow;": "↤",
  23276. "LeftTriangle;": "⊲",
  23277. "LeftUpVector;": "↿",
  23278. "NotCongruent;": "≢",
  23279. "NotHumpEqual;": "≏̸",
  23280. "NotLessEqual;": "≰",
  23281. "NotLessTilde;": "≴",
  23282. "Proportional;": "∝",
  23283. "RightCeiling;": "⌉",
  23284. "risingdotseq;": "≓",
  23285. "RoundImplies;": "⥰",
  23286. "ShortUpArrow;": "↑",
  23287. "SquareSubset;": "⊏",
  23288. "triangledown;": "▿",
  23289. "triangleleft;": "◃",
  23290. "UnderBracket;": "⎵",
  23291. "varsubsetneq;": "⊊︀",
  23292. "varsupsetneq;": "⊋︀",
  23293. "VerticalLine;": "|",
  23294. "ApplyFunction;": "⁡",
  23295. "bigtriangleup;": "△",
  23296. "blacktriangle;": "▴",
  23297. "DifferentialD;": "ⅆ",
  23298. "divideontimes;": "⋇",
  23299. "DoubleLeftTee;": "⫤",
  23300. "DoubleUpArrow;": "⇑",
  23301. "fallingdotseq;": "≒",
  23302. "hookleftarrow;": "↩",
  23303. "leftarrowtail;": "↢",
  23304. "leftharpoonup;": "↼",
  23305. "LeftTeeVector;": "⥚",
  23306. "LeftVectorBar;": "⥒",
  23307. "LessFullEqual;": "≦",
  23308. "LongLeftArrow;": "⟵",
  23309. "Longleftarrow;": "⟸",
  23310. "longleftarrow;": "⟵",
  23311. "looparrowleft;": "↫",
  23312. "measuredangle;": "∡",
  23313. "NotEqualTilde;": "≂̸",
  23314. "NotTildeEqual;": "≄",
  23315. "NotTildeTilde;": "≉",
  23316. "ntriangleleft;": "⋪",
  23317. "Poincareplane;": "ℌ",
  23318. "PrecedesEqual;": "⪯",
  23319. "PrecedesTilde;": "≾",
  23320. "RightArrowBar;": "⇥",
  23321. "RightTeeArrow;": "↦",
  23322. "RightTriangle;": "⊳",
  23323. "RightUpVector;": "↾",
  23324. "shortparallel;": "∥",
  23325. "smallsetminus;": "∖",
  23326. "SucceedsEqual;": "⪰",
  23327. "SucceedsTilde;": "≿",
  23328. "SupersetEqual;": "⊇",
  23329. "triangleright;": "▹",
  23330. "UpEquilibrium;": "⥮",
  23331. "upharpoonleft;": "↿",
  23332. "varsubsetneqq;": "⫋︀",
  23333. "varsupsetneqq;": "⫌︀",
  23334. "VerticalTilde;": "≀",
  23335. "VeryThinSpace;": " ",
  23336. "curvearrowleft;": "↶",
  23337. "DiacriticalDot;": "˙",
  23338. "doublebarwedge;": "⌆",
  23339. "DoubleRightTee;": "⊨",
  23340. "downdownarrows;": "⇊",
  23341. "DownLeftVector;": "↽",
  23342. "GreaterGreater;": "⪢",
  23343. "hookrightarrow;": "↪",
  23344. "HorizontalLine;": "─",
  23345. "InvisibleComma;": "⁣",
  23346. "InvisibleTimes;": "⁢",
  23347. "LeftDownVector;": "⇃",
  23348. "leftleftarrows;": "⇇",
  23349. "LeftRightArrow;": "↔",
  23350. "Leftrightarrow;": "⇔",
  23351. "leftrightarrow;": "↔",
  23352. "leftthreetimes;": "⋋",
  23353. "LessSlantEqual;": "⩽",
  23354. "LongRightArrow;": "⟶",
  23355. "Longrightarrow;": "⟹",
  23356. "longrightarrow;": "⟶",
  23357. "looparrowright;": "↬",
  23358. "LowerLeftArrow;": "↙",
  23359. "NestedLessLess;": "≪",
  23360. "NotGreaterLess;": "≹",
  23361. "NotLessGreater;": "≸",
  23362. "NotSubsetEqual;": "⊈",
  23363. "NotVerticalBar;": "∤",
  23364. "nshortparallel;": "∦",
  23365. "ntriangleright;": "⋫",
  23366. "OpenCurlyQuote;": "‘",
  23367. "ReverseElement;": "∋",
  23368. "rightarrowtail;": "↣",
  23369. "rightharpoonup;": "⇀",
  23370. "RightTeeVector;": "⥛",
  23371. "RightVectorBar;": "⥓",
  23372. "ShortDownArrow;": "↓",
  23373. "ShortLeftArrow;": "←",
  23374. "SquareSuperset;": "⊐",
  23375. "TildeFullEqual;": "≅",
  23376. "trianglelefteq;": "⊴",
  23377. "upharpoonright;": "↾",
  23378. "UpperLeftArrow;": "↖",
  23379. "ZeroWidthSpace;": "​",
  23380. "bigtriangledown;": "▽",
  23381. "circlearrowleft;": "↺",
  23382. "CloseCurlyQuote;": "’",
  23383. "ContourIntegral;": "∮",
  23384. "curvearrowright;": "↷",
  23385. "DoubleDownArrow;": "⇓",
  23386. "DoubleLeftArrow;": "⇐",
  23387. "downharpoonleft;": "⇃",
  23388. "DownRightVector;": "⇁",
  23389. "leftharpoondown;": "↽",
  23390. "leftrightarrows;": "⇆",
  23391. "LeftRightVector;": "⥎",
  23392. "LeftTriangleBar;": "⧏",
  23393. "LeftUpTeeVector;": "⥠",
  23394. "LeftUpVectorBar;": "⥘",
  23395. "LowerRightArrow;": "↘",
  23396. "nLeftrightarrow;": "⇎",
  23397. "nleftrightarrow;": "↮",
  23398. "NotGreaterEqual;": "≱",
  23399. "NotGreaterTilde;": "≵",
  23400. "NotHumpDownHump;": "≎̸",
  23401. "NotLeftTriangle;": "⋪",
  23402. "NotSquareSubset;": "⊏̸",
  23403. "ntrianglelefteq;": "⋬",
  23404. "OverParenthesis;": "⏜",
  23405. "RightDownVector;": "⇂",
  23406. "rightleftarrows;": "⇄",
  23407. "rightsquigarrow;": "↝",
  23408. "rightthreetimes;": "⋌",
  23409. "ShortRightArrow;": "→",
  23410. "straightepsilon;": "ϵ",
  23411. "trianglerighteq;": "⊵",
  23412. "UpperRightArrow;": "↗",
  23413. "vartriangleleft;": "⊲",
  23414. "circlearrowright;": "↻",
  23415. "DiacriticalAcute;": "´",
  23416. "DiacriticalGrave;": "`",
  23417. "DiacriticalTilde;": "˜",
  23418. "DoubleRightArrow;": "⇒",
  23419. "DownArrowUpArrow;": "⇵",
  23420. "downharpoonright;": "⇂",
  23421. "EmptySmallSquare;": "◻",
  23422. "GreaterEqualLess;": "⋛",
  23423. "GreaterFullEqual;": "≧",
  23424. "LeftAngleBracket;": "⟨",
  23425. "LeftUpDownVector;": "⥑",
  23426. "LessEqualGreater;": "⋚",
  23427. "NonBreakingSpace;": " ",
  23428. "NotPrecedesEqual;": "⪯̸",
  23429. "NotRightTriangle;": "⋫",
  23430. "NotSucceedsEqual;": "⪰̸",
  23431. "NotSucceedsTilde;": "≿̸",
  23432. "NotSupersetEqual;": "⊉",
  23433. "ntrianglerighteq;": "⋭",
  23434. "rightharpoondown;": "⇁",
  23435. "rightrightarrows;": "⇉",
  23436. "RightTriangleBar;": "⧐",
  23437. "RightUpTeeVector;": "⥜",
  23438. "RightUpVectorBar;": "⥔",
  23439. "twoheadleftarrow;": "↞",
  23440. "UnderParenthesis;": "⏝",
  23441. "UpArrowDownArrow;": "⇅",
  23442. "vartriangleright;": "⊳",
  23443. "blacktriangledown;": "▾",
  23444. "blacktriangleleft;": "◂",
  23445. "DoubleUpDownArrow;": "⇕",
  23446. "DoubleVerticalBar;": "∥",
  23447. "DownLeftTeeVector;": "⥞",
  23448. "DownLeftVectorBar;": "⥖",
  23449. "FilledSmallSquare;": "◼",
  23450. "GreaterSlantEqual;": "⩾",
  23451. "LeftDoubleBracket;": "⟦",
  23452. "LeftDownTeeVector;": "⥡",
  23453. "LeftDownVectorBar;": "⥙",
  23454. "leftrightharpoons;": "⇋",
  23455. "LeftTriangleEqual;": "⊴",
  23456. "NegativeThinSpace;": "​",
  23457. "NotGreaterGreater;": "≫̸",
  23458. "NotLessSlantEqual;": "⩽̸",
  23459. "NotNestedLessLess;": "⪡̸",
  23460. "NotReverseElement;": "∌",
  23461. "NotSquareSuperset;": "⊐̸",
  23462. "NotTildeFullEqual;": "≇",
  23463. "RightAngleBracket;": "⟩",
  23464. "rightleftharpoons;": "⇌",
  23465. "RightUpDownVector;": "⥏",
  23466. "SquareSubsetEqual;": "⊑",
  23467. "twoheadrightarrow;": "↠",
  23468. "VerticalSeparator;": "❘",
  23469. "blacktriangleright;": "▸",
  23470. "DownRightTeeVector;": "⥟",
  23471. "DownRightVectorBar;": "⥗",
  23472. "LongLeftRightArrow;": "⟷",
  23473. "Longleftrightarrow;": "⟺",
  23474. "longleftrightarrow;": "⟷",
  23475. "NegativeThickSpace;": "​",
  23476. "NotLeftTriangleBar;": "⧏̸",
  23477. "PrecedesSlantEqual;": "≼",
  23478. "ReverseEquilibrium;": "⇋",
  23479. "RightDoubleBracket;": "⟧",
  23480. "RightDownTeeVector;": "⥝",
  23481. "RightDownVectorBar;": "⥕",
  23482. "RightTriangleEqual;": "⊵",
  23483. "SquareIntersection;": "⊓",
  23484. "SucceedsSlantEqual;": "≽",
  23485. "DoubleLongLeftArrow;": "⟸",
  23486. "DownLeftRightVector;": "⥐",
  23487. "LeftArrowRightArrow;": "⇆",
  23488. "leftrightsquigarrow;": "↭",
  23489. "NegativeMediumSpace;": "​",
  23490. "NotGreaterFullEqual;": "≧̸",
  23491. "NotRightTriangleBar;": "⧐̸",
  23492. "RightArrowLeftArrow;": "⇄",
  23493. "SquareSupersetEqual;": "⊒",
  23494. "CapitalDifferentialD;": "ⅅ",
  23495. "DoubleLeftRightArrow;": "⇔",
  23496. "DoubleLongRightArrow;": "⟹",
  23497. "EmptyVerySmallSquare;": "▫",
  23498. "NestedGreaterGreater;": "≫",
  23499. "NotDoubleVerticalBar;": "∦",
  23500. "NotGreaterSlantEqual;": "⩾̸",
  23501. "NotLeftTriangleEqual;": "⋬",
  23502. "NotSquareSubsetEqual;": "⋢",
  23503. "OpenCurlyDoubleQuote;": "“",
  23504. "ReverseUpEquilibrium;": "⥯",
  23505. "CloseCurlyDoubleQuote;": "”",
  23506. "DoubleContourIntegral;": "∯",
  23507. "FilledVerySmallSquare;": "▪",
  23508. "NegativeVeryThinSpace;": "​",
  23509. "NotPrecedesSlantEqual;": "⋠",
  23510. "NotRightTriangleEqual;": "⋭",
  23511. "NotSucceedsSlantEqual;": "⋡",
  23512. "DiacriticalDoubleAcute;": "˝",
  23513. "NotSquareSupersetEqual;": "⋣",
  23514. "NotNestedGreaterGreater;": "⪢̸",
  23515. "ClockwiseContourIntegral;": "∲",
  23516. "DoubleLongLeftRightArrow;": "⟺",
  23517. "CounterClockwiseContourIntegral;": "∳"
  23518. };
  23519. // lazy compute this to make this file tree-shakable for browser
  23520. let maxCRNameLength;
  23521. const decodeHtml = (rawText, asAttr) => {
  23522. let offset = 0;
  23523. const end = rawText.length;
  23524. let decodedText = '';
  23525. function advance(length) {
  23526. offset += length;
  23527. rawText = rawText.slice(length);
  23528. }
  23529. while (offset < end) {
  23530. const head = /&(?:#x?)?/i.exec(rawText);
  23531. if (!head || offset + head.index >= end) {
  23532. const remaining = end - offset;
  23533. decodedText += rawText.slice(0, remaining);
  23534. advance(remaining);
  23535. break;
  23536. }
  23537. // Advance to the "&".
  23538. decodedText += rawText.slice(0, head.index);
  23539. advance(head.index);
  23540. if (head[0] === '&') {
  23541. // Named character reference.
  23542. let name = '';
  23543. let value = undefined;
  23544. if (/[0-9a-z]/i.test(rawText[1])) {
  23545. if (!maxCRNameLength) {
  23546. maxCRNameLength = Object.keys(namedCharacterReferences).reduce((max, name) => Math.max(max, name.length), 0);
  23547. }
  23548. for (let length = maxCRNameLength; !value && length > 0; --length) {
  23549. name = rawText.slice(1, 1 + length);
  23550. value = namedCharacterReferences[name];
  23551. }
  23552. if (value) {
  23553. const semi = name.endsWith(';');
  23554. if (asAttr &&
  23555. !semi &&
  23556. /[=a-z0-9]/i.test(rawText[name.length + 1] || '')) {
  23557. decodedText += '&' + name;
  23558. advance(1 + name.length);
  23559. }
  23560. else {
  23561. decodedText += value;
  23562. advance(1 + name.length);
  23563. }
  23564. }
  23565. else {
  23566. decodedText += '&' + name;
  23567. advance(1 + name.length);
  23568. }
  23569. }
  23570. else {
  23571. decodedText += '&';
  23572. advance(1);
  23573. }
  23574. }
  23575. else {
  23576. // Numeric character reference.
  23577. const hex = head[0] === '&#x';
  23578. const pattern = hex ? /^&#x([0-9a-f]+);?/i : /^&#([0-9]+);?/;
  23579. const body = pattern.exec(rawText);
  23580. if (!body) {
  23581. decodedText += head[0];
  23582. advance(head[0].length);
  23583. }
  23584. else {
  23585. // https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
  23586. let cp = Number.parseInt(body[1], hex ? 16 : 10);
  23587. if (cp === 0) {
  23588. cp = 0xfffd;
  23589. }
  23590. else if (cp > 0x10ffff) {
  23591. cp = 0xfffd;
  23592. }
  23593. else if (cp >= 0xd800 && cp <= 0xdfff) {
  23594. cp = 0xfffd;
  23595. }
  23596. else if ((cp >= 0xfdd0 && cp <= 0xfdef) || (cp & 0xfffe) === 0xfffe) ;
  23597. else if ((cp >= 0x01 && cp <= 0x08) ||
  23598. cp === 0x0b ||
  23599. (cp >= 0x0d && cp <= 0x1f) ||
  23600. (cp >= 0x7f && cp <= 0x9f)) {
  23601. cp = CCR_REPLACEMENTS[cp] || cp;
  23602. }
  23603. decodedText += String.fromCodePoint(cp);
  23604. advance(body[0].length);
  23605. }
  23606. }
  23607. }
  23608. return decodedText;
  23609. };
  23610. // https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
  23611. const CCR_REPLACEMENTS = {
  23612. 0x80: 0x20ac,
  23613. 0x82: 0x201a,
  23614. 0x83: 0x0192,
  23615. 0x84: 0x201e,
  23616. 0x85: 0x2026,
  23617. 0x86: 0x2020,
  23618. 0x87: 0x2021,
  23619. 0x88: 0x02c6,
  23620. 0x89: 0x2030,
  23621. 0x8a: 0x0160,
  23622. 0x8b: 0x2039,
  23623. 0x8c: 0x0152,
  23624. 0x8e: 0x017d,
  23625. 0x91: 0x2018,
  23626. 0x92: 0x2019,
  23627. 0x93: 0x201c,
  23628. 0x94: 0x201d,
  23629. 0x95: 0x2022,
  23630. 0x96: 0x2013,
  23631. 0x97: 0x2014,
  23632. 0x98: 0x02dc,
  23633. 0x99: 0x2122,
  23634. 0x9a: 0x0161,
  23635. 0x9b: 0x203a,
  23636. 0x9c: 0x0153,
  23637. 0x9e: 0x017e,
  23638. 0x9f: 0x0178
  23639. };
  23640. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  23641. const parserOptions = {
  23642. isVoidTag,
  23643. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  23644. isPreTag: tag => tag === 'pre',
  23645. decodeEntities: decodeHtml,
  23646. isBuiltInComponent: (tag) => {
  23647. if (isBuiltInType(tag, `Transition`)) {
  23648. return TRANSITION;
  23649. }
  23650. else if (isBuiltInType(tag, `TransitionGroup`)) {
  23651. return TRANSITION_GROUP;
  23652. }
  23653. },
  23654. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  23655. getNamespace(tag, parent) {
  23656. let ns = parent ? parent.ns : 0 /* DOMNamespaces.HTML */;
  23657. if (parent && ns === 2 /* DOMNamespaces.MATH_ML */) {
  23658. if (parent.tag === 'annotation-xml') {
  23659. if (tag === 'svg') {
  23660. return 1 /* DOMNamespaces.SVG */;
  23661. }
  23662. if (parent.props.some(a => a.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  23663. a.name === 'encoding' &&
  23664. a.value != null &&
  23665. (a.value.content === 'text/html' ||
  23666. a.value.content === 'application/xhtml+xml'))) {
  23667. ns = 0 /* DOMNamespaces.HTML */;
  23668. }
  23669. }
  23670. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  23671. tag !== 'mglyph' &&
  23672. tag !== 'malignmark') {
  23673. ns = 0 /* DOMNamespaces.HTML */;
  23674. }
  23675. }
  23676. else if (parent && ns === 1 /* DOMNamespaces.SVG */) {
  23677. if (parent.tag === 'foreignObject' ||
  23678. parent.tag === 'desc' ||
  23679. parent.tag === 'title') {
  23680. ns = 0 /* DOMNamespaces.HTML */;
  23681. }
  23682. }
  23683. if (ns === 0 /* DOMNamespaces.HTML */) {
  23684. if (tag === 'svg') {
  23685. return 1 /* DOMNamespaces.SVG */;
  23686. }
  23687. if (tag === 'math') {
  23688. return 2 /* DOMNamespaces.MATH_ML */;
  23689. }
  23690. }
  23691. return ns;
  23692. },
  23693. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  23694. getTextMode({ tag, ns }) {
  23695. if (ns === 0 /* DOMNamespaces.HTML */) {
  23696. if (tag === 'textarea' || tag === 'title') {
  23697. return 1 /* TextModes.RCDATA */;
  23698. }
  23699. if (isRawTextContainer(tag)) {
  23700. return 2 /* TextModes.RAWTEXT */;
  23701. }
  23702. }
  23703. return 0 /* TextModes.DATA */;
  23704. }
  23705. };
  23706. // Parse inline CSS strings for static style attributes into an object.
  23707. // This is a NodeTransform since it works on the static `style` attribute and
  23708. // converts it into a dynamic equivalent:
  23709. // style="color: red" -> :style='{ "color": "red" }'
  23710. // It is then processed by `transformElement` and included in the generated
  23711. // props.
  23712. const transformStyle = node => {
  23713. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  23714. node.props.forEach((p, i) => {
  23715. if (p.type === 6 /* NodeTypes.ATTRIBUTE */ && p.name === 'style' && p.value) {
  23716. // replace p with an expression node
  23717. node.props[i] = {
  23718. type: 7 /* NodeTypes.DIRECTIVE */,
  23719. name: `bind`,
  23720. arg: createSimpleExpression(`style`, true, p.loc),
  23721. exp: parseInlineCSS(p.value.content, p.loc),
  23722. modifiers: [],
  23723. loc: p.loc
  23724. };
  23725. }
  23726. });
  23727. }
  23728. };
  23729. const parseInlineCSS = (cssText, loc) => {
  23730. const normalized = parseStringStyle(cssText);
  23731. return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  23732. };
  23733. function createDOMCompilerError(code, loc) {
  23734. return createCompilerError(code, loc, DOMErrorMessages );
  23735. }
  23736. const DOMErrorMessages = {
  23737. [51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  23738. [52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  23739. [53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  23740. [54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  23741. [55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  23742. [56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  23743. [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.`,
  23744. [58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  23745. [59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  23746. [60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  23747. [61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  23748. };
  23749. const transformVHtml = (dir, node, context) => {
  23750. const { exp, loc } = dir;
  23751. if (!exp) {
  23752. context.onError(createDOMCompilerError(51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */, loc));
  23753. }
  23754. if (node.children.length) {
  23755. context.onError(createDOMCompilerError(52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */, loc));
  23756. node.children.length = 0;
  23757. }
  23758. return {
  23759. props: [
  23760. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  23761. ]
  23762. };
  23763. };
  23764. const transformVText = (dir, node, context) => {
  23765. const { exp, loc } = dir;
  23766. if (!exp) {
  23767. context.onError(createDOMCompilerError(53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */, loc));
  23768. }
  23769. if (node.children.length) {
  23770. context.onError(createDOMCompilerError(54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */, loc));
  23771. node.children.length = 0;
  23772. }
  23773. return {
  23774. props: [
  23775. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  23776. ? getConstantType(exp, context) > 0
  23777. ? exp
  23778. : createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  23779. : createSimpleExpression('', true))
  23780. ]
  23781. };
  23782. };
  23783. const transformModel = (dir, node, context) => {
  23784. const baseResult = transformModel$1(dir, node, context);
  23785. // base transform has errors OR component v-model (only need props)
  23786. if (!baseResult.props.length || node.tagType === 1 /* ElementTypes.COMPONENT */) {
  23787. return baseResult;
  23788. }
  23789. if (dir.arg) {
  23790. context.onError(createDOMCompilerError(56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  23791. }
  23792. function checkDuplicatedValue() {
  23793. const value = findProp(node, 'value');
  23794. if (value) {
  23795. context.onError(createDOMCompilerError(58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  23796. }
  23797. }
  23798. const { tag } = node;
  23799. const isCustomElement = context.isCustomElement(tag);
  23800. if (tag === 'input' ||
  23801. tag === 'textarea' ||
  23802. tag === 'select' ||
  23803. isCustomElement) {
  23804. let directiveToUse = V_MODEL_TEXT;
  23805. let isInvalidType = false;
  23806. if (tag === 'input' || isCustomElement) {
  23807. const type = findProp(node, `type`);
  23808. if (type) {
  23809. if (type.type === 7 /* NodeTypes.DIRECTIVE */) {
  23810. // :type="foo"
  23811. directiveToUse = V_MODEL_DYNAMIC;
  23812. }
  23813. else if (type.value) {
  23814. switch (type.value.content) {
  23815. case 'radio':
  23816. directiveToUse = V_MODEL_RADIO;
  23817. break;
  23818. case 'checkbox':
  23819. directiveToUse = V_MODEL_CHECKBOX;
  23820. break;
  23821. case 'file':
  23822. isInvalidType = true;
  23823. context.onError(createDOMCompilerError(57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  23824. break;
  23825. default:
  23826. // text type
  23827. checkDuplicatedValue();
  23828. break;
  23829. }
  23830. }
  23831. }
  23832. else if (hasDynamicKeyVBind(node)) {
  23833. // element has bindings with dynamic keys, which can possibly contain
  23834. // "type".
  23835. directiveToUse = V_MODEL_DYNAMIC;
  23836. }
  23837. else {
  23838. // text type
  23839. checkDuplicatedValue();
  23840. }
  23841. }
  23842. else if (tag === 'select') {
  23843. directiveToUse = V_MODEL_SELECT;
  23844. }
  23845. else {
  23846. // textarea
  23847. checkDuplicatedValue();
  23848. }
  23849. // inject runtime directive
  23850. // by returning the helper symbol via needRuntime
  23851. // the import will replaced a resolveDirective call.
  23852. if (!isInvalidType) {
  23853. baseResult.needRuntime = context.helper(directiveToUse);
  23854. }
  23855. }
  23856. else {
  23857. context.onError(createDOMCompilerError(55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  23858. }
  23859. // native vmodel doesn't need the `modelValue` props since they are also
  23860. // passed to the runtime as `binding.value`. removing it reduces code size.
  23861. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  23862. p.key.content === 'modelValue'));
  23863. return baseResult;
  23864. };
  23865. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  23866. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  23867. // event propagation management
  23868. `stop,prevent,self,` +
  23869. // system modifiers + exact
  23870. `ctrl,shift,alt,meta,exact,` +
  23871. // mouse
  23872. `middle`);
  23873. // left & right could be mouse or key modifiers based on event type
  23874. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  23875. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  23876. const resolveModifiers = (key, modifiers, context, loc) => {
  23877. const keyModifiers = [];
  23878. const nonKeyModifiers = [];
  23879. const eventOptionModifiers = [];
  23880. for (let i = 0; i < modifiers.length; i++) {
  23881. const modifier = modifiers[i];
  23882. if (isEventOptionModifier(modifier)) {
  23883. // eventOptionModifiers: modifiers for addEventListener() options,
  23884. // e.g. .passive & .capture
  23885. eventOptionModifiers.push(modifier);
  23886. }
  23887. else {
  23888. // runtimeModifiers: modifiers that needs runtime guards
  23889. if (maybeKeyModifier(modifier)) {
  23890. if (isStaticExp(key)) {
  23891. if (isKeyboardEvent(key.content)) {
  23892. keyModifiers.push(modifier);
  23893. }
  23894. else {
  23895. nonKeyModifiers.push(modifier);
  23896. }
  23897. }
  23898. else {
  23899. keyModifiers.push(modifier);
  23900. nonKeyModifiers.push(modifier);
  23901. }
  23902. }
  23903. else {
  23904. if (isNonKeyModifier(modifier)) {
  23905. nonKeyModifiers.push(modifier);
  23906. }
  23907. else {
  23908. keyModifiers.push(modifier);
  23909. }
  23910. }
  23911. }
  23912. }
  23913. return {
  23914. keyModifiers,
  23915. nonKeyModifiers,
  23916. eventOptionModifiers
  23917. };
  23918. };
  23919. const transformClick = (key, event) => {
  23920. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  23921. return isStaticClick
  23922. ? createSimpleExpression(event, true)
  23923. : key.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */
  23924. ? createCompoundExpression([
  23925. `(`,
  23926. key,
  23927. `) === "onClick" ? "${event}" : (`,
  23928. key,
  23929. `)`
  23930. ])
  23931. : key;
  23932. };
  23933. const transformOn = (dir, node, context) => {
  23934. return transformOn$1(dir, node, context, baseResult => {
  23935. const { modifiers } = dir;
  23936. if (!modifiers.length)
  23937. return baseResult;
  23938. let { key, value: handlerExp } = baseResult.props[0];
  23939. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
  23940. // normalize click.right and click.middle since they don't actually fire
  23941. if (nonKeyModifiers.includes('right')) {
  23942. key = transformClick(key, `onContextmenu`);
  23943. }
  23944. if (nonKeyModifiers.includes('middle')) {
  23945. key = transformClick(key, `onMouseup`);
  23946. }
  23947. if (nonKeyModifiers.length) {
  23948. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  23949. handlerExp,
  23950. JSON.stringify(nonKeyModifiers)
  23951. ]);
  23952. }
  23953. if (keyModifiers.length &&
  23954. // if event name is dynamic, always wrap with keys guard
  23955. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  23956. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  23957. handlerExp,
  23958. JSON.stringify(keyModifiers)
  23959. ]);
  23960. }
  23961. if (eventOptionModifiers.length) {
  23962. const modifierPostfix = eventOptionModifiers.map(capitalize$1).join('');
  23963. key = isStaticExp(key)
  23964. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  23965. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  23966. }
  23967. return {
  23968. props: [createObjectProperty(key, handlerExp)]
  23969. };
  23970. });
  23971. };
  23972. const transformShow = (dir, node, context) => {
  23973. const { exp, loc } = dir;
  23974. if (!exp) {
  23975. context.onError(createDOMCompilerError(59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */, loc));
  23976. }
  23977. return {
  23978. props: [],
  23979. needRuntime: context.helper(V_SHOW)
  23980. };
  23981. };
  23982. const transformTransition = (node, context) => {
  23983. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  23984. node.tagType === 1 /* ElementTypes.COMPONENT */) {
  23985. const component = context.isBuiltInComponent(node.tag);
  23986. if (component === TRANSITION) {
  23987. return () => {
  23988. if (!node.children.length) {
  23989. return;
  23990. }
  23991. // warn multiple transition children
  23992. if (hasMultipleChildren(node)) {
  23993. context.onError(createDOMCompilerError(60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */, {
  23994. start: node.children[0].loc.start,
  23995. end: node.children[node.children.length - 1].loc.end,
  23996. source: ''
  23997. }));
  23998. }
  23999. // check if it's s single child w/ v-show
  24000. // if yes, inject "persisted: true" to the transition props
  24001. const child = node.children[0];
  24002. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  24003. for (const p of child.props) {
  24004. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'show') {
  24005. node.props.push({
  24006. type: 6 /* NodeTypes.ATTRIBUTE */,
  24007. name: 'persisted',
  24008. value: undefined,
  24009. loc: node.loc
  24010. });
  24011. }
  24012. }
  24013. }
  24014. };
  24015. }
  24016. }
  24017. };
  24018. function hasMultipleChildren(node) {
  24019. // #1352 filter out potential comment nodes.
  24020. const children = (node.children = node.children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */ &&
  24021. !(c.type === 2 /* NodeTypes.TEXT */ && !c.content.trim())));
  24022. const child = children[0];
  24023. return (children.length !== 1 ||
  24024. child.type === 11 /* NodeTypes.FOR */ ||
  24025. (child.type === 9 /* NodeTypes.IF */ && child.branches.some(hasMultipleChildren)));
  24026. }
  24027. /**
  24028. * This module is Node-only.
  24029. */
  24030. /**
  24031. * Regex for replacing placeholders for embedded constant variables
  24032. * (e.g. import URL string constants generated by compiler-sfc)
  24033. */
  24034. const expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g;
  24035. /**
  24036. * Turn eligible hoisted static trees into stringified static nodes, e.g.
  24037. *
  24038. * ```js
  24039. * const _hoisted_1 = createStaticVNode(`<div class="foo">bar</div>`)
  24040. * ```
  24041. *
  24042. * A single static vnode can contain stringified content for **multiple**
  24043. * consecutive nodes (element and plain text), called a "chunk".
  24044. * `@vue/runtime-dom` will create the content via innerHTML in a hidden
  24045. * container element and insert all the nodes in place. The call must also
  24046. * provide the number of nodes contained in the chunk so that during hydration
  24047. * we can know how many nodes the static vnode should adopt.
  24048. *
  24049. * The optimization scans a children list that contains hoisted nodes, and
  24050. * tries to find the largest chunk of consecutive hoisted nodes before running
  24051. * into a non-hoisted node or the end of the list. A chunk is then converted
  24052. * into a single static vnode and replaces the hoisted expression of the first
  24053. * node in the chunk. Other nodes in the chunk are considered "merged" and
  24054. * therefore removed from both the hoist list and the children array.
  24055. *
  24056. * This optimization is only performed in Node.js.
  24057. */
  24058. const stringifyStatic = (children, context, parent) => {
  24059. // bail stringification for slot content
  24060. if (context.scopes.vSlot > 0) {
  24061. return;
  24062. }
  24063. let nc = 0; // current node count
  24064. let ec = 0; // current element with binding count
  24065. const currentChunk = [];
  24066. const stringifyCurrentChunk = (currentIndex) => {
  24067. if (nc >= 20 /* StringifyThresholds.NODE_COUNT */ ||
  24068. ec >= 5 /* StringifyThresholds.ELEMENT_WITH_BINDING_COUNT */) {
  24069. // combine all currently eligible nodes into a single static vnode call
  24070. const staticCall = createCallExpression(context.helper(CREATE_STATIC), [
  24071. JSON.stringify(currentChunk.map(node => stringifyNode(node, context)).join('')).replace(expReplaceRE, `" + $1 + "`),
  24072. // the 2nd argument indicates the number of DOM nodes this static vnode
  24073. // will insert / hydrate
  24074. String(currentChunk.length)
  24075. ]);
  24076. // replace the first node's hoisted expression with the static vnode call
  24077. replaceHoist(currentChunk[0], staticCall, context);
  24078. if (currentChunk.length > 1) {
  24079. for (let i = 1; i < currentChunk.length; i++) {
  24080. // for the merged nodes, set their hoisted expression to null
  24081. replaceHoist(currentChunk[i], null, context);
  24082. }
  24083. // also remove merged nodes from children
  24084. const deleteCount = currentChunk.length - 1;
  24085. children.splice(currentIndex - currentChunk.length + 1, deleteCount);
  24086. return deleteCount;
  24087. }
  24088. }
  24089. return 0;
  24090. };
  24091. let i = 0;
  24092. for (; i < children.length; i++) {
  24093. const child = children[i];
  24094. const hoisted = getHoistedNode(child);
  24095. if (hoisted) {
  24096. // presence of hoisted means child must be a stringifiable node
  24097. const node = child;
  24098. const result = analyzeNode(node);
  24099. if (result) {
  24100. // node is stringifiable, record state
  24101. nc += result[0];
  24102. ec += result[1];
  24103. currentChunk.push(node);
  24104. continue;
  24105. }
  24106. }
  24107. // we only reach here if we ran into a node that is not stringifiable
  24108. // check if currently analyzed nodes meet criteria for stringification.
  24109. // adjust iteration index
  24110. i -= stringifyCurrentChunk(i);
  24111. // reset state
  24112. nc = 0;
  24113. ec = 0;
  24114. currentChunk.length = 0;
  24115. }
  24116. // in case the last node was also stringifiable
  24117. stringifyCurrentChunk(i);
  24118. };
  24119. const getHoistedNode = (node) => ((node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 0 /* ElementTypes.ELEMENT */) ||
  24120. node.type == 12 /* NodeTypes.TEXT_CALL */) &&
  24121. node.codegenNode &&
  24122. node.codegenNode.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  24123. node.codegenNode.hoisted;
  24124. const dataAriaRE = /^(data|aria)-/;
  24125. const isStringifiableAttr = (name, ns) => {
  24126. return ((ns === 0 /* DOMNamespaces.HTML */
  24127. ? isKnownHtmlAttr(name)
  24128. : ns === 1 /* DOMNamespaces.SVG */
  24129. ? isKnownSvgAttr(name)
  24130. : false) || dataAriaRE.test(name));
  24131. };
  24132. const replaceHoist = (node, replacement, context) => {
  24133. const hoistToReplace = node.codegenNode.hoisted;
  24134. context.hoists[context.hoists.indexOf(hoistToReplace)] = replacement;
  24135. };
  24136. const isNonStringifiable = /*#__PURE__*/ makeMap(`caption,thead,tr,th,tbody,td,tfoot,colgroup,col`);
  24137. /**
  24138. * for a hoisted node, analyze it and return:
  24139. * - false: bailed (contains non-stringifiable props or runtime constant)
  24140. * - [nc, ec] where
  24141. * - nc is the number of nodes inside
  24142. * - ec is the number of element with bindings inside
  24143. */
  24144. function analyzeNode(node) {
  24145. if (node.type === 1 /* NodeTypes.ELEMENT */ && isNonStringifiable(node.tag)) {
  24146. return false;
  24147. }
  24148. if (node.type === 12 /* NodeTypes.TEXT_CALL */) {
  24149. return [1, 0];
  24150. }
  24151. let nc = 1; // node count
  24152. let ec = node.props.length > 0 ? 1 : 0; // element w/ binding count
  24153. let bailed = false;
  24154. const bail = () => {
  24155. bailed = true;
  24156. return false;
  24157. };
  24158. // TODO: check for cases where using innerHTML will result in different
  24159. // output compared to imperative node insertions.
  24160. // probably only need to check for most common case
  24161. // i.e. non-phrasing-content tags inside `<p>`
  24162. function walk(node) {
  24163. for (let i = 0; i < node.props.length; i++) {
  24164. const p = node.props[i];
  24165. // bail on non-attr bindings
  24166. if (p.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  24167. !isStringifiableAttr(p.name, node.ns)) {
  24168. return bail();
  24169. }
  24170. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'bind') {
  24171. // bail on non-attr bindings
  24172. if (p.arg &&
  24173. (p.arg.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */ ||
  24174. (p.arg.isStatic && !isStringifiableAttr(p.arg.content, node.ns)))) {
  24175. return bail();
  24176. }
  24177. if (p.exp &&
  24178. (p.exp.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */ ||
  24179. p.exp.constType < 3 /* ConstantTypes.CAN_STRINGIFY */)) {
  24180. return bail();
  24181. }
  24182. }
  24183. }
  24184. for (let i = 0; i < node.children.length; i++) {
  24185. nc++;
  24186. const child = node.children[i];
  24187. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  24188. if (child.props.length > 0) {
  24189. ec++;
  24190. }
  24191. walk(child);
  24192. if (bailed) {
  24193. return false;
  24194. }
  24195. }
  24196. }
  24197. return true;
  24198. }
  24199. return walk(node) ? [nc, ec] : false;
  24200. }
  24201. function stringifyNode(node, context) {
  24202. if (isString$2(node)) {
  24203. return node;
  24204. }
  24205. if (isSymbol$1(node)) {
  24206. return ``;
  24207. }
  24208. switch (node.type) {
  24209. case 1 /* NodeTypes.ELEMENT */:
  24210. return stringifyElement(node, context);
  24211. case 2 /* NodeTypes.TEXT */:
  24212. return escapeHtml(node.content);
  24213. case 3 /* NodeTypes.COMMENT */:
  24214. return `<!--${escapeHtml(node.content)}-->`;
  24215. case 5 /* NodeTypes.INTERPOLATION */:
  24216. return escapeHtml(toDisplayString(evaluateConstant(node.content)));
  24217. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  24218. return escapeHtml(evaluateConstant(node));
  24219. case 12 /* NodeTypes.TEXT_CALL */:
  24220. return stringifyNode(node.content, context);
  24221. default:
  24222. // static trees will not contain if/for nodes
  24223. return '';
  24224. }
  24225. }
  24226. function stringifyElement(node, context) {
  24227. let res = `<${node.tag}`;
  24228. let innerHTML = '';
  24229. for (let i = 0; i < node.props.length; i++) {
  24230. const p = node.props[i];
  24231. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  24232. res += ` ${p.name}`;
  24233. if (p.value) {
  24234. res += `="${escapeHtml(p.value.content)}"`;
  24235. }
  24236. }
  24237. else if (p.type === 7 /* NodeTypes.DIRECTIVE */) {
  24238. if (p.name === 'bind') {
  24239. const exp = p.exp;
  24240. if (exp.content[0] === '_') {
  24241. // internally generated string constant references
  24242. // e.g. imported URL strings via compiler-sfc transformAssetUrl plugin
  24243. res += ` ${p.arg.content}="__VUE_EXP_START__${exp.content}__VUE_EXP_END__"`;
  24244. continue;
  24245. }
  24246. // #6568
  24247. if (isBooleanAttr(p.arg.content) &&
  24248. exp.content === 'false') {
  24249. continue;
  24250. }
  24251. // constant v-bind, e.g. :foo="1"
  24252. let evaluated = evaluateConstant(exp);
  24253. if (evaluated != null) {
  24254. const arg = p.arg && p.arg.content;
  24255. if (arg === 'class') {
  24256. evaluated = normalizeClass(evaluated);
  24257. }
  24258. else if (arg === 'style') {
  24259. evaluated = stringifyStyle(normalizeStyle(evaluated));
  24260. }
  24261. res += ` ${p.arg.content}="${escapeHtml(evaluated)}"`;
  24262. }
  24263. }
  24264. else if (p.name === 'html') {
  24265. // #5439 v-html with constant value
  24266. // not sure why would anyone do this but it can happen
  24267. innerHTML = evaluateConstant(p.exp);
  24268. }
  24269. else if (p.name === 'text') {
  24270. innerHTML = escapeHtml(toDisplayString(evaluateConstant(p.exp)));
  24271. }
  24272. }
  24273. }
  24274. if (context.scopeId) {
  24275. res += ` ${context.scopeId}`;
  24276. }
  24277. res += `>`;
  24278. if (innerHTML) {
  24279. res += innerHTML;
  24280. }
  24281. else {
  24282. for (let i = 0; i < node.children.length; i++) {
  24283. res += stringifyNode(node.children[i], context);
  24284. }
  24285. }
  24286. if (!isVoidTag(node.tag)) {
  24287. res += `</${node.tag}>`;
  24288. }
  24289. return res;
  24290. }
  24291. // __UNSAFE__
  24292. // Reason: eval.
  24293. // It's technically safe to eval because only constant expressions are possible
  24294. // here, e.g. `{{ 1 }}` or `{{ 'foo' }}`
  24295. // in addition, constant exps bail on presence of parens so you can't even
  24296. // run JSFuck in here. But we mark it unsafe for security review purposes.
  24297. // (see compiler-core/src/transforms/transformExpression)
  24298. function evaluateConstant(exp) {
  24299. if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  24300. return new Function(`return ${exp.content}`)();
  24301. }
  24302. else {
  24303. // compound
  24304. let res = ``;
  24305. exp.children.forEach(c => {
  24306. if (isString$2(c) || isSymbol$1(c)) {
  24307. return;
  24308. }
  24309. if (c.type === 2 /* NodeTypes.TEXT */) {
  24310. res += c.content;
  24311. }
  24312. else if (c.type === 5 /* NodeTypes.INTERPOLATION */) {
  24313. res += toDisplayString(evaluateConstant(c.content));
  24314. }
  24315. else {
  24316. res += evaluateConstant(c);
  24317. }
  24318. });
  24319. return res;
  24320. }
  24321. }
  24322. const ignoreSideEffectTags = (node, context) => {
  24323. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  24324. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  24325. (node.tag === 'script' || node.tag === 'style')) {
  24326. context.onError(createDOMCompilerError(61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  24327. context.removeNode();
  24328. }
  24329. };
  24330. const DOMNodeTransforms = [
  24331. transformStyle,
  24332. ...([transformTransition] )
  24333. ];
  24334. const DOMDirectiveTransforms = {
  24335. cloak: noopDirectiveTransform,
  24336. html: transformVHtml,
  24337. text: transformVText,
  24338. model: transformModel,
  24339. on: transformOn,
  24340. show: transformShow
  24341. };
  24342. function compile$1(template, options = {}) {
  24343. return baseCompile(template, extend({}, parserOptions, options, {
  24344. nodeTransforms: [
  24345. // ignore <script> and <tag>
  24346. // this is not put inside DOMNodeTransforms because that list is used
  24347. // by compiler-ssr to generate vnode fallback branches
  24348. ignoreSideEffectTags,
  24349. ...DOMNodeTransforms,
  24350. ...(options.nodeTransforms || [])
  24351. ],
  24352. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  24353. transformHoist: stringifyStatic
  24354. }));
  24355. }
  24356. function parse$8(template, options = {}) {
  24357. return baseParse(template, extend({}, parserOptions, options));
  24358. }
  24359. var CompilerDOM = /*#__PURE__*/Object.freeze({
  24360. __proto__: null,
  24361. BASE_TRANSITION: BASE_TRANSITION,
  24362. CAMELIZE: CAMELIZE,
  24363. CAPITALIZE: CAPITALIZE,
  24364. CREATE_BLOCK: CREATE_BLOCK,
  24365. CREATE_COMMENT: CREATE_COMMENT,
  24366. CREATE_ELEMENT_BLOCK: CREATE_ELEMENT_BLOCK,
  24367. CREATE_ELEMENT_VNODE: CREATE_ELEMENT_VNODE,
  24368. CREATE_SLOTS: CREATE_SLOTS,
  24369. CREATE_STATIC: CREATE_STATIC,
  24370. CREATE_TEXT: CREATE_TEXT,
  24371. CREATE_VNODE: CREATE_VNODE,
  24372. DOMDirectiveTransforms: DOMDirectiveTransforms,
  24373. DOMNodeTransforms: DOMNodeTransforms,
  24374. FRAGMENT: FRAGMENT,
  24375. GUARD_REACTIVE_PROPS: GUARD_REACTIVE_PROPS,
  24376. IS_MEMO_SAME: IS_MEMO_SAME,
  24377. IS_REF: IS_REF,
  24378. KEEP_ALIVE: KEEP_ALIVE,
  24379. MERGE_PROPS: MERGE_PROPS,
  24380. NORMALIZE_CLASS: NORMALIZE_CLASS,
  24381. NORMALIZE_PROPS: NORMALIZE_PROPS,
  24382. NORMALIZE_STYLE: NORMALIZE_STYLE,
  24383. OPEN_BLOCK: OPEN_BLOCK,
  24384. POP_SCOPE_ID: POP_SCOPE_ID,
  24385. PUSH_SCOPE_ID: PUSH_SCOPE_ID,
  24386. RENDER_LIST: RENDER_LIST,
  24387. RENDER_SLOT: RENDER_SLOT,
  24388. RESOLVE_COMPONENT: RESOLVE_COMPONENT,
  24389. RESOLVE_DIRECTIVE: RESOLVE_DIRECTIVE,
  24390. RESOLVE_DYNAMIC_COMPONENT: RESOLVE_DYNAMIC_COMPONENT,
  24391. RESOLVE_FILTER: RESOLVE_FILTER,
  24392. SET_BLOCK_TRACKING: SET_BLOCK_TRACKING,
  24393. SUSPENSE: SUSPENSE,
  24394. TELEPORT: TELEPORT,
  24395. TO_DISPLAY_STRING: TO_DISPLAY_STRING,
  24396. TO_HANDLERS: TO_HANDLERS,
  24397. TO_HANDLER_KEY: TO_HANDLER_KEY,
  24398. TRANSITION: TRANSITION,
  24399. TRANSITION_GROUP: TRANSITION_GROUP,
  24400. UNREF: UNREF,
  24401. V_MODEL_CHECKBOX: V_MODEL_CHECKBOX,
  24402. V_MODEL_DYNAMIC: V_MODEL_DYNAMIC,
  24403. V_MODEL_RADIO: V_MODEL_RADIO,
  24404. V_MODEL_SELECT: V_MODEL_SELECT,
  24405. V_MODEL_TEXT: V_MODEL_TEXT,
  24406. V_ON_WITH_KEYS: V_ON_WITH_KEYS,
  24407. V_ON_WITH_MODIFIERS: V_ON_WITH_MODIFIERS,
  24408. V_SHOW: V_SHOW,
  24409. WITH_CTX: WITH_CTX,
  24410. WITH_DIRECTIVES: WITH_DIRECTIVES,
  24411. WITH_MEMO: WITH_MEMO,
  24412. advancePositionWithClone: advancePositionWithClone,
  24413. advancePositionWithMutation: advancePositionWithMutation,
  24414. assert: assert,
  24415. baseCompile: baseCompile,
  24416. baseParse: baseParse,
  24417. buildDirectiveArgs: buildDirectiveArgs,
  24418. buildProps: buildProps,
  24419. buildSlots: buildSlots,
  24420. checkCompatEnabled: checkCompatEnabled,
  24421. compile: compile$1,
  24422. createArrayExpression: createArrayExpression,
  24423. createAssignmentExpression: createAssignmentExpression,
  24424. createBlockStatement: createBlockStatement,
  24425. createCacheExpression: createCacheExpression,
  24426. createCallExpression: createCallExpression,
  24427. createCompilerError: createCompilerError,
  24428. createCompoundExpression: createCompoundExpression,
  24429. createConditionalExpression: createConditionalExpression,
  24430. createDOMCompilerError: createDOMCompilerError,
  24431. createForLoopParams: createForLoopParams,
  24432. createFunctionExpression: createFunctionExpression,
  24433. createIfStatement: createIfStatement,
  24434. createInterpolation: createInterpolation,
  24435. createObjectExpression: createObjectExpression,
  24436. createObjectProperty: createObjectProperty,
  24437. createReturnStatement: createReturnStatement,
  24438. createRoot: createRoot,
  24439. createSequenceExpression: createSequenceExpression,
  24440. createSimpleExpression: createSimpleExpression,
  24441. createStructuralDirectiveTransform: createStructuralDirectiveTransform,
  24442. createTemplateLiteral: createTemplateLiteral,
  24443. createTransformContext: createTransformContext,
  24444. createVNodeCall: createVNodeCall,
  24445. extractIdentifiers: extractIdentifiers,
  24446. findDir: findDir,
  24447. findProp: findProp,
  24448. generate: generate,
  24449. generateCodeFrame: generateCodeFrame,
  24450. getBaseTransformPreset: getBaseTransformPreset,
  24451. getConstantType: getConstantType,
  24452. getInnerRange: getInnerRange,
  24453. getMemoedVNodeCall: getMemoedVNodeCall,
  24454. getVNodeBlockHelper: getVNodeBlockHelper,
  24455. getVNodeHelper: getVNodeHelper,
  24456. hasDynamicKeyVBind: hasDynamicKeyVBind,
  24457. hasScopeRef: hasScopeRef,
  24458. helperNameMap: helperNameMap,
  24459. injectProp: injectProp,
  24460. isBuiltInType: isBuiltInType,
  24461. isCoreComponent: isCoreComponent,
  24462. isFunctionType: isFunctionType,
  24463. isInDestructureAssignment: isInDestructureAssignment,
  24464. isMemberExpression: isMemberExpression,
  24465. isMemberExpressionBrowser: isMemberExpressionBrowser,
  24466. isMemberExpressionNode: isMemberExpressionNode,
  24467. isReferencedIdentifier: isReferencedIdentifier,
  24468. isSimpleIdentifier: isSimpleIdentifier,
  24469. isSlotOutlet: isSlotOutlet,
  24470. isStaticArgOf: isStaticArgOf,
  24471. isStaticExp: isStaticExp,
  24472. isStaticProperty: isStaticProperty,
  24473. isStaticPropertyKey: isStaticPropertyKey,
  24474. isTemplateNode: isTemplateNode,
  24475. isText: isText$1,
  24476. isVSlot: isVSlot,
  24477. locStub: locStub,
  24478. makeBlock: makeBlock,
  24479. noopDirectiveTransform: noopDirectiveTransform,
  24480. parse: parse$8,
  24481. parserOptions: parserOptions,
  24482. processExpression: processExpression,
  24483. processFor: processFor,
  24484. processIf: processIf,
  24485. processSlotOutlet: processSlotOutlet,
  24486. registerRuntimeHelpers: registerRuntimeHelpers,
  24487. resolveComponentType: resolveComponentType,
  24488. stringifyExpression: stringifyExpression,
  24489. toValidAssetId: toValidAssetId,
  24490. trackSlotScopes: trackSlotScopes,
  24491. trackVForSlotScopes: trackVForSlotScopes,
  24492. transform: transform$1,
  24493. transformBind: transformBind,
  24494. transformElement: transformElement,
  24495. transformExpression: transformExpression,
  24496. transformModel: transformModel$1,
  24497. transformOn: transformOn$1,
  24498. transformStyle: transformStyle,
  24499. traverseNode: traverseNode,
  24500. walkBlockDeclarations: walkBlockDeclarations,
  24501. walkFunctionParams: walkFunctionParams,
  24502. walkIdentifiers: walkIdentifiers,
  24503. warnDeprecation: warnDeprecation
  24504. });
  24505. function pad$1 (hash, len) {
  24506. while (hash.length < len) {
  24507. hash = '0' + hash;
  24508. }
  24509. return hash;
  24510. }
  24511. function fold (hash, text) {
  24512. var i;
  24513. var chr;
  24514. var len;
  24515. if (text.length === 0) {
  24516. return hash;
  24517. }
  24518. for (i = 0, len = text.length; i < len; i++) {
  24519. chr = text.charCodeAt(i);
  24520. hash = ((hash << 5) - hash) + chr;
  24521. hash |= 0;
  24522. }
  24523. return hash < 0 ? hash * -2 : hash;
  24524. }
  24525. function foldObject (hash, o, seen) {
  24526. return Object.keys(o).sort().reduce(foldKey, hash);
  24527. function foldKey (hash, key) {
  24528. return foldValue(hash, o[key], key, seen);
  24529. }
  24530. }
  24531. function foldValue (input, value, key, seen) {
  24532. var hash = fold(fold(fold(input, key), toString$2(value)), typeof value);
  24533. if (value === null) {
  24534. return fold(hash, 'null');
  24535. }
  24536. if (value === undefined) {
  24537. return fold(hash, 'undefined');
  24538. }
  24539. if (typeof value === 'object' || typeof value === 'function') {
  24540. if (seen.indexOf(value) !== -1) {
  24541. return fold(hash, '[Circular]' + key);
  24542. }
  24543. seen.push(value);
  24544. var objHash = foldObject(hash, value, seen);
  24545. if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
  24546. return objHash;
  24547. }
  24548. try {
  24549. return fold(objHash, String(value.valueOf()))
  24550. } catch (err) {
  24551. return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
  24552. }
  24553. }
  24554. return fold(hash, value.toString());
  24555. }
  24556. function toString$2 (o) {
  24557. return Object.prototype.toString.call(o);
  24558. }
  24559. function sum (o) {
  24560. return pad$1(foldValue(0, o, '', []).toString(16), 8);
  24561. }
  24562. var hashSum = sum;
  24563. var hash = hashSum;
  24564. const CSS_VARS_HELPER = `useCssVars`;
  24565. function genCssVarsFromList(vars, id, isProd, isSSR = false) {
  24566. return `{\n ${vars
  24567. .map(key => `"${isSSR ? `--` : ``}${genVarName(id, key, isProd)}": (${key})`)
  24568. .join(',\n ')}\n}`;
  24569. }
  24570. function genVarName(id, raw, isProd) {
  24571. if (isProd) {
  24572. return hash(id + raw);
  24573. }
  24574. else {
  24575. // escape ASCII Punctuation & Symbols
  24576. return `${id}-${raw.replace(/[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g, s => `\\${s}`)}`;
  24577. }
  24578. }
  24579. function normalizeExpression(exp) {
  24580. exp = exp.trim();
  24581. if ((exp[0] === `'` && exp[exp.length - 1] === `'`) ||
  24582. (exp[0] === `"` && exp[exp.length - 1] === `"`)) {
  24583. return exp.slice(1, -1);
  24584. }
  24585. return exp;
  24586. }
  24587. const vBindRE = /v-bind\s*\(/g;
  24588. function parseCssVars(sfc) {
  24589. const vars = [];
  24590. sfc.styles.forEach(style => {
  24591. let match;
  24592. // ignore v-bind() in comments /* ... */
  24593. const content = style.content.replace(/\/\*([\s\S]*?)\*\//g, '');
  24594. while ((match = vBindRE.exec(content))) {
  24595. const start = match.index + match[0].length;
  24596. const end = lexBinding(content, start);
  24597. if (end !== null) {
  24598. const variable = normalizeExpression(content.slice(start, end));
  24599. if (!vars.includes(variable)) {
  24600. vars.push(variable);
  24601. }
  24602. }
  24603. }
  24604. });
  24605. return vars;
  24606. }
  24607. function lexBinding(content, start) {
  24608. let state = 0 /* LexerState.inParens */;
  24609. let parenDepth = 0;
  24610. for (let i = start; i < content.length; i++) {
  24611. const char = content.charAt(i);
  24612. switch (state) {
  24613. case 0 /* LexerState.inParens */:
  24614. if (char === `'`) {
  24615. state = 1 /* LexerState.inSingleQuoteString */;
  24616. }
  24617. else if (char === `"`) {
  24618. state = 2 /* LexerState.inDoubleQuoteString */;
  24619. }
  24620. else if (char === `(`) {
  24621. parenDepth++;
  24622. }
  24623. else if (char === `)`) {
  24624. if (parenDepth > 0) {
  24625. parenDepth--;
  24626. }
  24627. else {
  24628. return i;
  24629. }
  24630. }
  24631. break;
  24632. case 1 /* LexerState.inSingleQuoteString */:
  24633. if (char === `'`) {
  24634. state = 0 /* LexerState.inParens */;
  24635. }
  24636. break;
  24637. case 2 /* LexerState.inDoubleQuoteString */:
  24638. if (char === `"`) {
  24639. state = 0 /* LexerState.inParens */;
  24640. }
  24641. break;
  24642. }
  24643. }
  24644. return null;
  24645. }
  24646. const cssVarsPlugin = opts => {
  24647. const { id, isProd } = opts;
  24648. return {
  24649. postcssPlugin: 'vue-sfc-vars',
  24650. Declaration(decl) {
  24651. // rewrite CSS variables
  24652. const value = decl.value;
  24653. if (vBindRE.test(value)) {
  24654. vBindRE.lastIndex = 0;
  24655. let transformed = '';
  24656. let lastIndex = 0;
  24657. let match;
  24658. while ((match = vBindRE.exec(value))) {
  24659. const start = match.index + match[0].length;
  24660. const end = lexBinding(value, start);
  24661. if (end !== null) {
  24662. const variable = normalizeExpression(value.slice(start, end));
  24663. transformed +=
  24664. value.slice(lastIndex, match.index) +
  24665. `var(--${genVarName(id, variable, isProd)})`;
  24666. lastIndex = end + 1;
  24667. }
  24668. }
  24669. decl.value = transformed + value.slice(lastIndex);
  24670. }
  24671. }
  24672. };
  24673. };
  24674. cssVarsPlugin.postcss = true;
  24675. function genCssVarsCode(vars, bindings, id, isProd) {
  24676. const varsExp = genCssVarsFromList(vars, id, isProd);
  24677. const exp = createSimpleExpression(varsExp, false);
  24678. const context = createTransformContext(createRoot([]), {
  24679. prefixIdentifiers: true,
  24680. inline: true,
  24681. bindingMetadata: bindings.__isScriptSetup === false ? undefined : bindings
  24682. });
  24683. const transformed = processExpression(exp, context);
  24684. const transformedString = transformed.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */
  24685. ? transformed.content
  24686. : transformed.children
  24687. .map(c => {
  24688. return typeof c === 'string'
  24689. ? c
  24690. : c.content;
  24691. })
  24692. .join('');
  24693. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  24694. }
  24695. // <script setup> already gets the calls injected as part of the transform
  24696. // this is only for single normal <script>
  24697. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd) {
  24698. return (`\nimport { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'\n` +
  24699. `const __injectCSSVars__ = () => {\n${genCssVarsCode(cssVars, bindings, id, isProd)}}\n` +
  24700. `const __setup__ = __default__.setup\n` +
  24701. `__default__.setup = __setup__\n` +
  24702. ` ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }\n` +
  24703. ` : __injectCSSVars__\n`);
  24704. }
  24705. function createCache(size = 500) {
  24706. return new Map()
  24707. ;
  24708. }
  24709. var global$1 = (typeof global !== "undefined" ? global :
  24710. typeof self !== "undefined" ? self :
  24711. typeof window !== "undefined" ? window : {});
  24712. var lookup = [];
  24713. var revLookup = [];
  24714. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  24715. var inited = false;
  24716. function init () {
  24717. inited = true;
  24718. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  24719. for (var i = 0, len = code.length; i < len; ++i) {
  24720. lookup[i] = code[i];
  24721. revLookup[code.charCodeAt(i)] = i;
  24722. }
  24723. revLookup['-'.charCodeAt(0)] = 62;
  24724. revLookup['_'.charCodeAt(0)] = 63;
  24725. }
  24726. function toByteArray (b64) {
  24727. if (!inited) {
  24728. init();
  24729. }
  24730. var i, j, l, tmp, placeHolders, arr;
  24731. var len = b64.length;
  24732. if (len % 4 > 0) {
  24733. throw new Error('Invalid string. Length must be a multiple of 4')
  24734. }
  24735. // the number of equal signs (place holders)
  24736. // if there are two placeholders, than the two characters before it
  24737. // represent one byte
  24738. // if there is only one, then the three characters before it represent 2 bytes
  24739. // this is just a cheap hack to not do indexOf twice
  24740. placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
  24741. // base64 is 4/3 + up to two characters of the original data
  24742. arr = new Arr(len * 3 / 4 - placeHolders);
  24743. // if there are placeholders, only get up to the last complete 4 chars
  24744. l = placeHolders > 0 ? len - 4 : len;
  24745. var L = 0;
  24746. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  24747. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
  24748. arr[L++] = (tmp >> 16) & 0xFF;
  24749. arr[L++] = (tmp >> 8) & 0xFF;
  24750. arr[L++] = tmp & 0xFF;
  24751. }
  24752. if (placeHolders === 2) {
  24753. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
  24754. arr[L++] = tmp & 0xFF;
  24755. } else if (placeHolders === 1) {
  24756. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
  24757. arr[L++] = (tmp >> 8) & 0xFF;
  24758. arr[L++] = tmp & 0xFF;
  24759. }
  24760. return arr
  24761. }
  24762. function tripletToBase64 (num) {
  24763. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  24764. }
  24765. function encodeChunk (uint8, start, end) {
  24766. var tmp;
  24767. var output = [];
  24768. for (var i = start; i < end; i += 3) {
  24769. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
  24770. output.push(tripletToBase64(tmp));
  24771. }
  24772. return output.join('')
  24773. }
  24774. function fromByteArray (uint8) {
  24775. if (!inited) {
  24776. init();
  24777. }
  24778. var tmp;
  24779. var len = uint8.length;
  24780. var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  24781. var output = '';
  24782. var parts = [];
  24783. var maxChunkLength = 16383; // must be multiple of 3
  24784. // go through the array every three bytes, we'll deal with trailing stuff later
  24785. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  24786. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
  24787. }
  24788. // pad the end with zeros, but make sure to not forget the extra bytes
  24789. if (extraBytes === 1) {
  24790. tmp = uint8[len - 1];
  24791. output += lookup[tmp >> 2];
  24792. output += lookup[(tmp << 4) & 0x3F];
  24793. output += '==';
  24794. } else if (extraBytes === 2) {
  24795. tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
  24796. output += lookup[tmp >> 10];
  24797. output += lookup[(tmp >> 4) & 0x3F];
  24798. output += lookup[(tmp << 2) & 0x3F];
  24799. output += '=';
  24800. }
  24801. parts.push(output);
  24802. return parts.join('')
  24803. }
  24804. function read (buffer, offset, isLE, mLen, nBytes) {
  24805. var e, m;
  24806. var eLen = nBytes * 8 - mLen - 1;
  24807. var eMax = (1 << eLen) - 1;
  24808. var eBias = eMax >> 1;
  24809. var nBits = -7;
  24810. var i = isLE ? (nBytes - 1) : 0;
  24811. var d = isLE ? -1 : 1;
  24812. var s = buffer[offset + i];
  24813. i += d;
  24814. e = s & ((1 << (-nBits)) - 1);
  24815. s >>= (-nBits);
  24816. nBits += eLen;
  24817. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  24818. m = e & ((1 << (-nBits)) - 1);
  24819. e >>= (-nBits);
  24820. nBits += mLen;
  24821. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  24822. if (e === 0) {
  24823. e = 1 - eBias;
  24824. } else if (e === eMax) {
  24825. return m ? NaN : ((s ? -1 : 1) * Infinity)
  24826. } else {
  24827. m = m + Math.pow(2, mLen);
  24828. e = e - eBias;
  24829. }
  24830. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  24831. }
  24832. function write (buffer, value, offset, isLE, mLen, nBytes) {
  24833. var e, m, c;
  24834. var eLen = nBytes * 8 - mLen - 1;
  24835. var eMax = (1 << eLen) - 1;
  24836. var eBias = eMax >> 1;
  24837. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
  24838. var i = isLE ? 0 : (nBytes - 1);
  24839. var d = isLE ? 1 : -1;
  24840. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  24841. value = Math.abs(value);
  24842. if (isNaN(value) || value === Infinity) {
  24843. m = isNaN(value) ? 1 : 0;
  24844. e = eMax;
  24845. } else {
  24846. e = Math.floor(Math.log(value) / Math.LN2);
  24847. if (value * (c = Math.pow(2, -e)) < 1) {
  24848. e--;
  24849. c *= 2;
  24850. }
  24851. if (e + eBias >= 1) {
  24852. value += rt / c;
  24853. } else {
  24854. value += rt * Math.pow(2, 1 - eBias);
  24855. }
  24856. if (value * c >= 2) {
  24857. e++;
  24858. c /= 2;
  24859. }
  24860. if (e + eBias >= eMax) {
  24861. m = 0;
  24862. e = eMax;
  24863. } else if (e + eBias >= 1) {
  24864. m = (value * c - 1) * Math.pow(2, mLen);
  24865. e = e + eBias;
  24866. } else {
  24867. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  24868. e = 0;
  24869. }
  24870. }
  24871. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  24872. e = (e << mLen) | m;
  24873. eLen += mLen;
  24874. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  24875. buffer[offset + i - d] |= s * 128;
  24876. }
  24877. var toString$1 = {}.toString;
  24878. var isArray$2 = Array.isArray || function (arr) {
  24879. return toString$1.call(arr) == '[object Array]';
  24880. };
  24881. /*!
  24882. * The buffer module from node.js, for the browser.
  24883. *
  24884. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  24885. * @license MIT
  24886. */
  24887. var INSPECT_MAX_BYTES = 50;
  24888. /**
  24889. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  24890. * === true Use Uint8Array implementation (fastest)
  24891. * === false Use Object implementation (most compatible, even IE6)
  24892. *
  24893. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  24894. * Opera 11.6+, iOS 4.2+.
  24895. *
  24896. * Due to various browser bugs, sometimes the Object implementation will be used even
  24897. * when the browser supports typed arrays.
  24898. *
  24899. * Note:
  24900. *
  24901. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  24902. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  24903. *
  24904. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  24905. *
  24906. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  24907. * incorrect length in some situations.
  24908. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  24909. * get the Object implementation, which is slower but behaves correctly.
  24910. */
  24911. Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
  24912. ? global$1.TYPED_ARRAY_SUPPORT
  24913. : true;
  24914. /*
  24915. * Export kMaxLength after typed array support is determined.
  24916. */
  24917. kMaxLength();
  24918. function kMaxLength () {
  24919. return Buffer.TYPED_ARRAY_SUPPORT
  24920. ? 0x7fffffff
  24921. : 0x3fffffff
  24922. }
  24923. function createBuffer (that, length) {
  24924. if (kMaxLength() < length) {
  24925. throw new RangeError('Invalid typed array length')
  24926. }
  24927. if (Buffer.TYPED_ARRAY_SUPPORT) {
  24928. // Return an augmented `Uint8Array` instance, for best performance
  24929. that = new Uint8Array(length);
  24930. that.__proto__ = Buffer.prototype;
  24931. } else {
  24932. // Fallback: Return an object instance of the Buffer class
  24933. if (that === null) {
  24934. that = new Buffer(length);
  24935. }
  24936. that.length = length;
  24937. }
  24938. return that
  24939. }
  24940. /**
  24941. * The Buffer constructor returns instances of `Uint8Array` that have their
  24942. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  24943. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  24944. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  24945. * returns a single octet.
  24946. *
  24947. * The `Uint8Array` prototype remains unmodified.
  24948. */
  24949. function Buffer (arg, encodingOrOffset, length) {
  24950. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  24951. return new Buffer(arg, encodingOrOffset, length)
  24952. }
  24953. // Common case.
  24954. if (typeof arg === 'number') {
  24955. if (typeof encodingOrOffset === 'string') {
  24956. throw new Error(
  24957. 'If encoding is specified then the first argument must be a string'
  24958. )
  24959. }
  24960. return allocUnsafe(this, arg)
  24961. }
  24962. return from(this, arg, encodingOrOffset, length)
  24963. }
  24964. Buffer.poolSize = 8192; // not used by this implementation
  24965. // TODO: Legacy, not needed anymore. Remove in next major version.
  24966. Buffer._augment = function (arr) {
  24967. arr.__proto__ = Buffer.prototype;
  24968. return arr
  24969. };
  24970. function from (that, value, encodingOrOffset, length) {
  24971. if (typeof value === 'number') {
  24972. throw new TypeError('"value" argument must not be a number')
  24973. }
  24974. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  24975. return fromArrayBuffer(that, value, encodingOrOffset, length)
  24976. }
  24977. if (typeof value === 'string') {
  24978. return fromString(that, value, encodingOrOffset)
  24979. }
  24980. return fromObject(that, value)
  24981. }
  24982. /**
  24983. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  24984. * if value is a number.
  24985. * Buffer.from(str[, encoding])
  24986. * Buffer.from(array)
  24987. * Buffer.from(buffer)
  24988. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  24989. **/
  24990. Buffer.from = function (value, encodingOrOffset, length) {
  24991. return from(null, value, encodingOrOffset, length)
  24992. };
  24993. if (Buffer.TYPED_ARRAY_SUPPORT) {
  24994. Buffer.prototype.__proto__ = Uint8Array.prototype;
  24995. Buffer.__proto__ = Uint8Array;
  24996. if (typeof Symbol !== 'undefined' && Symbol.species &&
  24997. Buffer[Symbol.species] === Buffer) ;
  24998. }
  24999. function assertSize (size) {
  25000. if (typeof size !== 'number') {
  25001. throw new TypeError('"size" argument must be a number')
  25002. } else if (size < 0) {
  25003. throw new RangeError('"size" argument must not be negative')
  25004. }
  25005. }
  25006. function alloc (that, size, fill, encoding) {
  25007. assertSize(size);
  25008. if (size <= 0) {
  25009. return createBuffer(that, size)
  25010. }
  25011. if (fill !== undefined) {
  25012. // Only pay attention to encoding if it's a string. This
  25013. // prevents accidentally sending in a number that would
  25014. // be interpretted as a start offset.
  25015. return typeof encoding === 'string'
  25016. ? createBuffer(that, size).fill(fill, encoding)
  25017. : createBuffer(that, size).fill(fill)
  25018. }
  25019. return createBuffer(that, size)
  25020. }
  25021. /**
  25022. * Creates a new filled Buffer instance.
  25023. * alloc(size[, fill[, encoding]])
  25024. **/
  25025. Buffer.alloc = function (size, fill, encoding) {
  25026. return alloc(null, size, fill, encoding)
  25027. };
  25028. function allocUnsafe (that, size) {
  25029. assertSize(size);
  25030. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
  25031. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  25032. for (var i = 0; i < size; ++i) {
  25033. that[i] = 0;
  25034. }
  25035. }
  25036. return that
  25037. }
  25038. /**
  25039. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  25040. * */
  25041. Buffer.allocUnsafe = function (size) {
  25042. return allocUnsafe(null, size)
  25043. };
  25044. /**
  25045. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  25046. */
  25047. Buffer.allocUnsafeSlow = function (size) {
  25048. return allocUnsafe(null, size)
  25049. };
  25050. function fromString (that, string, encoding) {
  25051. if (typeof encoding !== 'string' || encoding === '') {
  25052. encoding = 'utf8';
  25053. }
  25054. if (!Buffer.isEncoding(encoding)) {
  25055. throw new TypeError('"encoding" must be a valid string encoding')
  25056. }
  25057. var length = byteLength(string, encoding) | 0;
  25058. that = createBuffer(that, length);
  25059. var actual = that.write(string, encoding);
  25060. if (actual !== length) {
  25061. // Writing a hex string, for example, that contains invalid characters will
  25062. // cause everything after the first invalid character to be ignored. (e.g.
  25063. // 'abxxcd' will be treated as 'ab')
  25064. that = that.slice(0, actual);
  25065. }
  25066. return that
  25067. }
  25068. function fromArrayLike (that, array) {
  25069. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  25070. that = createBuffer(that, length);
  25071. for (var i = 0; i < length; i += 1) {
  25072. that[i] = array[i] & 255;
  25073. }
  25074. return that
  25075. }
  25076. function fromArrayBuffer (that, array, byteOffset, length) {
  25077. array.byteLength; // this throws if `array` is not a valid ArrayBuffer
  25078. if (byteOffset < 0 || array.byteLength < byteOffset) {
  25079. throw new RangeError('\'offset\' is out of bounds')
  25080. }
  25081. if (array.byteLength < byteOffset + (length || 0)) {
  25082. throw new RangeError('\'length\' is out of bounds')
  25083. }
  25084. if (byteOffset === undefined && length === undefined) {
  25085. array = new Uint8Array(array);
  25086. } else if (length === undefined) {
  25087. array = new Uint8Array(array, byteOffset);
  25088. } else {
  25089. array = new Uint8Array(array, byteOffset, length);
  25090. }
  25091. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25092. // Return an augmented `Uint8Array` instance, for best performance
  25093. that = array;
  25094. that.__proto__ = Buffer.prototype;
  25095. } else {
  25096. // Fallback: Return an object instance of the Buffer class
  25097. that = fromArrayLike(that, array);
  25098. }
  25099. return that
  25100. }
  25101. function fromObject (that, obj) {
  25102. if (internalIsBuffer(obj)) {
  25103. var len = checked(obj.length) | 0;
  25104. that = createBuffer(that, len);
  25105. if (that.length === 0) {
  25106. return that
  25107. }
  25108. obj.copy(that, 0, 0, len);
  25109. return that
  25110. }
  25111. if (obj) {
  25112. if ((typeof ArrayBuffer !== 'undefined' &&
  25113. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  25114. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  25115. return createBuffer(that, 0)
  25116. }
  25117. return fromArrayLike(that, obj)
  25118. }
  25119. if (obj.type === 'Buffer' && isArray$2(obj.data)) {
  25120. return fromArrayLike(that, obj.data)
  25121. }
  25122. }
  25123. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  25124. }
  25125. function checked (length) {
  25126. // Note: cannot use `length < kMaxLength()` here because that fails when
  25127. // length is NaN (which is otherwise coerced to zero.)
  25128. if (length >= kMaxLength()) {
  25129. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  25130. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  25131. }
  25132. return length | 0
  25133. }
  25134. Buffer.isBuffer = isBuffer$1;
  25135. function internalIsBuffer (b) {
  25136. return !!(b != null && b._isBuffer)
  25137. }
  25138. Buffer.compare = function compare (a, b) {
  25139. if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
  25140. throw new TypeError('Arguments must be Buffers')
  25141. }
  25142. if (a === b) return 0
  25143. var x = a.length;
  25144. var y = b.length;
  25145. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  25146. if (a[i] !== b[i]) {
  25147. x = a[i];
  25148. y = b[i];
  25149. break
  25150. }
  25151. }
  25152. if (x < y) return -1
  25153. if (y < x) return 1
  25154. return 0
  25155. };
  25156. Buffer.isEncoding = function isEncoding (encoding) {
  25157. switch (String(encoding).toLowerCase()) {
  25158. case 'hex':
  25159. case 'utf8':
  25160. case 'utf-8':
  25161. case 'ascii':
  25162. case 'latin1':
  25163. case 'binary':
  25164. case 'base64':
  25165. case 'ucs2':
  25166. case 'ucs-2':
  25167. case 'utf16le':
  25168. case 'utf-16le':
  25169. return true
  25170. default:
  25171. return false
  25172. }
  25173. };
  25174. Buffer.concat = function concat (list, length) {
  25175. if (!isArray$2(list)) {
  25176. throw new TypeError('"list" argument must be an Array of Buffers')
  25177. }
  25178. if (list.length === 0) {
  25179. return Buffer.alloc(0)
  25180. }
  25181. var i;
  25182. if (length === undefined) {
  25183. length = 0;
  25184. for (i = 0; i < list.length; ++i) {
  25185. length += list[i].length;
  25186. }
  25187. }
  25188. var buffer = Buffer.allocUnsafe(length);
  25189. var pos = 0;
  25190. for (i = 0; i < list.length; ++i) {
  25191. var buf = list[i];
  25192. if (!internalIsBuffer(buf)) {
  25193. throw new TypeError('"list" argument must be an Array of Buffers')
  25194. }
  25195. buf.copy(buffer, pos);
  25196. pos += buf.length;
  25197. }
  25198. return buffer
  25199. };
  25200. function byteLength (string, encoding) {
  25201. if (internalIsBuffer(string)) {
  25202. return string.length
  25203. }
  25204. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  25205. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  25206. return string.byteLength
  25207. }
  25208. if (typeof string !== 'string') {
  25209. string = '' + string;
  25210. }
  25211. var len = string.length;
  25212. if (len === 0) return 0
  25213. // Use a for loop to avoid recursion
  25214. var loweredCase = false;
  25215. for (;;) {
  25216. switch (encoding) {
  25217. case 'ascii':
  25218. case 'latin1':
  25219. case 'binary':
  25220. return len
  25221. case 'utf8':
  25222. case 'utf-8':
  25223. case undefined:
  25224. return utf8ToBytes(string).length
  25225. case 'ucs2':
  25226. case 'ucs-2':
  25227. case 'utf16le':
  25228. case 'utf-16le':
  25229. return len * 2
  25230. case 'hex':
  25231. return len >>> 1
  25232. case 'base64':
  25233. return base64ToBytes(string).length
  25234. default:
  25235. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  25236. encoding = ('' + encoding).toLowerCase();
  25237. loweredCase = true;
  25238. }
  25239. }
  25240. }
  25241. Buffer.byteLength = byteLength;
  25242. function slowToString (encoding, start, end) {
  25243. var loweredCase = false;
  25244. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  25245. // property of a typed array.
  25246. // This behaves neither like String nor Uint8Array in that we set start/end
  25247. // to their upper/lower bounds if the value passed is out of range.
  25248. // undefined is handled specially as per ECMA-262 6th Edition,
  25249. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  25250. if (start === undefined || start < 0) {
  25251. start = 0;
  25252. }
  25253. // Return early if start > this.length. Done here to prevent potential uint32
  25254. // coercion fail below.
  25255. if (start > this.length) {
  25256. return ''
  25257. }
  25258. if (end === undefined || end > this.length) {
  25259. end = this.length;
  25260. }
  25261. if (end <= 0) {
  25262. return ''
  25263. }
  25264. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  25265. end >>>= 0;
  25266. start >>>= 0;
  25267. if (end <= start) {
  25268. return ''
  25269. }
  25270. if (!encoding) encoding = 'utf8';
  25271. while (true) {
  25272. switch (encoding) {
  25273. case 'hex':
  25274. return hexSlice(this, start, end)
  25275. case 'utf8':
  25276. case 'utf-8':
  25277. return utf8Slice(this, start, end)
  25278. case 'ascii':
  25279. return asciiSlice(this, start, end)
  25280. case 'latin1':
  25281. case 'binary':
  25282. return latin1Slice(this, start, end)
  25283. case 'base64':
  25284. return base64Slice(this, start, end)
  25285. case 'ucs2':
  25286. case 'ucs-2':
  25287. case 'utf16le':
  25288. case 'utf-16le':
  25289. return utf16leSlice(this, start, end)
  25290. default:
  25291. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  25292. encoding = (encoding + '').toLowerCase();
  25293. loweredCase = true;
  25294. }
  25295. }
  25296. }
  25297. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  25298. // Buffer instances.
  25299. Buffer.prototype._isBuffer = true;
  25300. function swap (b, n, m) {
  25301. var i = b[n];
  25302. b[n] = b[m];
  25303. b[m] = i;
  25304. }
  25305. Buffer.prototype.swap16 = function swap16 () {
  25306. var len = this.length;
  25307. if (len % 2 !== 0) {
  25308. throw new RangeError('Buffer size must be a multiple of 16-bits')
  25309. }
  25310. for (var i = 0; i < len; i += 2) {
  25311. swap(this, i, i + 1);
  25312. }
  25313. return this
  25314. };
  25315. Buffer.prototype.swap32 = function swap32 () {
  25316. var len = this.length;
  25317. if (len % 4 !== 0) {
  25318. throw new RangeError('Buffer size must be a multiple of 32-bits')
  25319. }
  25320. for (var i = 0; i < len; i += 4) {
  25321. swap(this, i, i + 3);
  25322. swap(this, i + 1, i + 2);
  25323. }
  25324. return this
  25325. };
  25326. Buffer.prototype.swap64 = function swap64 () {
  25327. var len = this.length;
  25328. if (len % 8 !== 0) {
  25329. throw new RangeError('Buffer size must be a multiple of 64-bits')
  25330. }
  25331. for (var i = 0; i < len; i += 8) {
  25332. swap(this, i, i + 7);
  25333. swap(this, i + 1, i + 6);
  25334. swap(this, i + 2, i + 5);
  25335. swap(this, i + 3, i + 4);
  25336. }
  25337. return this
  25338. };
  25339. Buffer.prototype.toString = function toString () {
  25340. var length = this.length | 0;
  25341. if (length === 0) return ''
  25342. if (arguments.length === 0) return utf8Slice(this, 0, length)
  25343. return slowToString.apply(this, arguments)
  25344. };
  25345. Buffer.prototype.equals = function equals (b) {
  25346. if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
  25347. if (this === b) return true
  25348. return Buffer.compare(this, b) === 0
  25349. };
  25350. Buffer.prototype.inspect = function inspect () {
  25351. var str = '';
  25352. var max = INSPECT_MAX_BYTES;
  25353. if (this.length > 0) {
  25354. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
  25355. if (this.length > max) str += ' ... ';
  25356. }
  25357. return '<Buffer ' + str + '>'
  25358. };
  25359. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  25360. if (!internalIsBuffer(target)) {
  25361. throw new TypeError('Argument must be a Buffer')
  25362. }
  25363. if (start === undefined) {
  25364. start = 0;
  25365. }
  25366. if (end === undefined) {
  25367. end = target ? target.length : 0;
  25368. }
  25369. if (thisStart === undefined) {
  25370. thisStart = 0;
  25371. }
  25372. if (thisEnd === undefined) {
  25373. thisEnd = this.length;
  25374. }
  25375. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  25376. throw new RangeError('out of range index')
  25377. }
  25378. if (thisStart >= thisEnd && start >= end) {
  25379. return 0
  25380. }
  25381. if (thisStart >= thisEnd) {
  25382. return -1
  25383. }
  25384. if (start >= end) {
  25385. return 1
  25386. }
  25387. start >>>= 0;
  25388. end >>>= 0;
  25389. thisStart >>>= 0;
  25390. thisEnd >>>= 0;
  25391. if (this === target) return 0
  25392. var x = thisEnd - thisStart;
  25393. var y = end - start;
  25394. var len = Math.min(x, y);
  25395. var thisCopy = this.slice(thisStart, thisEnd);
  25396. var targetCopy = target.slice(start, end);
  25397. for (var i = 0; i < len; ++i) {
  25398. if (thisCopy[i] !== targetCopy[i]) {
  25399. x = thisCopy[i];
  25400. y = targetCopy[i];
  25401. break
  25402. }
  25403. }
  25404. if (x < y) return -1
  25405. if (y < x) return 1
  25406. return 0
  25407. };
  25408. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  25409. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  25410. //
  25411. // Arguments:
  25412. // - buffer - a Buffer to search
  25413. // - val - a string, Buffer, or number
  25414. // - byteOffset - an index into `buffer`; will be clamped to an int32
  25415. // - encoding - an optional encoding, relevant is val is a string
  25416. // - dir - true for indexOf, false for lastIndexOf
  25417. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  25418. // Empty buffer means no match
  25419. if (buffer.length === 0) return -1
  25420. // Normalize byteOffset
  25421. if (typeof byteOffset === 'string') {
  25422. encoding = byteOffset;
  25423. byteOffset = 0;
  25424. } else if (byteOffset > 0x7fffffff) {
  25425. byteOffset = 0x7fffffff;
  25426. } else if (byteOffset < -0x80000000) {
  25427. byteOffset = -0x80000000;
  25428. }
  25429. byteOffset = +byteOffset; // Coerce to Number.
  25430. if (isNaN(byteOffset)) {
  25431. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  25432. byteOffset = dir ? 0 : (buffer.length - 1);
  25433. }
  25434. // Normalize byteOffset: negative offsets start from the end of the buffer
  25435. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  25436. if (byteOffset >= buffer.length) {
  25437. if (dir) return -1
  25438. else byteOffset = buffer.length - 1;
  25439. } else if (byteOffset < 0) {
  25440. if (dir) byteOffset = 0;
  25441. else return -1
  25442. }
  25443. // Normalize val
  25444. if (typeof val === 'string') {
  25445. val = Buffer.from(val, encoding);
  25446. }
  25447. // Finally, search either indexOf (if dir is true) or lastIndexOf
  25448. if (internalIsBuffer(val)) {
  25449. // Special case: looking for empty string/buffer always fails
  25450. if (val.length === 0) {
  25451. return -1
  25452. }
  25453. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  25454. } else if (typeof val === 'number') {
  25455. val = val & 0xFF; // Search for a byte value [0-255]
  25456. if (Buffer.TYPED_ARRAY_SUPPORT &&
  25457. typeof Uint8Array.prototype.indexOf === 'function') {
  25458. if (dir) {
  25459. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  25460. } else {
  25461. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  25462. }
  25463. }
  25464. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  25465. }
  25466. throw new TypeError('val must be string, number or Buffer')
  25467. }
  25468. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  25469. var indexSize = 1;
  25470. var arrLength = arr.length;
  25471. var valLength = val.length;
  25472. if (encoding !== undefined) {
  25473. encoding = String(encoding).toLowerCase();
  25474. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  25475. encoding === 'utf16le' || encoding === 'utf-16le') {
  25476. if (arr.length < 2 || val.length < 2) {
  25477. return -1
  25478. }
  25479. indexSize = 2;
  25480. arrLength /= 2;
  25481. valLength /= 2;
  25482. byteOffset /= 2;
  25483. }
  25484. }
  25485. function read (buf, i) {
  25486. if (indexSize === 1) {
  25487. return buf[i]
  25488. } else {
  25489. return buf.readUInt16BE(i * indexSize)
  25490. }
  25491. }
  25492. var i;
  25493. if (dir) {
  25494. var foundIndex = -1;
  25495. for (i = byteOffset; i < arrLength; i++) {
  25496. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  25497. if (foundIndex === -1) foundIndex = i;
  25498. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  25499. } else {
  25500. if (foundIndex !== -1) i -= i - foundIndex;
  25501. foundIndex = -1;
  25502. }
  25503. }
  25504. } else {
  25505. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  25506. for (i = byteOffset; i >= 0; i--) {
  25507. var found = true;
  25508. for (var j = 0; j < valLength; j++) {
  25509. if (read(arr, i + j) !== read(val, j)) {
  25510. found = false;
  25511. break
  25512. }
  25513. }
  25514. if (found) return i
  25515. }
  25516. }
  25517. return -1
  25518. }
  25519. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  25520. return this.indexOf(val, byteOffset, encoding) !== -1
  25521. };
  25522. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  25523. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  25524. };
  25525. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  25526. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  25527. };
  25528. function hexWrite (buf, string, offset, length) {
  25529. offset = Number(offset) || 0;
  25530. var remaining = buf.length - offset;
  25531. if (!length) {
  25532. length = remaining;
  25533. } else {
  25534. length = Number(length);
  25535. if (length > remaining) {
  25536. length = remaining;
  25537. }
  25538. }
  25539. // must be an even number of digits
  25540. var strLen = string.length;
  25541. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  25542. if (length > strLen / 2) {
  25543. length = strLen / 2;
  25544. }
  25545. for (var i = 0; i < length; ++i) {
  25546. var parsed = parseInt(string.substr(i * 2, 2), 16);
  25547. if (isNaN(parsed)) return i
  25548. buf[offset + i] = parsed;
  25549. }
  25550. return i
  25551. }
  25552. function utf8Write (buf, string, offset, length) {
  25553. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  25554. }
  25555. function asciiWrite (buf, string, offset, length) {
  25556. return blitBuffer(asciiToBytes(string), buf, offset, length)
  25557. }
  25558. function latin1Write (buf, string, offset, length) {
  25559. return asciiWrite(buf, string, offset, length)
  25560. }
  25561. function base64Write (buf, string, offset, length) {
  25562. return blitBuffer(base64ToBytes(string), buf, offset, length)
  25563. }
  25564. function ucs2Write (buf, string, offset, length) {
  25565. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  25566. }
  25567. Buffer.prototype.write = function write (string, offset, length, encoding) {
  25568. // Buffer#write(string)
  25569. if (offset === undefined) {
  25570. encoding = 'utf8';
  25571. length = this.length;
  25572. offset = 0;
  25573. // Buffer#write(string, encoding)
  25574. } else if (length === undefined && typeof offset === 'string') {
  25575. encoding = offset;
  25576. length = this.length;
  25577. offset = 0;
  25578. // Buffer#write(string, offset[, length][, encoding])
  25579. } else if (isFinite(offset)) {
  25580. offset = offset | 0;
  25581. if (isFinite(length)) {
  25582. length = length | 0;
  25583. if (encoding === undefined) encoding = 'utf8';
  25584. } else {
  25585. encoding = length;
  25586. length = undefined;
  25587. }
  25588. // legacy write(string, encoding, offset, length) - remove in v0.13
  25589. } else {
  25590. throw new Error(
  25591. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  25592. )
  25593. }
  25594. var remaining = this.length - offset;
  25595. if (length === undefined || length > remaining) length = remaining;
  25596. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  25597. throw new RangeError('Attempt to write outside buffer bounds')
  25598. }
  25599. if (!encoding) encoding = 'utf8';
  25600. var loweredCase = false;
  25601. for (;;) {
  25602. switch (encoding) {
  25603. case 'hex':
  25604. return hexWrite(this, string, offset, length)
  25605. case 'utf8':
  25606. case 'utf-8':
  25607. return utf8Write(this, string, offset, length)
  25608. case 'ascii':
  25609. return asciiWrite(this, string, offset, length)
  25610. case 'latin1':
  25611. case 'binary':
  25612. return latin1Write(this, string, offset, length)
  25613. case 'base64':
  25614. // Warning: maxLength not taken into account in base64Write
  25615. return base64Write(this, string, offset, length)
  25616. case 'ucs2':
  25617. case 'ucs-2':
  25618. case 'utf16le':
  25619. case 'utf-16le':
  25620. return ucs2Write(this, string, offset, length)
  25621. default:
  25622. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  25623. encoding = ('' + encoding).toLowerCase();
  25624. loweredCase = true;
  25625. }
  25626. }
  25627. };
  25628. Buffer.prototype.toJSON = function toJSON () {
  25629. return {
  25630. type: 'Buffer',
  25631. data: Array.prototype.slice.call(this._arr || this, 0)
  25632. }
  25633. };
  25634. function base64Slice (buf, start, end) {
  25635. if (start === 0 && end === buf.length) {
  25636. return fromByteArray(buf)
  25637. } else {
  25638. return fromByteArray(buf.slice(start, end))
  25639. }
  25640. }
  25641. function utf8Slice (buf, start, end) {
  25642. end = Math.min(buf.length, end);
  25643. var res = [];
  25644. var i = start;
  25645. while (i < end) {
  25646. var firstByte = buf[i];
  25647. var codePoint = null;
  25648. var bytesPerSequence = (firstByte > 0xEF) ? 4
  25649. : (firstByte > 0xDF) ? 3
  25650. : (firstByte > 0xBF) ? 2
  25651. : 1;
  25652. if (i + bytesPerSequence <= end) {
  25653. var secondByte, thirdByte, fourthByte, tempCodePoint;
  25654. switch (bytesPerSequence) {
  25655. case 1:
  25656. if (firstByte < 0x80) {
  25657. codePoint = firstByte;
  25658. }
  25659. break
  25660. case 2:
  25661. secondByte = buf[i + 1];
  25662. if ((secondByte & 0xC0) === 0x80) {
  25663. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
  25664. if (tempCodePoint > 0x7F) {
  25665. codePoint = tempCodePoint;
  25666. }
  25667. }
  25668. break
  25669. case 3:
  25670. secondByte = buf[i + 1];
  25671. thirdByte = buf[i + 2];
  25672. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  25673. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
  25674. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  25675. codePoint = tempCodePoint;
  25676. }
  25677. }
  25678. break
  25679. case 4:
  25680. secondByte = buf[i + 1];
  25681. thirdByte = buf[i + 2];
  25682. fourthByte = buf[i + 3];
  25683. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  25684. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
  25685. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  25686. codePoint = tempCodePoint;
  25687. }
  25688. }
  25689. }
  25690. }
  25691. if (codePoint === null) {
  25692. // we did not generate a valid codePoint so insert a
  25693. // replacement char (U+FFFD) and advance only 1 byte
  25694. codePoint = 0xFFFD;
  25695. bytesPerSequence = 1;
  25696. } else if (codePoint > 0xFFFF) {
  25697. // encode to utf16 (surrogate pair dance)
  25698. codePoint -= 0x10000;
  25699. res.push(codePoint >>> 10 & 0x3FF | 0xD800);
  25700. codePoint = 0xDC00 | codePoint & 0x3FF;
  25701. }
  25702. res.push(codePoint);
  25703. i += bytesPerSequence;
  25704. }
  25705. return decodeCodePointsArray(res)
  25706. }
  25707. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  25708. // the lowest limit is Chrome, with 0x10000 args.
  25709. // We go 1 magnitude less, for safety
  25710. var MAX_ARGUMENTS_LENGTH = 0x1000;
  25711. function decodeCodePointsArray (codePoints) {
  25712. var len = codePoints.length;
  25713. if (len <= MAX_ARGUMENTS_LENGTH) {
  25714. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  25715. }
  25716. // Decode in chunks to avoid "call stack size exceeded".
  25717. var res = '';
  25718. var i = 0;
  25719. while (i < len) {
  25720. res += String.fromCharCode.apply(
  25721. String,
  25722. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  25723. );
  25724. }
  25725. return res
  25726. }
  25727. function asciiSlice (buf, start, end) {
  25728. var ret = '';
  25729. end = Math.min(buf.length, end);
  25730. for (var i = start; i < end; ++i) {
  25731. ret += String.fromCharCode(buf[i] & 0x7F);
  25732. }
  25733. return ret
  25734. }
  25735. function latin1Slice (buf, start, end) {
  25736. var ret = '';
  25737. end = Math.min(buf.length, end);
  25738. for (var i = start; i < end; ++i) {
  25739. ret += String.fromCharCode(buf[i]);
  25740. }
  25741. return ret
  25742. }
  25743. function hexSlice (buf, start, end) {
  25744. var len = buf.length;
  25745. if (!start || start < 0) start = 0;
  25746. if (!end || end < 0 || end > len) end = len;
  25747. var out = '';
  25748. for (var i = start; i < end; ++i) {
  25749. out += toHex(buf[i]);
  25750. }
  25751. return out
  25752. }
  25753. function utf16leSlice (buf, start, end) {
  25754. var bytes = buf.slice(start, end);
  25755. var res = '';
  25756. for (var i = 0; i < bytes.length; i += 2) {
  25757. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  25758. }
  25759. return res
  25760. }
  25761. Buffer.prototype.slice = function slice (start, end) {
  25762. var len = this.length;
  25763. start = ~~start;
  25764. end = end === undefined ? len : ~~end;
  25765. if (start < 0) {
  25766. start += len;
  25767. if (start < 0) start = 0;
  25768. } else if (start > len) {
  25769. start = len;
  25770. }
  25771. if (end < 0) {
  25772. end += len;
  25773. if (end < 0) end = 0;
  25774. } else if (end > len) {
  25775. end = len;
  25776. }
  25777. if (end < start) end = start;
  25778. var newBuf;
  25779. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25780. newBuf = this.subarray(start, end);
  25781. newBuf.__proto__ = Buffer.prototype;
  25782. } else {
  25783. var sliceLen = end - start;
  25784. newBuf = new Buffer(sliceLen, undefined);
  25785. for (var i = 0; i < sliceLen; ++i) {
  25786. newBuf[i] = this[i + start];
  25787. }
  25788. }
  25789. return newBuf
  25790. };
  25791. /*
  25792. * Need to make sure that buffer isn't trying to write out of bounds.
  25793. */
  25794. function checkOffset (offset, ext, length) {
  25795. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  25796. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  25797. }
  25798. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  25799. offset = offset | 0;
  25800. byteLength = byteLength | 0;
  25801. if (!noAssert) checkOffset(offset, byteLength, this.length);
  25802. var val = this[offset];
  25803. var mul = 1;
  25804. var i = 0;
  25805. while (++i < byteLength && (mul *= 0x100)) {
  25806. val += this[offset + i] * mul;
  25807. }
  25808. return val
  25809. };
  25810. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  25811. offset = offset | 0;
  25812. byteLength = byteLength | 0;
  25813. if (!noAssert) {
  25814. checkOffset(offset, byteLength, this.length);
  25815. }
  25816. var val = this[offset + --byteLength];
  25817. var mul = 1;
  25818. while (byteLength > 0 && (mul *= 0x100)) {
  25819. val += this[offset + --byteLength] * mul;
  25820. }
  25821. return val
  25822. };
  25823. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  25824. if (!noAssert) checkOffset(offset, 1, this.length);
  25825. return this[offset]
  25826. };
  25827. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  25828. if (!noAssert) checkOffset(offset, 2, this.length);
  25829. return this[offset] | (this[offset + 1] << 8)
  25830. };
  25831. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  25832. if (!noAssert) checkOffset(offset, 2, this.length);
  25833. return (this[offset] << 8) | this[offset + 1]
  25834. };
  25835. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  25836. if (!noAssert) checkOffset(offset, 4, this.length);
  25837. return ((this[offset]) |
  25838. (this[offset + 1] << 8) |
  25839. (this[offset + 2] << 16)) +
  25840. (this[offset + 3] * 0x1000000)
  25841. };
  25842. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  25843. if (!noAssert) checkOffset(offset, 4, this.length);
  25844. return (this[offset] * 0x1000000) +
  25845. ((this[offset + 1] << 16) |
  25846. (this[offset + 2] << 8) |
  25847. this[offset + 3])
  25848. };
  25849. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  25850. offset = offset | 0;
  25851. byteLength = byteLength | 0;
  25852. if (!noAssert) checkOffset(offset, byteLength, this.length);
  25853. var val = this[offset];
  25854. var mul = 1;
  25855. var i = 0;
  25856. while (++i < byteLength && (mul *= 0x100)) {
  25857. val += this[offset + i] * mul;
  25858. }
  25859. mul *= 0x80;
  25860. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  25861. return val
  25862. };
  25863. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  25864. offset = offset | 0;
  25865. byteLength = byteLength | 0;
  25866. if (!noAssert) checkOffset(offset, byteLength, this.length);
  25867. var i = byteLength;
  25868. var mul = 1;
  25869. var val = this[offset + --i];
  25870. while (i > 0 && (mul *= 0x100)) {
  25871. val += this[offset + --i] * mul;
  25872. }
  25873. mul *= 0x80;
  25874. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  25875. return val
  25876. };
  25877. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  25878. if (!noAssert) checkOffset(offset, 1, this.length);
  25879. if (!(this[offset] & 0x80)) return (this[offset])
  25880. return ((0xff - this[offset] + 1) * -1)
  25881. };
  25882. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  25883. if (!noAssert) checkOffset(offset, 2, this.length);
  25884. var val = this[offset] | (this[offset + 1] << 8);
  25885. return (val & 0x8000) ? val | 0xFFFF0000 : val
  25886. };
  25887. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  25888. if (!noAssert) checkOffset(offset, 2, this.length);
  25889. var val = this[offset + 1] | (this[offset] << 8);
  25890. return (val & 0x8000) ? val | 0xFFFF0000 : val
  25891. };
  25892. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  25893. if (!noAssert) checkOffset(offset, 4, this.length);
  25894. return (this[offset]) |
  25895. (this[offset + 1] << 8) |
  25896. (this[offset + 2] << 16) |
  25897. (this[offset + 3] << 24)
  25898. };
  25899. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  25900. if (!noAssert) checkOffset(offset, 4, this.length);
  25901. return (this[offset] << 24) |
  25902. (this[offset + 1] << 16) |
  25903. (this[offset + 2] << 8) |
  25904. (this[offset + 3])
  25905. };
  25906. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  25907. if (!noAssert) checkOffset(offset, 4, this.length);
  25908. return read(this, offset, true, 23, 4)
  25909. };
  25910. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  25911. if (!noAssert) checkOffset(offset, 4, this.length);
  25912. return read(this, offset, false, 23, 4)
  25913. };
  25914. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  25915. if (!noAssert) checkOffset(offset, 8, this.length);
  25916. return read(this, offset, true, 52, 8)
  25917. };
  25918. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  25919. if (!noAssert) checkOffset(offset, 8, this.length);
  25920. return read(this, offset, false, 52, 8)
  25921. };
  25922. function checkInt (buf, value, offset, ext, max, min) {
  25923. if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  25924. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  25925. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  25926. }
  25927. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  25928. value = +value;
  25929. offset = offset | 0;
  25930. byteLength = byteLength | 0;
  25931. if (!noAssert) {
  25932. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  25933. checkInt(this, value, offset, byteLength, maxBytes, 0);
  25934. }
  25935. var mul = 1;
  25936. var i = 0;
  25937. this[offset] = value & 0xFF;
  25938. while (++i < byteLength && (mul *= 0x100)) {
  25939. this[offset + i] = (value / mul) & 0xFF;
  25940. }
  25941. return offset + byteLength
  25942. };
  25943. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  25944. value = +value;
  25945. offset = offset | 0;
  25946. byteLength = byteLength | 0;
  25947. if (!noAssert) {
  25948. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  25949. checkInt(this, value, offset, byteLength, maxBytes, 0);
  25950. }
  25951. var i = byteLength - 1;
  25952. var mul = 1;
  25953. this[offset + i] = value & 0xFF;
  25954. while (--i >= 0 && (mul *= 0x100)) {
  25955. this[offset + i] = (value / mul) & 0xFF;
  25956. }
  25957. return offset + byteLength
  25958. };
  25959. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  25960. value = +value;
  25961. offset = offset | 0;
  25962. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  25963. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  25964. this[offset] = (value & 0xff);
  25965. return offset + 1
  25966. };
  25967. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  25968. if (value < 0) value = 0xffff + value + 1;
  25969. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  25970. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  25971. (littleEndian ? i : 1 - i) * 8;
  25972. }
  25973. }
  25974. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  25975. value = +value;
  25976. offset = offset | 0;
  25977. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  25978. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25979. this[offset] = (value & 0xff);
  25980. this[offset + 1] = (value >>> 8);
  25981. } else {
  25982. objectWriteUInt16(this, value, offset, true);
  25983. }
  25984. return offset + 2
  25985. };
  25986. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  25987. value = +value;
  25988. offset = offset | 0;
  25989. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  25990. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25991. this[offset] = (value >>> 8);
  25992. this[offset + 1] = (value & 0xff);
  25993. } else {
  25994. objectWriteUInt16(this, value, offset, false);
  25995. }
  25996. return offset + 2
  25997. };
  25998. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  25999. if (value < 0) value = 0xffffffff + value + 1;
  26000. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  26001. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
  26002. }
  26003. }
  26004. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  26005. value = +value;
  26006. offset = offset | 0;
  26007. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  26008. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26009. this[offset + 3] = (value >>> 24);
  26010. this[offset + 2] = (value >>> 16);
  26011. this[offset + 1] = (value >>> 8);
  26012. this[offset] = (value & 0xff);
  26013. } else {
  26014. objectWriteUInt32(this, value, offset, true);
  26015. }
  26016. return offset + 4
  26017. };
  26018. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  26019. value = +value;
  26020. offset = offset | 0;
  26021. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  26022. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26023. this[offset] = (value >>> 24);
  26024. this[offset + 1] = (value >>> 16);
  26025. this[offset + 2] = (value >>> 8);
  26026. this[offset + 3] = (value & 0xff);
  26027. } else {
  26028. objectWriteUInt32(this, value, offset, false);
  26029. }
  26030. return offset + 4
  26031. };
  26032. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  26033. value = +value;
  26034. offset = offset | 0;
  26035. if (!noAssert) {
  26036. var limit = Math.pow(2, 8 * byteLength - 1);
  26037. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  26038. }
  26039. var i = 0;
  26040. var mul = 1;
  26041. var sub = 0;
  26042. this[offset] = value & 0xFF;
  26043. while (++i < byteLength && (mul *= 0x100)) {
  26044. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  26045. sub = 1;
  26046. }
  26047. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  26048. }
  26049. return offset + byteLength
  26050. };
  26051. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  26052. value = +value;
  26053. offset = offset | 0;
  26054. if (!noAssert) {
  26055. var limit = Math.pow(2, 8 * byteLength - 1);
  26056. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  26057. }
  26058. var i = byteLength - 1;
  26059. var mul = 1;
  26060. var sub = 0;
  26061. this[offset + i] = value & 0xFF;
  26062. while (--i >= 0 && (mul *= 0x100)) {
  26063. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  26064. sub = 1;
  26065. }
  26066. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  26067. }
  26068. return offset + byteLength
  26069. };
  26070. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  26071. value = +value;
  26072. offset = offset | 0;
  26073. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
  26074. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  26075. if (value < 0) value = 0xff + value + 1;
  26076. this[offset] = (value & 0xff);
  26077. return offset + 1
  26078. };
  26079. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  26080. value = +value;
  26081. offset = offset | 0;
  26082. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  26083. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26084. this[offset] = (value & 0xff);
  26085. this[offset + 1] = (value >>> 8);
  26086. } else {
  26087. objectWriteUInt16(this, value, offset, true);
  26088. }
  26089. return offset + 2
  26090. };
  26091. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  26092. value = +value;
  26093. offset = offset | 0;
  26094. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  26095. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26096. this[offset] = (value >>> 8);
  26097. this[offset + 1] = (value & 0xff);
  26098. } else {
  26099. objectWriteUInt16(this, value, offset, false);
  26100. }
  26101. return offset + 2
  26102. };
  26103. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  26104. value = +value;
  26105. offset = offset | 0;
  26106. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  26107. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26108. this[offset] = (value & 0xff);
  26109. this[offset + 1] = (value >>> 8);
  26110. this[offset + 2] = (value >>> 16);
  26111. this[offset + 3] = (value >>> 24);
  26112. } else {
  26113. objectWriteUInt32(this, value, offset, true);
  26114. }
  26115. return offset + 4
  26116. };
  26117. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  26118. value = +value;
  26119. offset = offset | 0;
  26120. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  26121. if (value < 0) value = 0xffffffff + value + 1;
  26122. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26123. this[offset] = (value >>> 24);
  26124. this[offset + 1] = (value >>> 16);
  26125. this[offset + 2] = (value >>> 8);
  26126. this[offset + 3] = (value & 0xff);
  26127. } else {
  26128. objectWriteUInt32(this, value, offset, false);
  26129. }
  26130. return offset + 4
  26131. };
  26132. function checkIEEE754 (buf, value, offset, ext, max, min) {
  26133. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  26134. if (offset < 0) throw new RangeError('Index out of range')
  26135. }
  26136. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  26137. if (!noAssert) {
  26138. checkIEEE754(buf, value, offset, 4);
  26139. }
  26140. write(buf, value, offset, littleEndian, 23, 4);
  26141. return offset + 4
  26142. }
  26143. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  26144. return writeFloat(this, value, offset, true, noAssert)
  26145. };
  26146. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  26147. return writeFloat(this, value, offset, false, noAssert)
  26148. };
  26149. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  26150. if (!noAssert) {
  26151. checkIEEE754(buf, value, offset, 8);
  26152. }
  26153. write(buf, value, offset, littleEndian, 52, 8);
  26154. return offset + 8
  26155. }
  26156. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  26157. return writeDouble(this, value, offset, true, noAssert)
  26158. };
  26159. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  26160. return writeDouble(this, value, offset, false, noAssert)
  26161. };
  26162. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  26163. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  26164. if (!start) start = 0;
  26165. if (!end && end !== 0) end = this.length;
  26166. if (targetStart >= target.length) targetStart = target.length;
  26167. if (!targetStart) targetStart = 0;
  26168. if (end > 0 && end < start) end = start;
  26169. // Copy 0 bytes; we're done
  26170. if (end === start) return 0
  26171. if (target.length === 0 || this.length === 0) return 0
  26172. // Fatal error conditions
  26173. if (targetStart < 0) {
  26174. throw new RangeError('targetStart out of bounds')
  26175. }
  26176. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  26177. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  26178. // Are we oob?
  26179. if (end > this.length) end = this.length;
  26180. if (target.length - targetStart < end - start) {
  26181. end = target.length - targetStart + start;
  26182. }
  26183. var len = end - start;
  26184. var i;
  26185. if (this === target && start < targetStart && targetStart < end) {
  26186. // descending copy from end
  26187. for (i = len - 1; i >= 0; --i) {
  26188. target[i + targetStart] = this[i + start];
  26189. }
  26190. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  26191. // ascending copy from start
  26192. for (i = 0; i < len; ++i) {
  26193. target[i + targetStart] = this[i + start];
  26194. }
  26195. } else {
  26196. Uint8Array.prototype.set.call(
  26197. target,
  26198. this.subarray(start, start + len),
  26199. targetStart
  26200. );
  26201. }
  26202. return len
  26203. };
  26204. // Usage:
  26205. // buffer.fill(number[, offset[, end]])
  26206. // buffer.fill(buffer[, offset[, end]])
  26207. // buffer.fill(string[, offset[, end]][, encoding])
  26208. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  26209. // Handle string cases:
  26210. if (typeof val === 'string') {
  26211. if (typeof start === 'string') {
  26212. encoding = start;
  26213. start = 0;
  26214. end = this.length;
  26215. } else if (typeof end === 'string') {
  26216. encoding = end;
  26217. end = this.length;
  26218. }
  26219. if (val.length === 1) {
  26220. var code = val.charCodeAt(0);
  26221. if (code < 256) {
  26222. val = code;
  26223. }
  26224. }
  26225. if (encoding !== undefined && typeof encoding !== 'string') {
  26226. throw new TypeError('encoding must be a string')
  26227. }
  26228. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  26229. throw new TypeError('Unknown encoding: ' + encoding)
  26230. }
  26231. } else if (typeof val === 'number') {
  26232. val = val & 255;
  26233. }
  26234. // Invalid ranges are not set to a default, so can range check early.
  26235. if (start < 0 || this.length < start || this.length < end) {
  26236. throw new RangeError('Out of range index')
  26237. }
  26238. if (end <= start) {
  26239. return this
  26240. }
  26241. start = start >>> 0;
  26242. end = end === undefined ? this.length : end >>> 0;
  26243. if (!val) val = 0;
  26244. var i;
  26245. if (typeof val === 'number') {
  26246. for (i = start; i < end; ++i) {
  26247. this[i] = val;
  26248. }
  26249. } else {
  26250. var bytes = internalIsBuffer(val)
  26251. ? val
  26252. : utf8ToBytes(new Buffer(val, encoding).toString());
  26253. var len = bytes.length;
  26254. for (i = 0; i < end - start; ++i) {
  26255. this[i + start] = bytes[i % len];
  26256. }
  26257. }
  26258. return this
  26259. };
  26260. // HELPER FUNCTIONS
  26261. // ================
  26262. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
  26263. function base64clean (str) {
  26264. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  26265. str = stringtrim(str).replace(INVALID_BASE64_RE, '');
  26266. // Node converts strings with length < 2 to ''
  26267. if (str.length < 2) return ''
  26268. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  26269. while (str.length % 4 !== 0) {
  26270. str = str + '=';
  26271. }
  26272. return str
  26273. }
  26274. function stringtrim (str) {
  26275. if (str.trim) return str.trim()
  26276. return str.replace(/^\s+|\s+$/g, '')
  26277. }
  26278. function toHex (n) {
  26279. if (n < 16) return '0' + n.toString(16)
  26280. return n.toString(16)
  26281. }
  26282. function utf8ToBytes (string, units) {
  26283. units = units || Infinity;
  26284. var codePoint;
  26285. var length = string.length;
  26286. var leadSurrogate = null;
  26287. var bytes = [];
  26288. for (var i = 0; i < length; ++i) {
  26289. codePoint = string.charCodeAt(i);
  26290. // is surrogate component
  26291. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  26292. // last char was a lead
  26293. if (!leadSurrogate) {
  26294. // no lead yet
  26295. if (codePoint > 0xDBFF) {
  26296. // unexpected trail
  26297. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  26298. continue
  26299. } else if (i + 1 === length) {
  26300. // unpaired lead
  26301. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  26302. continue
  26303. }
  26304. // valid lead
  26305. leadSurrogate = codePoint;
  26306. continue
  26307. }
  26308. // 2 leads in a row
  26309. if (codePoint < 0xDC00) {
  26310. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  26311. leadSurrogate = codePoint;
  26312. continue
  26313. }
  26314. // valid surrogate pair
  26315. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  26316. } else if (leadSurrogate) {
  26317. // valid bmp char, but last char was a lead
  26318. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  26319. }
  26320. leadSurrogate = null;
  26321. // encode utf8
  26322. if (codePoint < 0x80) {
  26323. if ((units -= 1) < 0) break
  26324. bytes.push(codePoint);
  26325. } else if (codePoint < 0x800) {
  26326. if ((units -= 2) < 0) break
  26327. bytes.push(
  26328. codePoint >> 0x6 | 0xC0,
  26329. codePoint & 0x3F | 0x80
  26330. );
  26331. } else if (codePoint < 0x10000) {
  26332. if ((units -= 3) < 0) break
  26333. bytes.push(
  26334. codePoint >> 0xC | 0xE0,
  26335. codePoint >> 0x6 & 0x3F | 0x80,
  26336. codePoint & 0x3F | 0x80
  26337. );
  26338. } else if (codePoint < 0x110000) {
  26339. if ((units -= 4) < 0) break
  26340. bytes.push(
  26341. codePoint >> 0x12 | 0xF0,
  26342. codePoint >> 0xC & 0x3F | 0x80,
  26343. codePoint >> 0x6 & 0x3F | 0x80,
  26344. codePoint & 0x3F | 0x80
  26345. );
  26346. } else {
  26347. throw new Error('Invalid code point')
  26348. }
  26349. }
  26350. return bytes
  26351. }
  26352. function asciiToBytes (str) {
  26353. var byteArray = [];
  26354. for (var i = 0; i < str.length; ++i) {
  26355. // Node's code seems to be doing this and not & 0x7F..
  26356. byteArray.push(str.charCodeAt(i) & 0xFF);
  26357. }
  26358. return byteArray
  26359. }
  26360. function utf16leToBytes (str, units) {
  26361. var c, hi, lo;
  26362. var byteArray = [];
  26363. for (var i = 0; i < str.length; ++i) {
  26364. if ((units -= 2) < 0) break
  26365. c = str.charCodeAt(i);
  26366. hi = c >> 8;
  26367. lo = c % 256;
  26368. byteArray.push(lo);
  26369. byteArray.push(hi);
  26370. }
  26371. return byteArray
  26372. }
  26373. function base64ToBytes (str) {
  26374. return toByteArray(base64clean(str))
  26375. }
  26376. function blitBuffer (src, dst, offset, length) {
  26377. for (var i = 0; i < length; ++i) {
  26378. if ((i + offset >= dst.length) || (i >= src.length)) break
  26379. dst[i + offset] = src[i];
  26380. }
  26381. return i
  26382. }
  26383. function isnan (val) {
  26384. return val !== val // eslint-disable-line no-self-compare
  26385. }
  26386. // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
  26387. // The _isBuffer check is for Safari 5-7 support, because it's missing
  26388. // Object.prototype.constructor. Remove this eventually
  26389. function isBuffer$1(obj) {
  26390. return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
  26391. }
  26392. function isFastBuffer (obj) {
  26393. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  26394. }
  26395. // For Node v0.10 support. Remove this eventually.
  26396. function isSlowBuffer (obj) {
  26397. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
  26398. }
  26399. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  26400. function encode$1(decoded) {
  26401. var sourceFileIndex = 0; // second field
  26402. var sourceCodeLine = 0; // third field
  26403. var sourceCodeColumn = 0; // fourth field
  26404. var nameIndex = 0; // fifth field
  26405. var mappings = '';
  26406. for (var i = 0; i < decoded.length; i++) {
  26407. var line = decoded[i];
  26408. if (i > 0)
  26409. mappings += ';';
  26410. if (line.length === 0)
  26411. continue;
  26412. var generatedCodeColumn = 0; // first field
  26413. var lineMappings = [];
  26414. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  26415. var segment = line_1[_i];
  26416. var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
  26417. generatedCodeColumn = segment[0];
  26418. if (segment.length > 1) {
  26419. segmentMappings +=
  26420. encodeInteger(segment[1] - sourceFileIndex) +
  26421. encodeInteger(segment[2] - sourceCodeLine) +
  26422. encodeInteger(segment[3] - sourceCodeColumn);
  26423. sourceFileIndex = segment[1];
  26424. sourceCodeLine = segment[2];
  26425. sourceCodeColumn = segment[3];
  26426. }
  26427. if (segment.length === 5) {
  26428. segmentMappings += encodeInteger(segment[4] - nameIndex);
  26429. nameIndex = segment[4];
  26430. }
  26431. lineMappings.push(segmentMappings);
  26432. }
  26433. mappings += lineMappings.join(',');
  26434. }
  26435. return mappings;
  26436. }
  26437. function encodeInteger(num) {
  26438. var result = '';
  26439. num = num < 0 ? (-num << 1) | 1 : num << 1;
  26440. do {
  26441. var clamped = num & 31;
  26442. num >>>= 5;
  26443. if (num > 0) {
  26444. clamped |= 32;
  26445. }
  26446. result += chars[clamped];
  26447. } while (num > 0);
  26448. return result;
  26449. }
  26450. var BitSet = function BitSet(arg) {
  26451. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  26452. };
  26453. BitSet.prototype.add = function add (n) {
  26454. this.bits[n >> 5] |= 1 << (n & 31);
  26455. };
  26456. BitSet.prototype.has = function has (n) {
  26457. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  26458. };
  26459. var Chunk = function Chunk(start, end, content) {
  26460. this.start = start;
  26461. this.end = end;
  26462. this.original = content;
  26463. this.intro = '';
  26464. this.outro = '';
  26465. this.content = content;
  26466. this.storeName = false;
  26467. this.edited = false;
  26468. // we make these non-enumerable, for sanity while debugging
  26469. Object.defineProperties(this, {
  26470. previous: { writable: true, value: null },
  26471. next: { writable: true, value: null }
  26472. });
  26473. };
  26474. Chunk.prototype.appendLeft = function appendLeft (content) {
  26475. this.outro += content;
  26476. };
  26477. Chunk.prototype.appendRight = function appendRight (content) {
  26478. this.intro = this.intro + content;
  26479. };
  26480. Chunk.prototype.clone = function clone () {
  26481. var chunk = new Chunk(this.start, this.end, this.original);
  26482. chunk.intro = this.intro;
  26483. chunk.outro = this.outro;
  26484. chunk.content = this.content;
  26485. chunk.storeName = this.storeName;
  26486. chunk.edited = this.edited;
  26487. return chunk;
  26488. };
  26489. Chunk.prototype.contains = function contains (index) {
  26490. return this.start < index && index < this.end;
  26491. };
  26492. Chunk.prototype.eachNext = function eachNext (fn) {
  26493. var chunk = this;
  26494. while (chunk) {
  26495. fn(chunk);
  26496. chunk = chunk.next;
  26497. }
  26498. };
  26499. Chunk.prototype.eachPrevious = function eachPrevious (fn) {
  26500. var chunk = this;
  26501. while (chunk) {
  26502. fn(chunk);
  26503. chunk = chunk.previous;
  26504. }
  26505. };
  26506. Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
  26507. this.content = content;
  26508. if (!contentOnly) {
  26509. this.intro = '';
  26510. this.outro = '';
  26511. }
  26512. this.storeName = storeName;
  26513. this.edited = true;
  26514. return this;
  26515. };
  26516. Chunk.prototype.prependLeft = function prependLeft (content) {
  26517. this.outro = content + this.outro;
  26518. };
  26519. Chunk.prototype.prependRight = function prependRight (content) {
  26520. this.intro = content + this.intro;
  26521. };
  26522. Chunk.prototype.split = function split (index) {
  26523. var sliceIndex = index - this.start;
  26524. var originalBefore = this.original.slice(0, sliceIndex);
  26525. var originalAfter = this.original.slice(sliceIndex);
  26526. this.original = originalBefore;
  26527. var newChunk = new Chunk(index, this.end, originalAfter);
  26528. newChunk.outro = this.outro;
  26529. this.outro = '';
  26530. this.end = index;
  26531. if (this.edited) {
  26532. // TODO is this block necessary?...
  26533. newChunk.edit('', false);
  26534. this.content = '';
  26535. } else {
  26536. this.content = originalBefore;
  26537. }
  26538. newChunk.next = this.next;
  26539. if (newChunk.next) { newChunk.next.previous = newChunk; }
  26540. newChunk.previous = this;
  26541. this.next = newChunk;
  26542. return newChunk;
  26543. };
  26544. Chunk.prototype.toString = function toString () {
  26545. return this.intro + this.content + this.outro;
  26546. };
  26547. Chunk.prototype.trimEnd = function trimEnd (rx) {
  26548. this.outro = this.outro.replace(rx, '');
  26549. if (this.outro.length) { return true; }
  26550. var trimmed = this.content.replace(rx, '');
  26551. if (trimmed.length) {
  26552. if (trimmed !== this.content) {
  26553. this.split(this.start + trimmed.length).edit('', undefined, true);
  26554. }
  26555. return true;
  26556. } else {
  26557. this.edit('', undefined, true);
  26558. this.intro = this.intro.replace(rx, '');
  26559. if (this.intro.length) { return true; }
  26560. }
  26561. };
  26562. Chunk.prototype.trimStart = function trimStart (rx) {
  26563. this.intro = this.intro.replace(rx, '');
  26564. if (this.intro.length) { return true; }
  26565. var trimmed = this.content.replace(rx, '');
  26566. if (trimmed.length) {
  26567. if (trimmed !== this.content) {
  26568. this.split(this.end - trimmed.length);
  26569. this.edit('', undefined, true);
  26570. }
  26571. return true;
  26572. } else {
  26573. this.edit('', undefined, true);
  26574. this.outro = this.outro.replace(rx, '');
  26575. if (this.outro.length) { return true; }
  26576. }
  26577. };
  26578. var btoa = function () {
  26579. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  26580. };
  26581. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  26582. btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
  26583. } else if (typeof Buffer === 'function') {
  26584. btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
  26585. }
  26586. var SourceMap = function SourceMap(properties) {
  26587. this.version = 3;
  26588. this.file = properties.file;
  26589. this.sources = properties.sources;
  26590. this.sourcesContent = properties.sourcesContent;
  26591. this.names = properties.names;
  26592. this.mappings = encode$1(properties.mappings);
  26593. };
  26594. SourceMap.prototype.toString = function toString () {
  26595. return JSON.stringify(this);
  26596. };
  26597. SourceMap.prototype.toUrl = function toUrl () {
  26598. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  26599. };
  26600. function guessIndent(code) {
  26601. var lines = code.split('\n');
  26602. var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
  26603. var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
  26604. if (tabbed.length === 0 && spaced.length === 0) {
  26605. return null;
  26606. }
  26607. // More lines tabbed than spaced? Assume tabs, and
  26608. // default to tabs in the case of a tie (or nothing
  26609. // to go on)
  26610. if (tabbed.length >= spaced.length) {
  26611. return '\t';
  26612. }
  26613. // Otherwise, we need to guess the multiple
  26614. var min = spaced.reduce(function (previous, current) {
  26615. var numSpaces = /^ +/.exec(current)[0].length;
  26616. return Math.min(numSpaces, previous);
  26617. }, Infinity);
  26618. return new Array(min + 1).join(' ');
  26619. }
  26620. function getRelativePath(from, to) {
  26621. var fromParts = from.split(/[/\\]/);
  26622. var toParts = to.split(/[/\\]/);
  26623. fromParts.pop(); // get dirname
  26624. while (fromParts[0] === toParts[0]) {
  26625. fromParts.shift();
  26626. toParts.shift();
  26627. }
  26628. if (fromParts.length) {
  26629. var i = fromParts.length;
  26630. while (i--) { fromParts[i] = '..'; }
  26631. }
  26632. return fromParts.concat(toParts).join('/');
  26633. }
  26634. var toString = Object.prototype.toString;
  26635. function isObject$1(thing) {
  26636. return toString.call(thing) === '[object Object]';
  26637. }
  26638. function getLocator(source) {
  26639. var originalLines = source.split('\n');
  26640. var lineOffsets = [];
  26641. for (var i = 0, pos = 0; i < originalLines.length; i++) {
  26642. lineOffsets.push(pos);
  26643. pos += originalLines[i].length + 1;
  26644. }
  26645. return function locate(index) {
  26646. var i = 0;
  26647. var j = lineOffsets.length;
  26648. while (i < j) {
  26649. var m = (i + j) >> 1;
  26650. if (index < lineOffsets[m]) {
  26651. j = m;
  26652. } else {
  26653. i = m + 1;
  26654. }
  26655. }
  26656. var line = i - 1;
  26657. var column = index - lineOffsets[line];
  26658. return { line: line, column: column };
  26659. };
  26660. }
  26661. var Mappings = function Mappings(hires) {
  26662. this.hires = hires;
  26663. this.generatedCodeLine = 0;
  26664. this.generatedCodeColumn = 0;
  26665. this.raw = [];
  26666. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  26667. this.pending = null;
  26668. };
  26669. Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
  26670. if (content.length) {
  26671. var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  26672. if (nameIndex >= 0) {
  26673. segment.push(nameIndex);
  26674. }
  26675. this.rawSegments.push(segment);
  26676. } else if (this.pending) {
  26677. this.rawSegments.push(this.pending);
  26678. }
  26679. this.advance(content);
  26680. this.pending = null;
  26681. };
  26682. Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
  26683. var originalCharIndex = chunk.start;
  26684. var first = true;
  26685. while (originalCharIndex < chunk.end) {
  26686. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  26687. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  26688. }
  26689. if (original[originalCharIndex] === '\n') {
  26690. loc.line += 1;
  26691. loc.column = 0;
  26692. this.generatedCodeLine += 1;
  26693. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  26694. this.generatedCodeColumn = 0;
  26695. first = true;
  26696. } else {
  26697. loc.column += 1;
  26698. this.generatedCodeColumn += 1;
  26699. first = false;
  26700. }
  26701. originalCharIndex += 1;
  26702. }
  26703. this.pending = null;
  26704. };
  26705. Mappings.prototype.advance = function advance (str) {
  26706. if (!str) { return; }
  26707. var lines = str.split('\n');
  26708. if (lines.length > 1) {
  26709. for (var i = 0; i < lines.length - 1; i++) {
  26710. this.generatedCodeLine++;
  26711. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  26712. }
  26713. this.generatedCodeColumn = 0;
  26714. }
  26715. this.generatedCodeColumn += lines[lines.length - 1].length;
  26716. };
  26717. var n = '\n';
  26718. var warned = {
  26719. insertLeft: false,
  26720. insertRight: false,
  26721. storeName: false
  26722. };
  26723. var MagicString = function MagicString(string, options) {
  26724. if ( options === void 0 ) options = {};
  26725. var chunk = new Chunk(0, string.length, string);
  26726. Object.defineProperties(this, {
  26727. original: { writable: true, value: string },
  26728. outro: { writable: true, value: '' },
  26729. intro: { writable: true, value: '' },
  26730. firstChunk: { writable: true, value: chunk },
  26731. lastChunk: { writable: true, value: chunk },
  26732. lastSearchedChunk: { writable: true, value: chunk },
  26733. byStart: { writable: true, value: {} },
  26734. byEnd: { writable: true, value: {} },
  26735. filename: { writable: true, value: options.filename },
  26736. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  26737. sourcemapLocations: { writable: true, value: new BitSet() },
  26738. storedNames: { writable: true, value: {} },
  26739. indentStr: { writable: true, value: guessIndent(string) }
  26740. });
  26741. this.byStart[0] = chunk;
  26742. this.byEnd[string.length] = chunk;
  26743. };
  26744. MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
  26745. this.sourcemapLocations.add(char);
  26746. };
  26747. MagicString.prototype.append = function append (content) {
  26748. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  26749. this.outro += content;
  26750. return this;
  26751. };
  26752. MagicString.prototype.appendLeft = function appendLeft (index, content) {
  26753. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  26754. this._split(index);
  26755. var chunk = this.byEnd[index];
  26756. if (chunk) {
  26757. chunk.appendLeft(content);
  26758. } else {
  26759. this.intro += content;
  26760. }
  26761. return this;
  26762. };
  26763. MagicString.prototype.appendRight = function appendRight (index, content) {
  26764. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  26765. this._split(index);
  26766. var chunk = this.byStart[index];
  26767. if (chunk) {
  26768. chunk.appendRight(content);
  26769. } else {
  26770. this.outro += content;
  26771. }
  26772. return this;
  26773. };
  26774. MagicString.prototype.clone = function clone () {
  26775. var cloned = new MagicString(this.original, { filename: this.filename });
  26776. var originalChunk = this.firstChunk;
  26777. var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  26778. while (originalChunk) {
  26779. cloned.byStart[clonedChunk.start] = clonedChunk;
  26780. cloned.byEnd[clonedChunk.end] = clonedChunk;
  26781. var nextOriginalChunk = originalChunk.next;
  26782. var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  26783. if (nextClonedChunk) {
  26784. clonedChunk.next = nextClonedChunk;
  26785. nextClonedChunk.previous = clonedChunk;
  26786. clonedChunk = nextClonedChunk;
  26787. }
  26788. originalChunk = nextOriginalChunk;
  26789. }
  26790. cloned.lastChunk = clonedChunk;
  26791. if (this.indentExclusionRanges) {
  26792. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  26793. }
  26794. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  26795. cloned.intro = this.intro;
  26796. cloned.outro = this.outro;
  26797. return cloned;
  26798. };
  26799. MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
  26800. var this$1$1 = this;
  26801. options = options || {};
  26802. var sourceIndex = 0;
  26803. var names = Object.keys(this.storedNames);
  26804. var mappings = new Mappings(options.hires);
  26805. var locate = getLocator(this.original);
  26806. if (this.intro) {
  26807. mappings.advance(this.intro);
  26808. }
  26809. this.firstChunk.eachNext(function (chunk) {
  26810. var loc = locate(chunk.start);
  26811. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  26812. if (chunk.edited) {
  26813. mappings.addEdit(
  26814. sourceIndex,
  26815. chunk.content,
  26816. loc,
  26817. chunk.storeName ? names.indexOf(chunk.original) : -1
  26818. );
  26819. } else {
  26820. mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations);
  26821. }
  26822. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  26823. });
  26824. return {
  26825. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  26826. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  26827. sourcesContent: options.includeContent ? [this.original] : [null],
  26828. names: names,
  26829. mappings: mappings.raw
  26830. };
  26831. };
  26832. MagicString.prototype.generateMap = function generateMap (options) {
  26833. return new SourceMap(this.generateDecodedMap(options));
  26834. };
  26835. MagicString.prototype.getIndentString = function getIndentString () {
  26836. return this.indentStr === null ? '\t' : this.indentStr;
  26837. };
  26838. MagicString.prototype.indent = function indent (indentStr, options) {
  26839. var pattern = /^[^\r\n]/gm;
  26840. if (isObject$1(indentStr)) {
  26841. options = indentStr;
  26842. indentStr = undefined;
  26843. }
  26844. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  26845. if (indentStr === '') { return this; } // noop
  26846. options = options || {};
  26847. // Process exclusion ranges
  26848. var isExcluded = {};
  26849. if (options.exclude) {
  26850. var exclusions =
  26851. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  26852. exclusions.forEach(function (exclusion) {
  26853. for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
  26854. isExcluded[i] = true;
  26855. }
  26856. });
  26857. }
  26858. var shouldIndentNextCharacter = options.indentStart !== false;
  26859. var replacer = function (match) {
  26860. if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
  26861. shouldIndentNextCharacter = true;
  26862. return match;
  26863. };
  26864. this.intro = this.intro.replace(pattern, replacer);
  26865. var charIndex = 0;
  26866. var chunk = this.firstChunk;
  26867. while (chunk) {
  26868. var end = chunk.end;
  26869. if (chunk.edited) {
  26870. if (!isExcluded[charIndex]) {
  26871. chunk.content = chunk.content.replace(pattern, replacer);
  26872. if (chunk.content.length) {
  26873. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  26874. }
  26875. }
  26876. } else {
  26877. charIndex = chunk.start;
  26878. while (charIndex < end) {
  26879. if (!isExcluded[charIndex]) {
  26880. var char = this.original[charIndex];
  26881. if (char === '\n') {
  26882. shouldIndentNextCharacter = true;
  26883. } else if (char !== '\r' && shouldIndentNextCharacter) {
  26884. shouldIndentNextCharacter = false;
  26885. if (charIndex === chunk.start) {
  26886. chunk.prependRight(indentStr);
  26887. } else {
  26888. this._splitChunk(chunk, charIndex);
  26889. chunk = chunk.next;
  26890. chunk.prependRight(indentStr);
  26891. }
  26892. }
  26893. }
  26894. charIndex += 1;
  26895. }
  26896. }
  26897. charIndex = chunk.end;
  26898. chunk = chunk.next;
  26899. }
  26900. this.outro = this.outro.replace(pattern, replacer);
  26901. return this;
  26902. };
  26903. MagicString.prototype.insert = function insert () {
  26904. throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
  26905. };
  26906. MagicString.prototype.insertLeft = function insertLeft (index, content) {
  26907. if (!warned.insertLeft) {
  26908. console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
  26909. warned.insertLeft = true;
  26910. }
  26911. return this.appendLeft(index, content);
  26912. };
  26913. MagicString.prototype.insertRight = function insertRight (index, content) {
  26914. if (!warned.insertRight) {
  26915. console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
  26916. warned.insertRight = true;
  26917. }
  26918. return this.prependRight(index, content);
  26919. };
  26920. MagicString.prototype.move = function move (start, end, index) {
  26921. if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
  26922. this._split(start);
  26923. this._split(end);
  26924. this._split(index);
  26925. var first = this.byStart[start];
  26926. var last = this.byEnd[end];
  26927. var oldLeft = first.previous;
  26928. var oldRight = last.next;
  26929. var newRight = this.byStart[index];
  26930. if (!newRight && last === this.lastChunk) { return this; }
  26931. var newLeft = newRight ? newRight.previous : this.lastChunk;
  26932. if (oldLeft) { oldLeft.next = oldRight; }
  26933. if (oldRight) { oldRight.previous = oldLeft; }
  26934. if (newLeft) { newLeft.next = first; }
  26935. if (newRight) { newRight.previous = last; }
  26936. if (!first.previous) { this.firstChunk = last.next; }
  26937. if (!last.next) {
  26938. this.lastChunk = first.previous;
  26939. this.lastChunk.next = null;
  26940. }
  26941. first.previous = newLeft;
  26942. last.next = newRight || null;
  26943. if (!newLeft) { this.firstChunk = first; }
  26944. if (!newRight) { this.lastChunk = last; }
  26945. return this;
  26946. };
  26947. MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
  26948. if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
  26949. while (start < 0) { start += this.original.length; }
  26950. while (end < 0) { end += this.original.length; }
  26951. if (end > this.original.length) { throw new Error('end is out of bounds'); }
  26952. if (start === end)
  26953. { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
  26954. this._split(start);
  26955. this._split(end);
  26956. if (options === true) {
  26957. if (!warned.storeName) {
  26958. console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console
  26959. warned.storeName = true;
  26960. }
  26961. options = { storeName: true };
  26962. }
  26963. var storeName = options !== undefined ? options.storeName : false;
  26964. var contentOnly = options !== undefined ? options.contentOnly : false;
  26965. if (storeName) {
  26966. var original = this.original.slice(start, end);
  26967. this.storedNames[original] = true;
  26968. }
  26969. var first = this.byStart[start];
  26970. var last = this.byEnd[end];
  26971. if (first) {
  26972. if (end > first.end && first.next !== this.byStart[first.end]) {
  26973. throw new Error('Cannot overwrite across a split point');
  26974. }
  26975. first.edit(content, storeName, contentOnly);
  26976. if (first !== last) {
  26977. var chunk = first.next;
  26978. while (chunk !== last) {
  26979. chunk.edit('', false);
  26980. chunk = chunk.next;
  26981. }
  26982. chunk.edit('', false);
  26983. }
  26984. } else {
  26985. // must be inserting at the end
  26986. var newChunk = new Chunk(start, end, '').edit(content, storeName);
  26987. // TODO last chunk in the array may not be the last chunk, if it's moved...
  26988. last.next = newChunk;
  26989. newChunk.previous = last;
  26990. }
  26991. return this;
  26992. };
  26993. MagicString.prototype.prepend = function prepend (content) {
  26994. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  26995. this.intro = content + this.intro;
  26996. return this;
  26997. };
  26998. MagicString.prototype.prependLeft = function prependLeft (index, content) {
  26999. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  27000. this._split(index);
  27001. var chunk = this.byEnd[index];
  27002. if (chunk) {
  27003. chunk.prependLeft(content);
  27004. } else {
  27005. this.intro = content + this.intro;
  27006. }
  27007. return this;
  27008. };
  27009. MagicString.prototype.prependRight = function prependRight (index, content) {
  27010. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  27011. this._split(index);
  27012. var chunk = this.byStart[index];
  27013. if (chunk) {
  27014. chunk.prependRight(content);
  27015. } else {
  27016. this.outro = content + this.outro;
  27017. }
  27018. return this;
  27019. };
  27020. MagicString.prototype.remove = function remove (start, end) {
  27021. while (start < 0) { start += this.original.length; }
  27022. while (end < 0) { end += this.original.length; }
  27023. if (start === end) { return this; }
  27024. if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
  27025. if (start > end) { throw new Error('end must be greater than start'); }
  27026. this._split(start);
  27027. this._split(end);
  27028. var chunk = this.byStart[start];
  27029. while (chunk) {
  27030. chunk.intro = '';
  27031. chunk.outro = '';
  27032. chunk.edit('');
  27033. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  27034. }
  27035. return this;
  27036. };
  27037. MagicString.prototype.lastChar = function lastChar () {
  27038. if (this.outro.length)
  27039. { return this.outro[this.outro.length - 1]; }
  27040. var chunk = this.lastChunk;
  27041. do {
  27042. if (chunk.outro.length)
  27043. { return chunk.outro[chunk.outro.length - 1]; }
  27044. if (chunk.content.length)
  27045. { return chunk.content[chunk.content.length - 1]; }
  27046. if (chunk.intro.length)
  27047. { return chunk.intro[chunk.intro.length - 1]; }
  27048. } while (chunk = chunk.previous);
  27049. if (this.intro.length)
  27050. { return this.intro[this.intro.length - 1]; }
  27051. return '';
  27052. };
  27053. MagicString.prototype.lastLine = function lastLine () {
  27054. var lineIndex = this.outro.lastIndexOf(n);
  27055. if (lineIndex !== -1)
  27056. { return this.outro.substr(lineIndex + 1); }
  27057. var lineStr = this.outro;
  27058. var chunk = this.lastChunk;
  27059. do {
  27060. if (chunk.outro.length > 0) {
  27061. lineIndex = chunk.outro.lastIndexOf(n);
  27062. if (lineIndex !== -1)
  27063. { return chunk.outro.substr(lineIndex + 1) + lineStr; }
  27064. lineStr = chunk.outro + lineStr;
  27065. }
  27066. if (chunk.content.length > 0) {
  27067. lineIndex = chunk.content.lastIndexOf(n);
  27068. if (lineIndex !== -1)
  27069. { return chunk.content.substr(lineIndex + 1) + lineStr; }
  27070. lineStr = chunk.content + lineStr;
  27071. }
  27072. if (chunk.intro.length > 0) {
  27073. lineIndex = chunk.intro.lastIndexOf(n);
  27074. if (lineIndex !== -1)
  27075. { return chunk.intro.substr(lineIndex + 1) + lineStr; }
  27076. lineStr = chunk.intro + lineStr;
  27077. }
  27078. } while (chunk = chunk.previous);
  27079. lineIndex = this.intro.lastIndexOf(n);
  27080. if (lineIndex !== -1)
  27081. { return this.intro.substr(lineIndex + 1) + lineStr; }
  27082. return this.intro + lineStr;
  27083. };
  27084. MagicString.prototype.slice = function slice (start, end) {
  27085. if ( start === void 0 ) start = 0;
  27086. if ( end === void 0 ) end = this.original.length;
  27087. while (start < 0) { start += this.original.length; }
  27088. while (end < 0) { end += this.original.length; }
  27089. var result = '';
  27090. // find start chunk
  27091. var chunk = this.firstChunk;
  27092. while (chunk && (chunk.start > start || chunk.end <= start)) {
  27093. // found end chunk before start
  27094. if (chunk.start < end && chunk.end >= end) {
  27095. return result;
  27096. }
  27097. chunk = chunk.next;
  27098. }
  27099. if (chunk && chunk.edited && chunk.start !== start)
  27100. { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
  27101. var startChunk = chunk;
  27102. while (chunk) {
  27103. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  27104. result += chunk.intro;
  27105. }
  27106. var containsEnd = chunk.start < end && chunk.end >= end;
  27107. if (containsEnd && chunk.edited && chunk.end !== end)
  27108. { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
  27109. var sliceStart = startChunk === chunk ? start - chunk.start : 0;
  27110. var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  27111. result += chunk.content.slice(sliceStart, sliceEnd);
  27112. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  27113. result += chunk.outro;
  27114. }
  27115. if (containsEnd) {
  27116. break;
  27117. }
  27118. chunk = chunk.next;
  27119. }
  27120. return result;
  27121. };
  27122. // TODO deprecate this? not really very useful
  27123. MagicString.prototype.snip = function snip (start, end) {
  27124. var clone = this.clone();
  27125. clone.remove(0, start);
  27126. clone.remove(end, clone.original.length);
  27127. return clone;
  27128. };
  27129. MagicString.prototype._split = function _split (index) {
  27130. if (this.byStart[index] || this.byEnd[index]) { return; }
  27131. var chunk = this.lastSearchedChunk;
  27132. var searchForward = index > chunk.end;
  27133. while (chunk) {
  27134. if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
  27135. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  27136. }
  27137. };
  27138. MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
  27139. if (chunk.edited && chunk.content.length) {
  27140. // zero-length edited chunks are a special case (overlapping replacements)
  27141. var loc = getLocator(this.original)(index);
  27142. throw new Error(
  27143. ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
  27144. );
  27145. }
  27146. var newChunk = chunk.split(index);
  27147. this.byEnd[index] = chunk;
  27148. this.byStart[index] = newChunk;
  27149. this.byEnd[newChunk.end] = newChunk;
  27150. if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
  27151. this.lastSearchedChunk = chunk;
  27152. return true;
  27153. };
  27154. MagicString.prototype.toString = function toString () {
  27155. var str = this.intro;
  27156. var chunk = this.firstChunk;
  27157. while (chunk) {
  27158. str += chunk.toString();
  27159. chunk = chunk.next;
  27160. }
  27161. return str + this.outro;
  27162. };
  27163. MagicString.prototype.isEmpty = function isEmpty () {
  27164. var chunk = this.firstChunk;
  27165. do {
  27166. if (chunk.intro.length && chunk.intro.trim() ||
  27167. chunk.content.length && chunk.content.trim() ||
  27168. chunk.outro.length && chunk.outro.trim())
  27169. { return false; }
  27170. } while (chunk = chunk.next);
  27171. return true;
  27172. };
  27173. MagicString.prototype.length = function length () {
  27174. var chunk = this.firstChunk;
  27175. var length = 0;
  27176. do {
  27177. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  27178. } while (chunk = chunk.next);
  27179. return length;
  27180. };
  27181. MagicString.prototype.trimLines = function trimLines () {
  27182. return this.trim('[\\r\\n]');
  27183. };
  27184. MagicString.prototype.trim = function trim (charType) {
  27185. return this.trimStart(charType).trimEnd(charType);
  27186. };
  27187. MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
  27188. var rx = new RegExp((charType || '\\s') + '+$');
  27189. this.outro = this.outro.replace(rx, '');
  27190. if (this.outro.length) { return true; }
  27191. var chunk = this.lastChunk;
  27192. do {
  27193. var end = chunk.end;
  27194. var aborted = chunk.trimEnd(rx);
  27195. // if chunk was trimmed, we have a new lastChunk
  27196. if (chunk.end !== end) {
  27197. if (this.lastChunk === chunk) {
  27198. this.lastChunk = chunk.next;
  27199. }
  27200. this.byEnd[chunk.end] = chunk;
  27201. this.byStart[chunk.next.start] = chunk.next;
  27202. this.byEnd[chunk.next.end] = chunk.next;
  27203. }
  27204. if (aborted) { return true; }
  27205. chunk = chunk.previous;
  27206. } while (chunk);
  27207. return false;
  27208. };
  27209. MagicString.prototype.trimEnd = function trimEnd (charType) {
  27210. this.trimEndAborted(charType);
  27211. return this;
  27212. };
  27213. MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
  27214. var rx = new RegExp('^' + (charType || '\\s') + '+');
  27215. this.intro = this.intro.replace(rx, '');
  27216. if (this.intro.length) { return true; }
  27217. var chunk = this.firstChunk;
  27218. do {
  27219. var end = chunk.end;
  27220. var aborted = chunk.trimStart(rx);
  27221. if (chunk.end !== end) {
  27222. // special case...
  27223. if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
  27224. this.byEnd[chunk.end] = chunk;
  27225. this.byStart[chunk.next.start] = chunk.next;
  27226. this.byEnd[chunk.next.end] = chunk.next;
  27227. }
  27228. if (aborted) { return true; }
  27229. chunk = chunk.next;
  27230. } while (chunk);
  27231. return false;
  27232. };
  27233. MagicString.prototype.trimStart = function trimStart (charType) {
  27234. this.trimStartAborted(charType);
  27235. return this;
  27236. };
  27237. var MagicString$1 = MagicString;
  27238. // Copyright Joyent, Inc. and other Node contributors.
  27239. //
  27240. // Permission is hereby granted, free of charge, to any person obtaining a
  27241. // copy of this software and associated documentation files (the
  27242. // "Software"), to deal in the Software without restriction, including
  27243. // without limitation the rights to use, copy, modify, merge, publish,
  27244. // distribute, sublicense, and/or sell copies of the Software, and to permit
  27245. // persons to whom the Software is furnished to do so, subject to the
  27246. // following conditions:
  27247. //
  27248. // The above copyright notice and this permission notice shall be included
  27249. // in all copies or substantial portions of the Software.
  27250. //
  27251. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  27252. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27253. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  27254. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  27255. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  27256. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  27257. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  27258. // resolves . and .. elements in a path array with directory names there
  27259. // must be no slashes, empty elements, or device names (c:\) in the array
  27260. // (so also no leading and trailing slashes - it does not distinguish
  27261. // relative and absolute paths)
  27262. function normalizeArray(parts, allowAboveRoot) {
  27263. // if the path tries to go above the root, `up` ends up > 0
  27264. var up = 0;
  27265. for (var i = parts.length - 1; i >= 0; i--) {
  27266. var last = parts[i];
  27267. if (last === '.') {
  27268. parts.splice(i, 1);
  27269. } else if (last === '..') {
  27270. parts.splice(i, 1);
  27271. up++;
  27272. } else if (up) {
  27273. parts.splice(i, 1);
  27274. up--;
  27275. }
  27276. }
  27277. // if the path is allowed to go above the root, restore leading ..s
  27278. if (allowAboveRoot) {
  27279. for (; up--; up) {
  27280. parts.unshift('..');
  27281. }
  27282. }
  27283. return parts;
  27284. }
  27285. // Split a filename into [root, dir, basename, ext], unix version
  27286. // 'root' is just a slash, or nothing.
  27287. var splitPathRe =
  27288. /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  27289. var splitPath = function(filename) {
  27290. return splitPathRe.exec(filename).slice(1);
  27291. };
  27292. // path.resolve([from ...], to)
  27293. // posix version
  27294. function resolve$2() {
  27295. var resolvedPath = '',
  27296. resolvedAbsolute = false;
  27297. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  27298. var path = (i >= 0) ? arguments[i] : '/';
  27299. // Skip empty and invalid entries
  27300. if (typeof path !== 'string') {
  27301. throw new TypeError('Arguments to path.resolve must be strings');
  27302. } else if (!path) {
  27303. continue;
  27304. }
  27305. resolvedPath = path + '/' + resolvedPath;
  27306. resolvedAbsolute = path.charAt(0) === '/';
  27307. }
  27308. // At this point the path should be resolved to a full absolute path, but
  27309. // handle relative paths to be safe (might happen when process.cwd() fails)
  27310. // Normalize the path
  27311. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  27312. return !!p;
  27313. }), !resolvedAbsolute).join('/');
  27314. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  27315. }
  27316. // path.normalize(path)
  27317. // posix version
  27318. function normalize(path) {
  27319. var isPathAbsolute = isAbsolute$1(path),
  27320. trailingSlash = substr(path, -1) === '/';
  27321. // Normalize the path
  27322. path = normalizeArray(filter(path.split('/'), function(p) {
  27323. return !!p;
  27324. }), !isPathAbsolute).join('/');
  27325. if (!path && !isPathAbsolute) {
  27326. path = '.';
  27327. }
  27328. if (path && trailingSlash) {
  27329. path += '/';
  27330. }
  27331. return (isPathAbsolute ? '/' : '') + path;
  27332. }
  27333. // posix version
  27334. function isAbsolute$1(path) {
  27335. return path.charAt(0) === '/';
  27336. }
  27337. // posix version
  27338. function join$1() {
  27339. var paths = Array.prototype.slice.call(arguments, 0);
  27340. return normalize(filter(paths, function(p, index) {
  27341. if (typeof p !== 'string') {
  27342. throw new TypeError('Arguments to path.join must be strings');
  27343. }
  27344. return p;
  27345. }).join('/'));
  27346. }
  27347. // path.relative(from, to)
  27348. // posix version
  27349. function relative$1(from, to) {
  27350. from = resolve$2(from).substr(1);
  27351. to = resolve$2(to).substr(1);
  27352. function trim(arr) {
  27353. var start = 0;
  27354. for (; start < arr.length; start++) {
  27355. if (arr[start] !== '') break;
  27356. }
  27357. var end = arr.length - 1;
  27358. for (; end >= 0; end--) {
  27359. if (arr[end] !== '') break;
  27360. }
  27361. if (start > end) return [];
  27362. return arr.slice(start, end - start + 1);
  27363. }
  27364. var fromParts = trim(from.split('/'));
  27365. var toParts = trim(to.split('/'));
  27366. var length = Math.min(fromParts.length, toParts.length);
  27367. var samePartsLength = length;
  27368. for (var i = 0; i < length; i++) {
  27369. if (fromParts[i] !== toParts[i]) {
  27370. samePartsLength = i;
  27371. break;
  27372. }
  27373. }
  27374. var outputParts = [];
  27375. for (var i = samePartsLength; i < fromParts.length; i++) {
  27376. outputParts.push('..');
  27377. }
  27378. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  27379. return outputParts.join('/');
  27380. }
  27381. var sep$1 = '/';
  27382. var delimiter$1 = ':';
  27383. function dirname$2(path) {
  27384. var result = splitPath(path),
  27385. root = result[0],
  27386. dir = result[1];
  27387. if (!root && !dir) {
  27388. // No dirname whatsoever
  27389. return '.';
  27390. }
  27391. if (dir) {
  27392. // It has a dirname, strip trailing slash
  27393. dir = dir.substr(0, dir.length - 1);
  27394. }
  27395. return root + dir;
  27396. }
  27397. function basename(path, ext) {
  27398. var f = splitPath(path)[2];
  27399. // TODO: make this comparison case-insensitive on windows?
  27400. if (ext && f.substr(-1 * ext.length) === ext) {
  27401. f = f.substr(0, f.length - ext.length);
  27402. }
  27403. return f;
  27404. }
  27405. function extname(path) {
  27406. return splitPath(path)[3];
  27407. }
  27408. var path = {
  27409. extname: extname,
  27410. basename: basename,
  27411. dirname: dirname$2,
  27412. sep: sep$1,
  27413. delimiter: delimiter$1,
  27414. relative: relative$1,
  27415. join: join$1,
  27416. isAbsolute: isAbsolute$1,
  27417. normalize: normalize,
  27418. resolve: resolve$2
  27419. };
  27420. function filter (xs, f) {
  27421. if (xs.filter) return xs.filter(f);
  27422. var res = [];
  27423. for (var i = 0; i < xs.length; i++) {
  27424. if (f(xs[i], i, xs)) res.push(xs[i]);
  27425. }
  27426. return res;
  27427. }
  27428. // String.prototype.substr - negative index don't work in IE8
  27429. var substr = 'ab'.substr(-1) === 'b' ?
  27430. function (str, start, len) { return str.substr(start, len) } :
  27431. function (str, start, len) {
  27432. if (start < 0) start = str.length + start;
  27433. return str.substr(start, len);
  27434. }
  27435. ;
  27436. var _polyfillNode_path = /*#__PURE__*/Object.freeze({
  27437. __proto__: null,
  27438. basename: basename,
  27439. default: path,
  27440. delimiter: delimiter$1,
  27441. dirname: dirname$2,
  27442. extname: extname,
  27443. isAbsolute: isAbsolute$1,
  27444. join: join$1,
  27445. normalize: normalize,
  27446. relative: relative$1,
  27447. resolve: resolve$2,
  27448. sep: sep$1
  27449. });
  27450. /*! https://mths.be/punycode v1.4.1 by @mathias */
  27451. /** Highest positive signed 32-bit float value */
  27452. var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
  27453. /** Bootstring parameters */
  27454. var base = 36;
  27455. var tMin = 1;
  27456. var tMax = 26;
  27457. var skew = 38;
  27458. var damp = 700;
  27459. var initialBias = 72;
  27460. var initialN = 128; // 0x80
  27461. var delimiter = '-'; // '\x2D'
  27462. var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars
  27463. var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
  27464. /** Error messages */
  27465. var errors = {
  27466. 'overflow': 'Overflow: input needs wider integers to process',
  27467. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  27468. 'invalid-input': 'Invalid input'
  27469. };
  27470. /** Convenience shortcuts */
  27471. var baseMinusTMin = base - tMin;
  27472. var floor = Math.floor;
  27473. var stringFromCharCode = String.fromCharCode;
  27474. /*--------------------------------------------------------------------------*/
  27475. /**
  27476. * A generic error utility function.
  27477. * @private
  27478. * @param {String} type The error type.
  27479. * @returns {Error} Throws a `RangeError` with the applicable error message.
  27480. */
  27481. function error(type) {
  27482. throw new RangeError(errors[type]);
  27483. }
  27484. /**
  27485. * A generic `Array#map` utility function.
  27486. * @private
  27487. * @param {Array} array The array to iterate over.
  27488. * @param {Function} callback The function that gets called for every array
  27489. * item.
  27490. * @returns {Array} A new array of values returned by the callback function.
  27491. */
  27492. function map$1(array, fn) {
  27493. var length = array.length;
  27494. var result = [];
  27495. while (length--) {
  27496. result[length] = fn(array[length]);
  27497. }
  27498. return result;
  27499. }
  27500. /**
  27501. * A simple `Array#map`-like wrapper to work with domain name strings or email
  27502. * addresses.
  27503. * @private
  27504. * @param {String} domain The domain name or email address.
  27505. * @param {Function} callback The function that gets called for every
  27506. * character.
  27507. * @returns {Array} A new string of characters returned by the callback
  27508. * function.
  27509. */
  27510. function mapDomain(string, fn) {
  27511. var parts = string.split('@');
  27512. var result = '';
  27513. if (parts.length > 1) {
  27514. // In email addresses, only the domain name should be punycoded. Leave
  27515. // the local part (i.e. everything up to `@`) intact.
  27516. result = parts[0] + '@';
  27517. string = parts[1];
  27518. }
  27519. // Avoid `split(regex)` for IE8 compatibility. See #17.
  27520. string = string.replace(regexSeparators, '\x2E');
  27521. var labels = string.split('.');
  27522. var encoded = map$1(labels, fn).join('.');
  27523. return result + encoded;
  27524. }
  27525. /**
  27526. * Creates an array containing the numeric code points of each Unicode
  27527. * character in the string. While JavaScript uses UCS-2 internally,
  27528. * this function will convert a pair of surrogate halves (each of which
  27529. * UCS-2 exposes as separate characters) into a single code point,
  27530. * matching UTF-16.
  27531. * @see `punycode.ucs2.encode`
  27532. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  27533. * @memberOf punycode.ucs2
  27534. * @name decode
  27535. * @param {String} string The Unicode input string (UCS-2).
  27536. * @returns {Array} The new array of code points.
  27537. */
  27538. function ucs2decode(string) {
  27539. var output = [],
  27540. counter = 0,
  27541. length = string.length,
  27542. value,
  27543. extra;
  27544. while (counter < length) {
  27545. value = string.charCodeAt(counter++);
  27546. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  27547. // high surrogate, and there is a next character
  27548. extra = string.charCodeAt(counter++);
  27549. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  27550. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  27551. } else {
  27552. // unmatched surrogate; only append this code unit, in case the next
  27553. // code unit is the high surrogate of a surrogate pair
  27554. output.push(value);
  27555. counter--;
  27556. }
  27557. } else {
  27558. output.push(value);
  27559. }
  27560. }
  27561. return output;
  27562. }
  27563. /**
  27564. * Converts a digit/integer into a basic code point.
  27565. * @see `basicToDigit()`
  27566. * @private
  27567. * @param {Number} digit The numeric value of a basic code point.
  27568. * @returns {Number} The basic code point whose value (when used for
  27569. * representing integers) is `digit`, which needs to be in the range
  27570. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  27571. * used; else, the lowercase form is used. The behavior is undefined
  27572. * if `flag` is non-zero and `digit` has no uppercase form.
  27573. */
  27574. function digitToBasic(digit, flag) {
  27575. // 0..25 map to ASCII a..z or A..Z
  27576. // 26..35 map to ASCII 0..9
  27577. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  27578. }
  27579. /**
  27580. * Bias adaptation function as per section 3.4 of RFC 3492.
  27581. * https://tools.ietf.org/html/rfc3492#section-3.4
  27582. * @private
  27583. */
  27584. function adapt(delta, numPoints, firstTime) {
  27585. var k = 0;
  27586. delta = firstTime ? floor(delta / damp) : delta >> 1;
  27587. delta += floor(delta / numPoints);
  27588. for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) {
  27589. delta = floor(delta / baseMinusTMin);
  27590. }
  27591. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  27592. }
  27593. /**
  27594. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  27595. * Punycode string of ASCII-only symbols.
  27596. * @memberOf punycode
  27597. * @param {String} input The string of Unicode symbols.
  27598. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  27599. */
  27600. function encode(input) {
  27601. var n,
  27602. delta,
  27603. handledCPCount,
  27604. basicLength,
  27605. bias,
  27606. j,
  27607. m,
  27608. q,
  27609. k,
  27610. t,
  27611. currentValue,
  27612. output = [],
  27613. /** `inputLength` will hold the number of code points in `input`. */
  27614. inputLength,
  27615. /** Cached calculation results */
  27616. handledCPCountPlusOne,
  27617. baseMinusT,
  27618. qMinusT;
  27619. // Convert the input in UCS-2 to Unicode
  27620. input = ucs2decode(input);
  27621. // Cache the length
  27622. inputLength = input.length;
  27623. // Initialize the state
  27624. n = initialN;
  27625. delta = 0;
  27626. bias = initialBias;
  27627. // Handle the basic code points
  27628. for (j = 0; j < inputLength; ++j) {
  27629. currentValue = input[j];
  27630. if (currentValue < 0x80) {
  27631. output.push(stringFromCharCode(currentValue));
  27632. }
  27633. }
  27634. handledCPCount = basicLength = output.length;
  27635. // `handledCPCount` is the number of code points that have been handled;
  27636. // `basicLength` is the number of basic code points.
  27637. // Finish the basic string - if it is not empty - with a delimiter
  27638. if (basicLength) {
  27639. output.push(delimiter);
  27640. }
  27641. // Main encoding loop:
  27642. while (handledCPCount < inputLength) {
  27643. // All non-basic code points < n have been handled already. Find the next
  27644. // larger one:
  27645. for (m = maxInt, j = 0; j < inputLength; ++j) {
  27646. currentValue = input[j];
  27647. if (currentValue >= n && currentValue < m) {
  27648. m = currentValue;
  27649. }
  27650. }
  27651. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  27652. // but guard against overflow
  27653. handledCPCountPlusOne = handledCPCount + 1;
  27654. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  27655. error('overflow');
  27656. }
  27657. delta += (m - n) * handledCPCountPlusOne;
  27658. n = m;
  27659. for (j = 0; j < inputLength; ++j) {
  27660. currentValue = input[j];
  27661. if (currentValue < n && ++delta > maxInt) {
  27662. error('overflow');
  27663. }
  27664. if (currentValue == n) {
  27665. // Represent delta as a generalized variable-length integer
  27666. for (q = delta, k = base; /* no condition */ ; k += base) {
  27667. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  27668. if (q < t) {
  27669. break;
  27670. }
  27671. qMinusT = q - t;
  27672. baseMinusT = base - t;
  27673. output.push(
  27674. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  27675. );
  27676. q = floor(qMinusT / baseMinusT);
  27677. }
  27678. output.push(stringFromCharCode(digitToBasic(q, 0)));
  27679. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  27680. delta = 0;
  27681. ++handledCPCount;
  27682. }
  27683. }
  27684. ++delta;
  27685. ++n;
  27686. }
  27687. return output.join('');
  27688. }
  27689. /**
  27690. * Converts a Unicode string representing a domain name or an email address to
  27691. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  27692. * i.e. it doesn't matter if you call it with a domain that's already in
  27693. * ASCII.
  27694. * @memberOf punycode
  27695. * @param {String} input The domain name or email address to convert, as a
  27696. * Unicode string.
  27697. * @returns {String} The Punycode representation of the given domain name or
  27698. * email address.
  27699. */
  27700. function toASCII(input) {
  27701. return mapDomain(input, function(string) {
  27702. return regexNonASCII.test(string) ?
  27703. 'xn--' + encode(string) :
  27704. string;
  27705. });
  27706. }
  27707. // shim for using process in browser
  27708. // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
  27709. function defaultSetTimout() {
  27710. throw new Error('setTimeout has not been defined');
  27711. }
  27712. function defaultClearTimeout () {
  27713. throw new Error('clearTimeout has not been defined');
  27714. }
  27715. var cachedSetTimeout = defaultSetTimout;
  27716. var cachedClearTimeout = defaultClearTimeout;
  27717. if (typeof global$1.setTimeout === 'function') {
  27718. cachedSetTimeout = setTimeout;
  27719. }
  27720. if (typeof global$1.clearTimeout === 'function') {
  27721. cachedClearTimeout = clearTimeout;
  27722. }
  27723. function runTimeout(fun) {
  27724. if (cachedSetTimeout === setTimeout) {
  27725. //normal enviroments in sane situations
  27726. return setTimeout(fun, 0);
  27727. }
  27728. // if setTimeout wasn't available but was latter defined
  27729. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  27730. cachedSetTimeout = setTimeout;
  27731. return setTimeout(fun, 0);
  27732. }
  27733. try {
  27734. // when when somebody has screwed with setTimeout but no I.E. maddness
  27735. return cachedSetTimeout(fun, 0);
  27736. } catch(e){
  27737. try {
  27738. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  27739. return cachedSetTimeout.call(null, fun, 0);
  27740. } catch(e){
  27741. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  27742. return cachedSetTimeout.call(this, fun, 0);
  27743. }
  27744. }
  27745. }
  27746. function runClearTimeout(marker) {
  27747. if (cachedClearTimeout === clearTimeout) {
  27748. //normal enviroments in sane situations
  27749. return clearTimeout(marker);
  27750. }
  27751. // if clearTimeout wasn't available but was latter defined
  27752. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  27753. cachedClearTimeout = clearTimeout;
  27754. return clearTimeout(marker);
  27755. }
  27756. try {
  27757. // when when somebody has screwed with setTimeout but no I.E. maddness
  27758. return cachedClearTimeout(marker);
  27759. } catch (e){
  27760. try {
  27761. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  27762. return cachedClearTimeout.call(null, marker);
  27763. } catch (e){
  27764. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  27765. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  27766. return cachedClearTimeout.call(this, marker);
  27767. }
  27768. }
  27769. }
  27770. var queue = [];
  27771. var draining = false;
  27772. var currentQueue;
  27773. var queueIndex = -1;
  27774. function cleanUpNextTick() {
  27775. if (!draining || !currentQueue) {
  27776. return;
  27777. }
  27778. draining = false;
  27779. if (currentQueue.length) {
  27780. queue = currentQueue.concat(queue);
  27781. } else {
  27782. queueIndex = -1;
  27783. }
  27784. if (queue.length) {
  27785. drainQueue();
  27786. }
  27787. }
  27788. function drainQueue() {
  27789. if (draining) {
  27790. return;
  27791. }
  27792. var timeout = runTimeout(cleanUpNextTick);
  27793. draining = true;
  27794. var len = queue.length;
  27795. while(len) {
  27796. currentQueue = queue;
  27797. queue = [];
  27798. while (++queueIndex < len) {
  27799. if (currentQueue) {
  27800. currentQueue[queueIndex].run();
  27801. }
  27802. }
  27803. queueIndex = -1;
  27804. len = queue.length;
  27805. }
  27806. currentQueue = null;
  27807. draining = false;
  27808. runClearTimeout(timeout);
  27809. }
  27810. function nextTick(fun) {
  27811. var args = new Array(arguments.length - 1);
  27812. if (arguments.length > 1) {
  27813. for (var i = 1; i < arguments.length; i++) {
  27814. args[i - 1] = arguments[i];
  27815. }
  27816. }
  27817. queue.push(new Item(fun, args));
  27818. if (queue.length === 1 && !draining) {
  27819. runTimeout(drainQueue);
  27820. }
  27821. }
  27822. // v8 likes predictible objects
  27823. function Item(fun, array) {
  27824. this.fun = fun;
  27825. this.array = array;
  27826. }
  27827. Item.prototype.run = function () {
  27828. this.fun.apply(null, this.array);
  27829. };
  27830. var title = 'browser';
  27831. var platform = 'browser';
  27832. var browser = true;
  27833. var env = {};
  27834. var argv = [];
  27835. var version = ''; // empty string to avoid regexp issues
  27836. var versions = {};
  27837. var release = {};
  27838. var config = {};
  27839. function noop() {}
  27840. var on = noop;
  27841. var addListener = noop;
  27842. var once = noop;
  27843. var off = noop;
  27844. var removeListener = noop;
  27845. var removeAllListeners = noop;
  27846. var emit = noop;
  27847. function binding(name) {
  27848. throw new Error('process.binding is not supported');
  27849. }
  27850. function cwd () { return '/' }
  27851. function chdir (dir) {
  27852. throw new Error('process.chdir is not supported');
  27853. }function umask() { return 0; }
  27854. // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
  27855. var performance = global$1.performance || {};
  27856. var performanceNow =
  27857. performance.now ||
  27858. performance.mozNow ||
  27859. performance.msNow ||
  27860. performance.oNow ||
  27861. performance.webkitNow ||
  27862. function(){ return (new Date()).getTime() };
  27863. // generate timestamp or delta
  27864. // see http://nodejs.org/api/process.html#process_process_hrtime
  27865. function hrtime(previousTimestamp){
  27866. var clocktime = performanceNow.call(performance)*1e-3;
  27867. var seconds = Math.floor(clocktime);
  27868. var nanoseconds = Math.floor((clocktime%1)*1e9);
  27869. if (previousTimestamp) {
  27870. seconds = seconds - previousTimestamp[0];
  27871. nanoseconds = nanoseconds - previousTimestamp[1];
  27872. if (nanoseconds<0) {
  27873. seconds--;
  27874. nanoseconds += 1e9;
  27875. }
  27876. }
  27877. return [seconds,nanoseconds]
  27878. }
  27879. var startTime = new Date();
  27880. function uptime() {
  27881. var currentTime = new Date();
  27882. var dif = currentTime - startTime;
  27883. return dif / 1000;
  27884. }
  27885. var browser$1 = {
  27886. nextTick: nextTick,
  27887. title: title,
  27888. browser: browser,
  27889. env: env,
  27890. argv: argv,
  27891. version: version,
  27892. versions: versions,
  27893. on: on,
  27894. addListener: addListener,
  27895. once: once,
  27896. off: off,
  27897. removeListener: removeListener,
  27898. removeAllListeners: removeAllListeners,
  27899. emit: emit,
  27900. binding: binding,
  27901. cwd: cwd,
  27902. chdir: chdir,
  27903. umask: umask,
  27904. hrtime: hrtime,
  27905. platform: platform,
  27906. release: release,
  27907. config: config,
  27908. uptime: uptime
  27909. };
  27910. var inherits;
  27911. if (typeof Object.create === 'function'){
  27912. inherits = function inherits(ctor, superCtor) {
  27913. // implementation from standard node.js 'util' module
  27914. ctor.super_ = superCtor;
  27915. ctor.prototype = Object.create(superCtor.prototype, {
  27916. constructor: {
  27917. value: ctor,
  27918. enumerable: false,
  27919. writable: true,
  27920. configurable: true
  27921. }
  27922. });
  27923. };
  27924. } else {
  27925. inherits = function inherits(ctor, superCtor) {
  27926. ctor.super_ = superCtor;
  27927. var TempCtor = function () {};
  27928. TempCtor.prototype = superCtor.prototype;
  27929. ctor.prototype = new TempCtor();
  27930. ctor.prototype.constructor = ctor;
  27931. };
  27932. }
  27933. var inherits$1 = inherits;
  27934. var formatRegExp = /%[sdj%]/g;
  27935. function format$1(f) {
  27936. if (!isString$1(f)) {
  27937. var objects = [];
  27938. for (var i = 0; i < arguments.length; i++) {
  27939. objects.push(inspect(arguments[i]));
  27940. }
  27941. return objects.join(' ');
  27942. }
  27943. var i = 1;
  27944. var args = arguments;
  27945. var len = args.length;
  27946. var str = String(f).replace(formatRegExp, function(x) {
  27947. if (x === '%%') return '%';
  27948. if (i >= len) return x;
  27949. switch (x) {
  27950. case '%s': return String(args[i++]);
  27951. case '%d': return Number(args[i++]);
  27952. case '%j':
  27953. try {
  27954. return JSON.stringify(args[i++]);
  27955. } catch (_) {
  27956. return '[Circular]';
  27957. }
  27958. default:
  27959. return x;
  27960. }
  27961. });
  27962. for (var x = args[i]; i < len; x = args[++i]) {
  27963. if (isNull(x) || !isObject(x)) {
  27964. str += ' ' + x;
  27965. } else {
  27966. str += ' ' + inspect(x);
  27967. }
  27968. }
  27969. return str;
  27970. }
  27971. // Mark that a method should not be used.
  27972. // Returns a modified function which warns once by default.
  27973. // If --no-deprecation is set, then it is a no-op.
  27974. function deprecate(fn, msg) {
  27975. // Allow for deprecating things in the process of starting up.
  27976. if (isUndefined(global$1.process)) {
  27977. return function() {
  27978. return deprecate(fn, msg).apply(this, arguments);
  27979. };
  27980. }
  27981. if (browser$1.noDeprecation === true) {
  27982. return fn;
  27983. }
  27984. var warned = false;
  27985. function deprecated() {
  27986. if (!warned) {
  27987. if (browser$1.throwDeprecation) {
  27988. throw new Error(msg);
  27989. } else if (browser$1.traceDeprecation) {
  27990. console.trace(msg);
  27991. } else {
  27992. console.error(msg);
  27993. }
  27994. warned = true;
  27995. }
  27996. return fn.apply(this, arguments);
  27997. }
  27998. return deprecated;
  27999. }
  28000. var debugs = {};
  28001. var debugEnviron;
  28002. function debuglog(set) {
  28003. if (isUndefined(debugEnviron))
  28004. debugEnviron = browser$1.env.NODE_DEBUG || '';
  28005. set = set.toUpperCase();
  28006. if (!debugs[set]) {
  28007. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  28008. var pid = 0;
  28009. debugs[set] = function() {
  28010. var msg = format$1.apply(null, arguments);
  28011. console.error('%s %d: %s', set, pid, msg);
  28012. };
  28013. } else {
  28014. debugs[set] = function() {};
  28015. }
  28016. }
  28017. return debugs[set];
  28018. }
  28019. /**
  28020. * Echos the value of a value. Trys to print the value out
  28021. * in the best way possible given the different types.
  28022. *
  28023. * @param {Object} obj The object to print out.
  28024. * @param {Object} opts Optional options object that alters the output.
  28025. */
  28026. /* legacy: obj, showHidden, depth, colors*/
  28027. function inspect(obj, opts) {
  28028. // default options
  28029. var ctx = {
  28030. seen: [],
  28031. stylize: stylizeNoColor
  28032. };
  28033. // legacy...
  28034. if (arguments.length >= 3) ctx.depth = arguments[2];
  28035. if (arguments.length >= 4) ctx.colors = arguments[3];
  28036. if (isBoolean(opts)) {
  28037. // legacy...
  28038. ctx.showHidden = opts;
  28039. } else if (opts) {
  28040. // got an "options" object
  28041. _extend(ctx, opts);
  28042. }
  28043. // set default options
  28044. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  28045. if (isUndefined(ctx.depth)) ctx.depth = 2;
  28046. if (isUndefined(ctx.colors)) ctx.colors = false;
  28047. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  28048. if (ctx.colors) ctx.stylize = stylizeWithColor;
  28049. return formatValue(ctx, obj, ctx.depth);
  28050. }
  28051. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  28052. inspect.colors = {
  28053. 'bold' : [1, 22],
  28054. 'italic' : [3, 23],
  28055. 'underline' : [4, 24],
  28056. 'inverse' : [7, 27],
  28057. 'white' : [37, 39],
  28058. 'grey' : [90, 39],
  28059. 'black' : [30, 39],
  28060. 'blue' : [34, 39],
  28061. 'cyan' : [36, 39],
  28062. 'green' : [32, 39],
  28063. 'magenta' : [35, 39],
  28064. 'red' : [31, 39],
  28065. 'yellow' : [33, 39]
  28066. };
  28067. // Don't use 'blue' not visible on cmd.exe
  28068. inspect.styles = {
  28069. 'special': 'cyan',
  28070. 'number': 'yellow',
  28071. 'boolean': 'yellow',
  28072. 'undefined': 'grey',
  28073. 'null': 'bold',
  28074. 'string': 'green',
  28075. 'date': 'magenta',
  28076. // "name": intentionally not styling
  28077. 'regexp': 'red'
  28078. };
  28079. function stylizeWithColor(str, styleType) {
  28080. var style = inspect.styles[styleType];
  28081. if (style) {
  28082. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  28083. '\u001b[' + inspect.colors[style][1] + 'm';
  28084. } else {
  28085. return str;
  28086. }
  28087. }
  28088. function stylizeNoColor(str, styleType) {
  28089. return str;
  28090. }
  28091. function arrayToHash(array) {
  28092. var hash = {};
  28093. array.forEach(function(val, idx) {
  28094. hash[val] = true;
  28095. });
  28096. return hash;
  28097. }
  28098. function formatValue(ctx, value, recurseTimes) {
  28099. // Provide a hook for user-specified inspect functions.
  28100. // Check that value is an object with an inspect function on it
  28101. if (ctx.customInspect &&
  28102. value &&
  28103. isFunction(value.inspect) &&
  28104. // Filter out the util module, it's inspect function is special
  28105. value.inspect !== inspect &&
  28106. // Also filter out any prototype objects using the circular check.
  28107. !(value.constructor && value.constructor.prototype === value)) {
  28108. var ret = value.inspect(recurseTimes, ctx);
  28109. if (!isString$1(ret)) {
  28110. ret = formatValue(ctx, ret, recurseTimes);
  28111. }
  28112. return ret;
  28113. }
  28114. // Primitive types cannot have properties
  28115. var primitive = formatPrimitive(ctx, value);
  28116. if (primitive) {
  28117. return primitive;
  28118. }
  28119. // Look up the keys of the object.
  28120. var keys = Object.keys(value);
  28121. var visibleKeys = arrayToHash(keys);
  28122. if (ctx.showHidden) {
  28123. keys = Object.getOwnPropertyNames(value);
  28124. }
  28125. // IE doesn't make error fields non-enumerable
  28126. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  28127. if (isError(value)
  28128. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  28129. return formatError(value);
  28130. }
  28131. // Some type of object without properties can be shortcutted.
  28132. if (keys.length === 0) {
  28133. if (isFunction(value)) {
  28134. var name = value.name ? ': ' + value.name : '';
  28135. return ctx.stylize('[Function' + name + ']', 'special');
  28136. }
  28137. if (isRegExp(value)) {
  28138. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  28139. }
  28140. if (isDate(value)) {
  28141. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  28142. }
  28143. if (isError(value)) {
  28144. return formatError(value);
  28145. }
  28146. }
  28147. var base = '', array = false, braces = ['{', '}'];
  28148. // Make Array say that they are Array
  28149. if (isArray$1(value)) {
  28150. array = true;
  28151. braces = ['[', ']'];
  28152. }
  28153. // Make functions say that they are functions
  28154. if (isFunction(value)) {
  28155. var n = value.name ? ': ' + value.name : '';
  28156. base = ' [Function' + n + ']';
  28157. }
  28158. // Make RegExps say that they are RegExps
  28159. if (isRegExp(value)) {
  28160. base = ' ' + RegExp.prototype.toString.call(value);
  28161. }
  28162. // Make dates with properties first say the date
  28163. if (isDate(value)) {
  28164. base = ' ' + Date.prototype.toUTCString.call(value);
  28165. }
  28166. // Make error with message first say the error
  28167. if (isError(value)) {
  28168. base = ' ' + formatError(value);
  28169. }
  28170. if (keys.length === 0 && (!array || value.length == 0)) {
  28171. return braces[0] + base + braces[1];
  28172. }
  28173. if (recurseTimes < 0) {
  28174. if (isRegExp(value)) {
  28175. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  28176. } else {
  28177. return ctx.stylize('[Object]', 'special');
  28178. }
  28179. }
  28180. ctx.seen.push(value);
  28181. var output;
  28182. if (array) {
  28183. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  28184. } else {
  28185. output = keys.map(function(key) {
  28186. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  28187. });
  28188. }
  28189. ctx.seen.pop();
  28190. return reduceToSingleString(output, base, braces);
  28191. }
  28192. function formatPrimitive(ctx, value) {
  28193. if (isUndefined(value))
  28194. return ctx.stylize('undefined', 'undefined');
  28195. if (isString$1(value)) {
  28196. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  28197. .replace(/'/g, "\\'")
  28198. .replace(/\\"/g, '"') + '\'';
  28199. return ctx.stylize(simple, 'string');
  28200. }
  28201. if (isNumber(value))
  28202. return ctx.stylize('' + value, 'number');
  28203. if (isBoolean(value))
  28204. return ctx.stylize('' + value, 'boolean');
  28205. // For some reason typeof null is "object", so special case here.
  28206. if (isNull(value))
  28207. return ctx.stylize('null', 'null');
  28208. }
  28209. function formatError(value) {
  28210. return '[' + Error.prototype.toString.call(value) + ']';
  28211. }
  28212. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  28213. var output = [];
  28214. for (var i = 0, l = value.length; i < l; ++i) {
  28215. if (hasOwnProperty$2(value, String(i))) {
  28216. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  28217. String(i), true));
  28218. } else {
  28219. output.push('');
  28220. }
  28221. }
  28222. keys.forEach(function(key) {
  28223. if (!key.match(/^\d+$/)) {
  28224. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  28225. key, true));
  28226. }
  28227. });
  28228. return output;
  28229. }
  28230. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  28231. var name, str, desc;
  28232. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  28233. if (desc.get) {
  28234. if (desc.set) {
  28235. str = ctx.stylize('[Getter/Setter]', 'special');
  28236. } else {
  28237. str = ctx.stylize('[Getter]', 'special');
  28238. }
  28239. } else {
  28240. if (desc.set) {
  28241. str = ctx.stylize('[Setter]', 'special');
  28242. }
  28243. }
  28244. if (!hasOwnProperty$2(visibleKeys, key)) {
  28245. name = '[' + key + ']';
  28246. }
  28247. if (!str) {
  28248. if (ctx.seen.indexOf(desc.value) < 0) {
  28249. if (isNull(recurseTimes)) {
  28250. str = formatValue(ctx, desc.value, null);
  28251. } else {
  28252. str = formatValue(ctx, desc.value, recurseTimes - 1);
  28253. }
  28254. if (str.indexOf('\n') > -1) {
  28255. if (array) {
  28256. str = str.split('\n').map(function(line) {
  28257. return ' ' + line;
  28258. }).join('\n').substr(2);
  28259. } else {
  28260. str = '\n' + str.split('\n').map(function(line) {
  28261. return ' ' + line;
  28262. }).join('\n');
  28263. }
  28264. }
  28265. } else {
  28266. str = ctx.stylize('[Circular]', 'special');
  28267. }
  28268. }
  28269. if (isUndefined(name)) {
  28270. if (array && key.match(/^\d+$/)) {
  28271. return str;
  28272. }
  28273. name = JSON.stringify('' + key);
  28274. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  28275. name = name.substr(1, name.length - 2);
  28276. name = ctx.stylize(name, 'name');
  28277. } else {
  28278. name = name.replace(/'/g, "\\'")
  28279. .replace(/\\"/g, '"')
  28280. .replace(/(^"|"$)/g, "'");
  28281. name = ctx.stylize(name, 'string');
  28282. }
  28283. }
  28284. return name + ': ' + str;
  28285. }
  28286. function reduceToSingleString(output, base, braces) {
  28287. var length = output.reduce(function(prev, cur) {
  28288. if (cur.indexOf('\n') >= 0) ;
  28289. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  28290. }, 0);
  28291. if (length > 60) {
  28292. return braces[0] +
  28293. (base === '' ? '' : base + '\n ') +
  28294. ' ' +
  28295. output.join(',\n ') +
  28296. ' ' +
  28297. braces[1];
  28298. }
  28299. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  28300. }
  28301. // NOTE: These type checking functions intentionally don't use `instanceof`
  28302. // because it is fragile and can be easily faked with `Object.create()`.
  28303. function isArray$1(ar) {
  28304. return Array.isArray(ar);
  28305. }
  28306. function isBoolean(arg) {
  28307. return typeof arg === 'boolean';
  28308. }
  28309. function isNull(arg) {
  28310. return arg === null;
  28311. }
  28312. function isNullOrUndefined(arg) {
  28313. return arg == null;
  28314. }
  28315. function isNumber(arg) {
  28316. return typeof arg === 'number';
  28317. }
  28318. function isString$1(arg) {
  28319. return typeof arg === 'string';
  28320. }
  28321. function isSymbol(arg) {
  28322. return typeof arg === 'symbol';
  28323. }
  28324. function isUndefined(arg) {
  28325. return arg === void 0;
  28326. }
  28327. function isRegExp(re) {
  28328. return isObject(re) && objectToString(re) === '[object RegExp]';
  28329. }
  28330. function isObject(arg) {
  28331. return typeof arg === 'object' && arg !== null;
  28332. }
  28333. function isDate(d) {
  28334. return isObject(d) && objectToString(d) === '[object Date]';
  28335. }
  28336. function isError(e) {
  28337. return isObject(e) &&
  28338. (objectToString(e) === '[object Error]' || e instanceof Error);
  28339. }
  28340. function isFunction(arg) {
  28341. return typeof arg === 'function';
  28342. }
  28343. function isPrimitive(arg) {
  28344. return arg === null ||
  28345. typeof arg === 'boolean' ||
  28346. typeof arg === 'number' ||
  28347. typeof arg === 'string' ||
  28348. typeof arg === 'symbol' || // ES6 symbol
  28349. typeof arg === 'undefined';
  28350. }
  28351. function isBuffer(maybeBuf) {
  28352. return Buffer.isBuffer(maybeBuf);
  28353. }
  28354. function objectToString(o) {
  28355. return Object.prototype.toString.call(o);
  28356. }
  28357. function pad(n) {
  28358. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  28359. }
  28360. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  28361. 'Oct', 'Nov', 'Dec'];
  28362. // 26 Feb 16:19:34
  28363. function timestamp() {
  28364. var d = new Date();
  28365. var time = [pad(d.getHours()),
  28366. pad(d.getMinutes()),
  28367. pad(d.getSeconds())].join(':');
  28368. return [d.getDate(), months[d.getMonth()], time].join(' ');
  28369. }
  28370. // log is just a thin wrapper to console.log that prepends a timestamp
  28371. function log() {
  28372. console.log('%s - %s', timestamp(), format$1.apply(null, arguments));
  28373. }
  28374. function _extend(origin, add) {
  28375. // Don't do anything if add isn't an object
  28376. if (!add || !isObject(add)) return origin;
  28377. var keys = Object.keys(add);
  28378. var i = keys.length;
  28379. while (i--) {
  28380. origin[keys[i]] = add[keys[i]];
  28381. }
  28382. return origin;
  28383. }
  28384. function hasOwnProperty$2(obj, prop) {
  28385. return Object.prototype.hasOwnProperty.call(obj, prop);
  28386. }
  28387. var _polyfillNode_util = {
  28388. inherits: inherits$1,
  28389. _extend: _extend,
  28390. log: log,
  28391. isBuffer: isBuffer,
  28392. isPrimitive: isPrimitive,
  28393. isFunction: isFunction,
  28394. isError: isError,
  28395. isDate: isDate,
  28396. isObject: isObject,
  28397. isRegExp: isRegExp,
  28398. isUndefined: isUndefined,
  28399. isSymbol: isSymbol,
  28400. isString: isString$1,
  28401. isNumber: isNumber,
  28402. isNullOrUndefined: isNullOrUndefined,
  28403. isNull: isNull,
  28404. isBoolean: isBoolean,
  28405. isArray: isArray$1,
  28406. inspect: inspect,
  28407. deprecate: deprecate,
  28408. format: format$1,
  28409. debuglog: debuglog
  28410. };
  28411. var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({
  28412. __proto__: null,
  28413. _extend: _extend,
  28414. debuglog: debuglog,
  28415. default: _polyfillNode_util,
  28416. deprecate: deprecate,
  28417. format: format$1,
  28418. inherits: inherits$1,
  28419. inspect: inspect,
  28420. isArray: isArray$1,
  28421. isBoolean: isBoolean,
  28422. isBuffer: isBuffer,
  28423. isDate: isDate,
  28424. isError: isError,
  28425. isFunction: isFunction,
  28426. isNull: isNull,
  28427. isNullOrUndefined: isNullOrUndefined,
  28428. isNumber: isNumber,
  28429. isObject: isObject,
  28430. isPrimitive: isPrimitive,
  28431. isRegExp: isRegExp,
  28432. isString: isString$1,
  28433. isSymbol: isSymbol,
  28434. isUndefined: isUndefined,
  28435. log: log
  28436. });
  28437. // Copyright Joyent, Inc. and other Node contributors.
  28438. //
  28439. // Permission is hereby granted, free of charge, to any person obtaining a
  28440. // copy of this software and associated documentation files (the
  28441. // "Software"), to deal in the Software without restriction, including
  28442. // without limitation the rights to use, copy, modify, merge, publish,
  28443. // distribute, sublicense, and/or sell copies of the Software, and to permit
  28444. // persons to whom the Software is furnished to do so, subject to the
  28445. // following conditions:
  28446. //
  28447. // The above copyright notice and this permission notice shall be included
  28448. // in all copies or substantial portions of the Software.
  28449. //
  28450. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  28451. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  28452. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  28453. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  28454. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  28455. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  28456. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  28457. // If obj.hasOwnProperty has been overridden, then calling
  28458. // obj.hasOwnProperty(prop) will break.
  28459. // See: https://github.com/joyent/node/issues/1707
  28460. function hasOwnProperty$1(obj, prop) {
  28461. return Object.prototype.hasOwnProperty.call(obj, prop);
  28462. }
  28463. var isArray = Array.isArray || function (xs) {
  28464. return Object.prototype.toString.call(xs) === '[object Array]';
  28465. };
  28466. function stringifyPrimitive(v) {
  28467. switch (typeof v) {
  28468. case 'string':
  28469. return v;
  28470. case 'boolean':
  28471. return v ? 'true' : 'false';
  28472. case 'number':
  28473. return isFinite(v) ? v : '';
  28474. default:
  28475. return '';
  28476. }
  28477. }
  28478. function stringify$5 (obj, sep, eq, name) {
  28479. sep = sep || '&';
  28480. eq = eq || '=';
  28481. if (obj === null) {
  28482. obj = undefined;
  28483. }
  28484. if (typeof obj === 'object') {
  28485. return map(objectKeys(obj), function(k) {
  28486. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  28487. if (isArray(obj[k])) {
  28488. return map(obj[k], function(v) {
  28489. return ks + encodeURIComponent(stringifyPrimitive(v));
  28490. }).join(sep);
  28491. } else {
  28492. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  28493. }
  28494. }).join(sep);
  28495. }
  28496. if (!name) return '';
  28497. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  28498. encodeURIComponent(stringifyPrimitive(obj));
  28499. }
  28500. function map (xs, f) {
  28501. if (xs.map) return xs.map(f);
  28502. var res = [];
  28503. for (var i = 0; i < xs.length; i++) {
  28504. res.push(f(xs[i], i));
  28505. }
  28506. return res;
  28507. }
  28508. var objectKeys = Object.keys || function (obj) {
  28509. var res = [];
  28510. for (var key in obj) {
  28511. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  28512. }
  28513. return res;
  28514. };
  28515. function parse$7(qs, sep, eq, options) {
  28516. sep = sep || '&';
  28517. eq = eq || '=';
  28518. var obj = {};
  28519. if (typeof qs !== 'string' || qs.length === 0) {
  28520. return obj;
  28521. }
  28522. var regexp = /\+/g;
  28523. qs = qs.split(sep);
  28524. var maxKeys = 1000;
  28525. if (options && typeof options.maxKeys === 'number') {
  28526. maxKeys = options.maxKeys;
  28527. }
  28528. var len = qs.length;
  28529. // maxKeys <= 0 means that we should not limit keys count
  28530. if (maxKeys > 0 && len > maxKeys) {
  28531. len = maxKeys;
  28532. }
  28533. for (var i = 0; i < len; ++i) {
  28534. var x = qs[i].replace(regexp, '%20'),
  28535. idx = x.indexOf(eq),
  28536. kstr, vstr, k, v;
  28537. if (idx >= 0) {
  28538. kstr = x.substr(0, idx);
  28539. vstr = x.substr(idx + 1);
  28540. } else {
  28541. kstr = x;
  28542. vstr = '';
  28543. }
  28544. k = decodeURIComponent(kstr);
  28545. v = decodeURIComponent(vstr);
  28546. if (!hasOwnProperty$1(obj, k)) {
  28547. obj[k] = v;
  28548. } else if (isArray(obj[k])) {
  28549. obj[k].push(v);
  28550. } else {
  28551. obj[k] = [obj[k], v];
  28552. }
  28553. }
  28554. return obj;
  28555. }
  28556. // WHATWG API
  28557. const URL$1 = global$1.URL;
  28558. const URLSearchParams = global$1.URLSearchParams;
  28559. var _polyfillNode_url = {
  28560. parse: urlParse,
  28561. resolve: urlResolve,
  28562. resolveObject: urlResolveObject,
  28563. fileURLToPath: urlFileURLToPath,
  28564. format: urlFormat,
  28565. Url: Url,
  28566. // WHATWG API
  28567. URL: URL$1,
  28568. URLSearchParams,
  28569. };
  28570. function Url() {
  28571. this.protocol = null;
  28572. this.slashes = null;
  28573. this.auth = null;
  28574. this.host = null;
  28575. this.port = null;
  28576. this.hostname = null;
  28577. this.hash = null;
  28578. this.search = null;
  28579. this.query = null;
  28580. this.pathname = null;
  28581. this.path = null;
  28582. this.href = null;
  28583. }
  28584. // Reference: RFC 3986, RFC 1808, RFC 2396
  28585. // define these here so at least they only have to be
  28586. // compiled once on the first module load.
  28587. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  28588. portPattern = /:[0-9]*$/,
  28589. // Special case for a simple path URL
  28590. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  28591. // RFC 2396: characters reserved for delimiting URLs.
  28592. // We actually just auto-escape these.
  28593. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  28594. // RFC 2396: characters not allowed for various reasons.
  28595. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  28596. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  28597. autoEscape = ['\''].concat(unwise),
  28598. // Characters that are never ever allowed in a hostname.
  28599. // Note that any invalid chars are also handled, but these
  28600. // are the ones that are *expected* to be seen, so we fast-path
  28601. // them.
  28602. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  28603. hostEndingChars = ['/', '?', '#'],
  28604. hostnameMaxLen = 255,
  28605. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  28606. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  28607. // protocols that can allow "unsafe" and "unwise" chars.
  28608. unsafeProtocol = {
  28609. 'javascript': true,
  28610. 'javascript:': true
  28611. },
  28612. // protocols that never have a hostname.
  28613. hostlessProtocol = {
  28614. 'javascript': true,
  28615. 'javascript:': true
  28616. },
  28617. // protocols that always contain a // bit.
  28618. slashedProtocol = {
  28619. 'http': true,
  28620. 'https': true,
  28621. 'ftp': true,
  28622. 'gopher': true,
  28623. 'file': true,
  28624. 'http:': true,
  28625. 'https:': true,
  28626. 'ftp:': true,
  28627. 'gopher:': true,
  28628. 'file:': true
  28629. };
  28630. function urlParse(url, parseQueryString, slashesDenoteHost) {
  28631. if (url && isObject(url) && url instanceof Url) return url;
  28632. var u = new Url;
  28633. u.parse(url, parseQueryString, slashesDenoteHost);
  28634. return u;
  28635. }
  28636. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  28637. return parse$6(this, url, parseQueryString, slashesDenoteHost);
  28638. };
  28639. function parse$6(self, url, parseQueryString, slashesDenoteHost) {
  28640. if (!isString$1(url)) {
  28641. throw new TypeError('Parameter \'url\' must be a string, not ' + typeof url);
  28642. }
  28643. // Copy chrome, IE, opera backslash-handling behavior.
  28644. // Back slashes before the query string get converted to forward slashes
  28645. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  28646. var queryIndex = url.indexOf('?'),
  28647. splitter =
  28648. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  28649. uSplit = url.split(splitter),
  28650. slashRegex = /\\/g;
  28651. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  28652. url = uSplit.join(splitter);
  28653. var rest = url;
  28654. // trim before proceeding.
  28655. // This is to support parse stuff like " http://foo.com \n"
  28656. rest = rest.trim();
  28657. if (!slashesDenoteHost && url.split('#').length === 1) {
  28658. // Try fast path regexp
  28659. var simplePath = simplePathPattern.exec(rest);
  28660. if (simplePath) {
  28661. self.path = rest;
  28662. self.href = rest;
  28663. self.pathname = simplePath[1];
  28664. if (simplePath[2]) {
  28665. self.search = simplePath[2];
  28666. if (parseQueryString) {
  28667. self.query = parse$7(self.search.substr(1));
  28668. } else {
  28669. self.query = self.search.substr(1);
  28670. }
  28671. } else if (parseQueryString) {
  28672. self.search = '';
  28673. self.query = {};
  28674. }
  28675. return self;
  28676. }
  28677. }
  28678. var proto = protocolPattern.exec(rest);
  28679. if (proto) {
  28680. proto = proto[0];
  28681. var lowerProto = proto.toLowerCase();
  28682. self.protocol = lowerProto;
  28683. rest = rest.substr(proto.length);
  28684. }
  28685. // figure out if it's got a host
  28686. // user@server is *always* interpreted as a hostname, and url
  28687. // resolution will treat //foo/bar as host=foo,path=bar because that's
  28688. // how the browser resolves relative URLs.
  28689. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  28690. var slashes = rest.substr(0, 2) === '//';
  28691. if (slashes && !(proto && hostlessProtocol[proto])) {
  28692. rest = rest.substr(2);
  28693. self.slashes = true;
  28694. }
  28695. }
  28696. var i, hec, l, p;
  28697. if (!hostlessProtocol[proto] &&
  28698. (slashes || (proto && !slashedProtocol[proto]))) {
  28699. // there's a hostname.
  28700. // the first instance of /, ?, ;, or # ends the host.
  28701. //
  28702. // If there is an @ in the hostname, then non-host chars *are* allowed
  28703. // to the left of the last @ sign, unless some host-ending character
  28704. // comes *before* the @-sign.
  28705. // URLs are obnoxious.
  28706. //
  28707. // ex:
  28708. // http://a@b@c/ => user:a@b host:c
  28709. // http://a@b?@c => user:a host:c path:/?@c
  28710. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  28711. // Review our test case against browsers more comprehensively.
  28712. // find the first instance of any hostEndingChars
  28713. var hostEnd = -1;
  28714. for (i = 0; i < hostEndingChars.length; i++) {
  28715. hec = rest.indexOf(hostEndingChars[i]);
  28716. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  28717. hostEnd = hec;
  28718. }
  28719. // at this point, either we have an explicit point where the
  28720. // auth portion cannot go past, or the last @ char is the decider.
  28721. var auth, atSign;
  28722. if (hostEnd === -1) {
  28723. // atSign can be anywhere.
  28724. atSign = rest.lastIndexOf('@');
  28725. } else {
  28726. // atSign must be in auth portion.
  28727. // http://a@b/c@d => host:b auth:a path:/c@d
  28728. atSign = rest.lastIndexOf('@', hostEnd);
  28729. }
  28730. // Now we have a portion which is definitely the auth.
  28731. // Pull that off.
  28732. if (atSign !== -1) {
  28733. auth = rest.slice(0, atSign);
  28734. rest = rest.slice(atSign + 1);
  28735. self.auth = decodeURIComponent(auth);
  28736. }
  28737. // the host is the remaining to the left of the first non-host char
  28738. hostEnd = -1;
  28739. for (i = 0; i < nonHostChars.length; i++) {
  28740. hec = rest.indexOf(nonHostChars[i]);
  28741. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  28742. hostEnd = hec;
  28743. }
  28744. // if we still have not hit it, then the entire thing is a host.
  28745. if (hostEnd === -1)
  28746. hostEnd = rest.length;
  28747. self.host = rest.slice(0, hostEnd);
  28748. rest = rest.slice(hostEnd);
  28749. // pull out port.
  28750. parseHost(self);
  28751. // we've indicated that there is a hostname,
  28752. // so even if it's empty, it has to be present.
  28753. self.hostname = self.hostname || '';
  28754. // if hostname begins with [ and ends with ]
  28755. // assume that it's an IPv6 address.
  28756. var ipv6Hostname = self.hostname[0] === '[' &&
  28757. self.hostname[self.hostname.length - 1] === ']';
  28758. // validate a little.
  28759. if (!ipv6Hostname) {
  28760. var hostparts = self.hostname.split(/\./);
  28761. for (i = 0, l = hostparts.length; i < l; i++) {
  28762. var part = hostparts[i];
  28763. if (!part) continue;
  28764. if (!part.match(hostnamePartPattern)) {
  28765. var newpart = '';
  28766. for (var j = 0, k = part.length; j < k; j++) {
  28767. if (part.charCodeAt(j) > 127) {
  28768. // we replace non-ASCII char with a temporary placeholder
  28769. // we need this to make sure size of hostname is not
  28770. // broken by replacing non-ASCII by nothing
  28771. newpart += 'x';
  28772. } else {
  28773. newpart += part[j];
  28774. }
  28775. }
  28776. // we test again with ASCII char only
  28777. if (!newpart.match(hostnamePartPattern)) {
  28778. var validParts = hostparts.slice(0, i);
  28779. var notHost = hostparts.slice(i + 1);
  28780. var bit = part.match(hostnamePartStart);
  28781. if (bit) {
  28782. validParts.push(bit[1]);
  28783. notHost.unshift(bit[2]);
  28784. }
  28785. if (notHost.length) {
  28786. rest = '/' + notHost.join('.') + rest;
  28787. }
  28788. self.hostname = validParts.join('.');
  28789. break;
  28790. }
  28791. }
  28792. }
  28793. }
  28794. if (self.hostname.length > hostnameMaxLen) {
  28795. self.hostname = '';
  28796. } else {
  28797. // hostnames are always lower case.
  28798. self.hostname = self.hostname.toLowerCase();
  28799. }
  28800. if (!ipv6Hostname) {
  28801. // IDNA Support: Returns a punycoded representation of "domain".
  28802. // It only converts parts of the domain name that
  28803. // have non-ASCII characters, i.e. it doesn't matter if
  28804. // you call it with a domain that already is ASCII-only.
  28805. self.hostname = toASCII(self.hostname);
  28806. }
  28807. p = self.port ? ':' + self.port : '';
  28808. var h = self.hostname || '';
  28809. self.host = h + p;
  28810. self.href += self.host;
  28811. // strip [ and ] from the hostname
  28812. // the host field still retains them, though
  28813. if (ipv6Hostname) {
  28814. self.hostname = self.hostname.substr(1, self.hostname.length - 2);
  28815. if (rest[0] !== '/') {
  28816. rest = '/' + rest;
  28817. }
  28818. }
  28819. }
  28820. // now rest is set to the post-host stuff.
  28821. // chop off any delim chars.
  28822. if (!unsafeProtocol[lowerProto]) {
  28823. // First, make 100% sure that any "autoEscape" chars get
  28824. // escaped, even if encodeURIComponent doesn't think they
  28825. // need to be.
  28826. for (i = 0, l = autoEscape.length; i < l; i++) {
  28827. var ae = autoEscape[i];
  28828. if (rest.indexOf(ae) === -1)
  28829. continue;
  28830. var esc = encodeURIComponent(ae);
  28831. if (esc === ae) {
  28832. esc = escape(ae);
  28833. }
  28834. rest = rest.split(ae).join(esc);
  28835. }
  28836. }
  28837. // chop off from the tail first.
  28838. var hash = rest.indexOf('#');
  28839. if (hash !== -1) {
  28840. // got a fragment string.
  28841. self.hash = rest.substr(hash);
  28842. rest = rest.slice(0, hash);
  28843. }
  28844. var qm = rest.indexOf('?');
  28845. if (qm !== -1) {
  28846. self.search = rest.substr(qm);
  28847. self.query = rest.substr(qm + 1);
  28848. if (parseQueryString) {
  28849. self.query = parse$7(self.query);
  28850. }
  28851. rest = rest.slice(0, qm);
  28852. } else if (parseQueryString) {
  28853. // no query string, but parseQueryString still requested
  28854. self.search = '';
  28855. self.query = {};
  28856. }
  28857. if (rest) self.pathname = rest;
  28858. if (slashedProtocol[lowerProto] &&
  28859. self.hostname && !self.pathname) {
  28860. self.pathname = '/';
  28861. }
  28862. //to support http.request
  28863. if (self.pathname || self.search) {
  28864. p = self.pathname || '';
  28865. var s = self.search || '';
  28866. self.path = p + s;
  28867. }
  28868. // finally, reconstruct the href based on what has been validated.
  28869. self.href = format(self);
  28870. return self;
  28871. }
  28872. function urlFileURLToPath(path) {
  28873. if (typeof path === 'string')
  28874. path = new Url().parse(path);
  28875. else if (!(path instanceof Url))
  28876. throw new TypeError('The "path" argument must be of type string or an instance of URL. Received type ' + (typeof path) + String(path));
  28877. if (path.protocol !== 'file:')
  28878. throw new TypeError('The URL must be of scheme file');
  28879. return getPathFromURLPosix(path);
  28880. }
  28881. function getPathFromURLPosix(url) {
  28882. const pathname = url.pathname;
  28883. for (let n = 0; n < pathname.length; n++) {
  28884. if (pathname[n] === '%') {
  28885. const third = pathname.codePointAt(n + 2) | 0x20;
  28886. if (pathname[n + 1] === '2' && third === 102) {
  28887. throw new TypeError(
  28888. 'must not include encoded / characters'
  28889. );
  28890. }
  28891. }
  28892. }
  28893. return decodeURIComponent(pathname);
  28894. }
  28895. // format a parsed object into a url string
  28896. function urlFormat(obj) {
  28897. // ensure it's an object, and not a string url.
  28898. // If it's an obj, this is a no-op.
  28899. // this way, you can call url_format() on strings
  28900. // to clean up potentially wonky urls.
  28901. if (isString$1(obj)) obj = parse$6({}, obj);
  28902. return format(obj);
  28903. }
  28904. function format(self) {
  28905. var auth = self.auth || '';
  28906. if (auth) {
  28907. auth = encodeURIComponent(auth);
  28908. auth = auth.replace(/%3A/i, ':');
  28909. auth += '@';
  28910. }
  28911. var protocol = self.protocol || '',
  28912. pathname = self.pathname || '',
  28913. hash = self.hash || '',
  28914. host = false,
  28915. query = '';
  28916. if (self.host) {
  28917. host = auth + self.host;
  28918. } else if (self.hostname) {
  28919. host = auth + (self.hostname.indexOf(':') === -1 ?
  28920. self.hostname :
  28921. '[' + this.hostname + ']');
  28922. if (self.port) {
  28923. host += ':' + self.port;
  28924. }
  28925. }
  28926. if (self.query &&
  28927. isObject(self.query) &&
  28928. Object.keys(self.query).length) {
  28929. query = stringify$5(self.query);
  28930. }
  28931. var search = self.search || (query && ('?' + query)) || '';
  28932. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  28933. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  28934. // unless they had them to begin with.
  28935. if (self.slashes ||
  28936. (!protocol || slashedProtocol[protocol]) && host !== false) {
  28937. host = '//' + (host || '');
  28938. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  28939. } else if (!host) {
  28940. host = '';
  28941. }
  28942. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  28943. if (search && search.charAt(0) !== '?') search = '?' + search;
  28944. pathname = pathname.replace(/[?#]/g, function(match) {
  28945. return encodeURIComponent(match);
  28946. });
  28947. search = search.replace('#', '%23');
  28948. return protocol + host + pathname + search + hash;
  28949. }
  28950. Url.prototype.format = function() {
  28951. return format(this);
  28952. };
  28953. function urlResolve(source, relative) {
  28954. return urlParse(source, false, true).resolve(relative);
  28955. }
  28956. Url.prototype.resolve = function(relative) {
  28957. return this.resolveObject(urlParse(relative, false, true)).format();
  28958. };
  28959. function urlResolveObject(source, relative) {
  28960. if (!source) return relative;
  28961. return urlParse(source, false, true).resolveObject(relative);
  28962. }
  28963. Url.prototype.resolveObject = function(relative) {
  28964. if (isString$1(relative)) {
  28965. var rel = new Url();
  28966. rel.parse(relative, false, true);
  28967. relative = rel;
  28968. }
  28969. var result = new Url();
  28970. var tkeys = Object.keys(this);
  28971. for (var tk = 0; tk < tkeys.length; tk++) {
  28972. var tkey = tkeys[tk];
  28973. result[tkey] = this[tkey];
  28974. }
  28975. // hash is always overridden, no matter what.
  28976. // even href="" will remove it.
  28977. result.hash = relative.hash;
  28978. // if the relative url is empty, then there's nothing left to do here.
  28979. if (relative.href === '') {
  28980. result.href = result.format();
  28981. return result;
  28982. }
  28983. // hrefs like //foo/bar always cut to the protocol.
  28984. if (relative.slashes && !relative.protocol) {
  28985. // take everything except the protocol from relative
  28986. var rkeys = Object.keys(relative);
  28987. for (var rk = 0; rk < rkeys.length; rk++) {
  28988. var rkey = rkeys[rk];
  28989. if (rkey !== 'protocol')
  28990. result[rkey] = relative[rkey];
  28991. }
  28992. //urlParse appends trailing / to urls like http://www.example.com
  28993. if (slashedProtocol[result.protocol] &&
  28994. result.hostname && !result.pathname) {
  28995. result.path = result.pathname = '/';
  28996. }
  28997. result.href = result.format();
  28998. return result;
  28999. }
  29000. var relPath;
  29001. if (relative.protocol && relative.protocol !== result.protocol) {
  29002. // if it's a known url protocol, then changing
  29003. // the protocol does weird things
  29004. // first, if it's not file:, then we MUST have a host,
  29005. // and if there was a path
  29006. // to begin with, then we MUST have a path.
  29007. // if it is file:, then the host is dropped,
  29008. // because that's known to be hostless.
  29009. // anything else is assumed to be absolute.
  29010. if (!slashedProtocol[relative.protocol]) {
  29011. var keys = Object.keys(relative);
  29012. for (var v = 0; v < keys.length; v++) {
  29013. var k = keys[v];
  29014. result[k] = relative[k];
  29015. }
  29016. result.href = result.format();
  29017. return result;
  29018. }
  29019. result.protocol = relative.protocol;
  29020. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  29021. relPath = (relative.pathname || '').split('/');
  29022. while (relPath.length && !(relative.host = relPath.shift()));
  29023. if (!relative.host) relative.host = '';
  29024. if (!relative.hostname) relative.hostname = '';
  29025. if (relPath[0] !== '') relPath.unshift('');
  29026. if (relPath.length < 2) relPath.unshift('');
  29027. result.pathname = relPath.join('/');
  29028. } else {
  29029. result.pathname = relative.pathname;
  29030. }
  29031. result.search = relative.search;
  29032. result.query = relative.query;
  29033. result.host = relative.host || '';
  29034. result.auth = relative.auth;
  29035. result.hostname = relative.hostname || relative.host;
  29036. result.port = relative.port;
  29037. // to support http.request
  29038. if (result.pathname || result.search) {
  29039. var p = result.pathname || '';
  29040. var s = result.search || '';
  29041. result.path = p + s;
  29042. }
  29043. result.slashes = result.slashes || relative.slashes;
  29044. result.href = result.format();
  29045. return result;
  29046. }
  29047. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  29048. isRelAbs = (
  29049. relative.host ||
  29050. relative.pathname && relative.pathname.charAt(0) === '/'
  29051. ),
  29052. mustEndAbs = (isRelAbs || isSourceAbs ||
  29053. (result.host && relative.pathname)),
  29054. removeAllDots = mustEndAbs,
  29055. srcPath = result.pathname && result.pathname.split('/') || [],
  29056. psychotic = result.protocol && !slashedProtocol[result.protocol];
  29057. relPath = relative.pathname && relative.pathname.split('/') || [];
  29058. // if the url is a non-slashed url, then relative
  29059. // links like ../.. should be able
  29060. // to crawl up to the hostname, as well. This is strange.
  29061. // result.protocol has already been set by now.
  29062. // Later on, put the first path part into the host field.
  29063. if (psychotic) {
  29064. result.hostname = '';
  29065. result.port = null;
  29066. if (result.host) {
  29067. if (srcPath[0] === '') srcPath[0] = result.host;
  29068. else srcPath.unshift(result.host);
  29069. }
  29070. result.host = '';
  29071. if (relative.protocol) {
  29072. relative.hostname = null;
  29073. relative.port = null;
  29074. if (relative.host) {
  29075. if (relPath[0] === '') relPath[0] = relative.host;
  29076. else relPath.unshift(relative.host);
  29077. }
  29078. relative.host = null;
  29079. }
  29080. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  29081. }
  29082. var authInHost;
  29083. if (isRelAbs) {
  29084. // it's absolute.
  29085. result.host = (relative.host || relative.host === '') ?
  29086. relative.host : result.host;
  29087. result.hostname = (relative.hostname || relative.hostname === '') ?
  29088. relative.hostname : result.hostname;
  29089. result.search = relative.search;
  29090. result.query = relative.query;
  29091. srcPath = relPath;
  29092. // fall through to the dot-handling below.
  29093. } else if (relPath.length) {
  29094. // it's relative
  29095. // throw away the existing file, and take the new path instead.
  29096. if (!srcPath) srcPath = [];
  29097. srcPath.pop();
  29098. srcPath = srcPath.concat(relPath);
  29099. result.search = relative.search;
  29100. result.query = relative.query;
  29101. } else if (!isNullOrUndefined(relative.search)) {
  29102. // just pull out the search.
  29103. // like href='?foo'.
  29104. // Put this after the other two cases because it simplifies the booleans
  29105. if (psychotic) {
  29106. result.hostname = result.host = srcPath.shift();
  29107. //occationaly the auth can get stuck only in host
  29108. //this especially happens in cases like
  29109. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  29110. authInHost = result.host && result.host.indexOf('@') > 0 ?
  29111. result.host.split('@') : false;
  29112. if (authInHost) {
  29113. result.auth = authInHost.shift();
  29114. result.host = result.hostname = authInHost.shift();
  29115. }
  29116. }
  29117. result.search = relative.search;
  29118. result.query = relative.query;
  29119. //to support http.request
  29120. if (!isNull(result.pathname) || !isNull(result.search)) {
  29121. result.path = (result.pathname ? result.pathname : '') +
  29122. (result.search ? result.search : '');
  29123. }
  29124. result.href = result.format();
  29125. return result;
  29126. }
  29127. if (!srcPath.length) {
  29128. // no path at all. easy.
  29129. // we've already handled the other stuff above.
  29130. result.pathname = null;
  29131. //to support http.request
  29132. if (result.search) {
  29133. result.path = '/' + result.search;
  29134. } else {
  29135. result.path = null;
  29136. }
  29137. result.href = result.format();
  29138. return result;
  29139. }
  29140. // if a url ENDs in . or .., then it must get a trailing slash.
  29141. // however, if it ends in anything else non-slashy,
  29142. // then it must NOT get a trailing slash.
  29143. var last = srcPath.slice(-1)[0];
  29144. var hasTrailingSlash = (
  29145. (result.host || relative.host || srcPath.length > 1) &&
  29146. (last === '.' || last === '..') || last === '');
  29147. // strip single dots, resolve double dots to parent dir
  29148. // if the path tries to go above the root, `up` ends up > 0
  29149. var up = 0;
  29150. for (var i = srcPath.length; i >= 0; i--) {
  29151. last = srcPath[i];
  29152. if (last === '.') {
  29153. srcPath.splice(i, 1);
  29154. } else if (last === '..') {
  29155. srcPath.splice(i, 1);
  29156. up++;
  29157. } else if (up) {
  29158. srcPath.splice(i, 1);
  29159. up--;
  29160. }
  29161. }
  29162. // if the path is allowed to go above the root, restore leading ..s
  29163. if (!mustEndAbs && !removeAllDots) {
  29164. for (; up--; up) {
  29165. srcPath.unshift('..');
  29166. }
  29167. }
  29168. if (mustEndAbs && srcPath[0] !== '' &&
  29169. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  29170. srcPath.unshift('');
  29171. }
  29172. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  29173. srcPath.push('');
  29174. }
  29175. var isAbsolute = srcPath[0] === '' ||
  29176. (srcPath[0] && srcPath[0].charAt(0) === '/');
  29177. // put the host back
  29178. if (psychotic) {
  29179. result.hostname = result.host = isAbsolute ? '' :
  29180. srcPath.length ? srcPath.shift() : '';
  29181. //occationaly the auth can get stuck only in host
  29182. //this especially happens in cases like
  29183. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  29184. authInHost = result.host && result.host.indexOf('@') > 0 ?
  29185. result.host.split('@') : false;
  29186. if (authInHost) {
  29187. result.auth = authInHost.shift();
  29188. result.host = result.hostname = authInHost.shift();
  29189. }
  29190. }
  29191. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  29192. if (mustEndAbs && !isAbsolute) {
  29193. srcPath.unshift('');
  29194. }
  29195. if (!srcPath.length) {
  29196. result.pathname = null;
  29197. result.path = null;
  29198. } else {
  29199. result.pathname = srcPath.join('/');
  29200. }
  29201. //to support request.http
  29202. if (!isNull(result.pathname) || !isNull(result.search)) {
  29203. result.path = (result.pathname ? result.pathname : '') +
  29204. (result.search ? result.search : '');
  29205. }
  29206. result.auth = relative.auth || result.auth;
  29207. result.slashes = result.slashes || relative.slashes;
  29208. result.href = result.format();
  29209. return result;
  29210. };
  29211. Url.prototype.parseHost = function() {
  29212. return parseHost(this);
  29213. };
  29214. function parseHost(self) {
  29215. var host = self.host;
  29216. var port = portPattern.exec(host);
  29217. if (port) {
  29218. port = port[0];
  29219. if (port !== ':') {
  29220. self.port = port.substr(1);
  29221. }
  29222. host = host.substr(0, host.length - port.length);
  29223. }
  29224. if (host) self.hostname = host;
  29225. }
  29226. var _polyfillNode_url$1 = /*#__PURE__*/Object.freeze({
  29227. __proto__: null,
  29228. URL: URL$1,
  29229. URLSearchParams: URLSearchParams,
  29230. Url: Url,
  29231. default: _polyfillNode_url,
  29232. fileURLToPath: urlFileURLToPath,
  29233. format: urlFormat,
  29234. parse: urlParse,
  29235. resolve: urlResolve,
  29236. resolveObject: urlResolveObject
  29237. });
  29238. function isRelativeUrl(url) {
  29239. const firstChar = url.charAt(0);
  29240. return firstChar === '.' || firstChar === '~' || firstChar === '@';
  29241. }
  29242. const externalRE = /^(https?:)?\/\//;
  29243. function isExternalUrl(url) {
  29244. return externalRE.test(url);
  29245. }
  29246. const dataUrlRE = /^\s*data:/i;
  29247. function isDataUrl(url) {
  29248. return dataUrlRE.test(url);
  29249. }
  29250. /**
  29251. * Parses string url into URL object.
  29252. */
  29253. function parseUrl(url) {
  29254. const firstChar = url.charAt(0);
  29255. if (firstChar === '~') {
  29256. const secondChar = url.charAt(1);
  29257. url = url.slice(secondChar === '/' ? 2 : 1);
  29258. }
  29259. return parseUriParts(url);
  29260. }
  29261. /**
  29262. * vuejs/component-compiler-utils#22 Support uri fragment in transformed require
  29263. * @param urlString an url as a string
  29264. */
  29265. function parseUriParts(urlString) {
  29266. // A TypeError is thrown if urlString is not a string
  29267. // @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
  29268. return urlParse(isString$2(urlString) ? urlString : '', false, true);
  29269. }
  29270. const defaultAssetUrlOptions = {
  29271. base: null,
  29272. includeAbsolute: false,
  29273. tags: {
  29274. video: ['src', 'poster'],
  29275. source: ['src'],
  29276. img: ['src'],
  29277. image: ['xlink:href', 'href'],
  29278. use: ['xlink:href', 'href']
  29279. }
  29280. };
  29281. const normalizeOptions = (options) => {
  29282. if (Object.keys(options).some(key => isArray$3(options[key]))) {
  29283. // legacy option format which directly passes in tags config
  29284. return Object.assign(Object.assign({}, defaultAssetUrlOptions), { tags: options });
  29285. }
  29286. return Object.assign(Object.assign({}, defaultAssetUrlOptions), options);
  29287. };
  29288. const createAssetUrlTransformWithOptions = (options) => {
  29289. return (node, context) => transformAssetUrl(node, context, options);
  29290. };
  29291. /**
  29292. * A `@vue/compiler-core` plugin that transforms relative asset urls into
  29293. * either imports or absolute urls.
  29294. *
  29295. * ``` js
  29296. * // Before
  29297. * createVNode('img', { src: './logo.png' })
  29298. *
  29299. * // After
  29300. * import _imports_0 from './logo.png'
  29301. * createVNode('img', { src: _imports_0 })
  29302. * ```
  29303. */
  29304. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  29305. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  29306. if (!node.props.length) {
  29307. return;
  29308. }
  29309. const tags = options.tags || defaultAssetUrlOptions.tags;
  29310. const attrs = tags[node.tag];
  29311. const wildCardAttrs = tags['*'];
  29312. if (!attrs && !wildCardAttrs) {
  29313. return;
  29314. }
  29315. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  29316. node.props.forEach((attr, index) => {
  29317. if (attr.type !== 6 /* NodeTypes.ATTRIBUTE */ ||
  29318. !assetAttrs.includes(attr.name) ||
  29319. !attr.value ||
  29320. isExternalUrl(attr.value.content) ||
  29321. isDataUrl(attr.value.content) ||
  29322. attr.value.content[0] === '#' ||
  29323. (!options.includeAbsolute && !isRelativeUrl(attr.value.content))) {
  29324. return;
  29325. }
  29326. const url = parseUrl(attr.value.content);
  29327. if (options.base && attr.value.content[0] === '.') {
  29328. // explicit base - directly rewrite relative urls into absolute url
  29329. // to avoid generating extra imports
  29330. // Allow for full hostnames provided in options.base
  29331. const base = parseUrl(options.base);
  29332. const protocol = base.protocol || '';
  29333. const host = base.host ? protocol + '//' + base.host : '';
  29334. const basePath = base.path || '/';
  29335. // when packaged in the browser, path will be using the posix-
  29336. // only version provided by rollup-plugin-node-builtins.
  29337. attr.value.content =
  29338. host +
  29339. (path.posix || path).join(basePath, url.path + (url.hash || ''));
  29340. return;
  29341. }
  29342. // otherwise, transform the url into an import.
  29343. // this assumes a bundler will resolve the import into the correct
  29344. // absolute url (e.g. webpack file-loader)
  29345. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  29346. node.props[index] = {
  29347. type: 7 /* NodeTypes.DIRECTIVE */,
  29348. name: 'bind',
  29349. arg: createSimpleExpression(attr.name, true, attr.loc),
  29350. exp,
  29351. modifiers: [],
  29352. loc: attr.loc
  29353. };
  29354. });
  29355. }
  29356. };
  29357. function getImportsExpressionExp(path, hash, loc, context) {
  29358. if (path) {
  29359. let name;
  29360. let exp;
  29361. const existingIndex = context.imports.findIndex(i => i.path === path);
  29362. if (existingIndex > -1) {
  29363. name = `_imports_${existingIndex}`;
  29364. exp = context.imports[existingIndex].exp;
  29365. }
  29366. else {
  29367. name = `_imports_${context.imports.length}`;
  29368. exp = createSimpleExpression(name, false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29369. context.imports.push({ exp, path });
  29370. }
  29371. if (!hash) {
  29372. return exp;
  29373. }
  29374. const hashExp = `${name} + '${hash}'`;
  29375. const finalExp = createSimpleExpression(hashExp, false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29376. if (!context.hoistStatic) {
  29377. return finalExp;
  29378. }
  29379. const existingHoistIndex = context.hoists.findIndex(h => {
  29380. return (h &&
  29381. h.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  29382. !h.isStatic &&
  29383. h.content === hashExp);
  29384. });
  29385. if (existingHoistIndex > -1) {
  29386. return createSimpleExpression(`_hoisted_${existingHoistIndex + 1}`, false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29387. }
  29388. return context.hoist(finalExp);
  29389. }
  29390. else {
  29391. return createSimpleExpression(`''`, false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29392. }
  29393. }
  29394. const srcsetTags = ['img', 'source'];
  29395. // http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
  29396. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  29397. const createSrcsetTransformWithOptions = (options) => {
  29398. return (node, context) => transformSrcset(node, context, options);
  29399. };
  29400. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  29401. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  29402. if (srcsetTags.includes(node.tag) && node.props.length) {
  29403. node.props.forEach((attr, index) => {
  29404. if (attr.name === 'srcset' && attr.type === 6 /* NodeTypes.ATTRIBUTE */) {
  29405. if (!attr.value)
  29406. return;
  29407. const value = attr.value.content;
  29408. if (!value)
  29409. return;
  29410. const imageCandidates = value.split(',').map(s => {
  29411. // The attribute value arrives here with all whitespace, except
  29412. // normal spaces, represented by escape sequences
  29413. const [url, descriptor] = s
  29414. .replace(escapedSpaceCharacters, ' ')
  29415. .trim()
  29416. .split(' ', 2);
  29417. return { url, descriptor };
  29418. });
  29419. // data urls contains comma after the encoding so we need to re-merge
  29420. // them
  29421. for (let i = 0; i < imageCandidates.length; i++) {
  29422. const { url } = imageCandidates[i];
  29423. if (isDataUrl(url)) {
  29424. imageCandidates[i + 1].url =
  29425. url + ',' + imageCandidates[i + 1].url;
  29426. imageCandidates.splice(i, 1);
  29427. }
  29428. }
  29429. const shouldProcessUrl = (url) => {
  29430. return (!isExternalUrl(url) &&
  29431. !isDataUrl(url) &&
  29432. (options.includeAbsolute || isRelativeUrl(url)));
  29433. };
  29434. // When srcset does not contain any qualified URLs, skip transforming
  29435. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  29436. return;
  29437. }
  29438. if (options.base) {
  29439. const base = options.base;
  29440. const set = [];
  29441. let needImportTransform = false;
  29442. imageCandidates.forEach(candidate => {
  29443. let { url, descriptor } = candidate;
  29444. descriptor = descriptor ? ` ${descriptor}` : ``;
  29445. if (url[0] === '.') {
  29446. candidate.url = (path.posix || path).join(base, url);
  29447. set.push(candidate.url + descriptor);
  29448. }
  29449. else if (shouldProcessUrl(url)) {
  29450. needImportTransform = true;
  29451. }
  29452. else {
  29453. set.push(url + descriptor);
  29454. }
  29455. });
  29456. if (!needImportTransform) {
  29457. attr.value.content = set.join(', ');
  29458. return;
  29459. }
  29460. }
  29461. const compoundExpression = createCompoundExpression([], attr.loc);
  29462. imageCandidates.forEach(({ url, descriptor }, index) => {
  29463. if (shouldProcessUrl(url)) {
  29464. const { path } = parseUrl(url);
  29465. let exp;
  29466. if (path) {
  29467. const existingImportsIndex = context.imports.findIndex(i => i.path === path);
  29468. if (existingImportsIndex > -1) {
  29469. exp = createSimpleExpression(`_imports_${existingImportsIndex}`, false, attr.loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29470. }
  29471. else {
  29472. exp = createSimpleExpression(`_imports_${context.imports.length}`, false, attr.loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29473. context.imports.push({ exp, path });
  29474. }
  29475. compoundExpression.children.push(exp);
  29476. }
  29477. }
  29478. else {
  29479. const exp = createSimpleExpression(`"${url}"`, false, attr.loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29480. compoundExpression.children.push(exp);
  29481. }
  29482. const isNotLast = imageCandidates.length - 1 > index;
  29483. if (descriptor && isNotLast) {
  29484. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  29485. }
  29486. else if (descriptor) {
  29487. compoundExpression.children.push(` + ' ${descriptor}'`);
  29488. }
  29489. else if (isNotLast) {
  29490. compoundExpression.children.push(` + ', ' + `);
  29491. }
  29492. });
  29493. let exp = compoundExpression;
  29494. if (context.hoistStatic) {
  29495. exp = context.hoist(compoundExpression);
  29496. exp.constType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  29497. }
  29498. node.props[index] = {
  29499. type: 7 /* NodeTypes.DIRECTIVE */,
  29500. name: 'bind',
  29501. arg: createSimpleExpression('srcset', true, attr.loc),
  29502. exp,
  29503. modifiers: [],
  29504. loc: attr.loc
  29505. };
  29506. }
  29507. });
  29508. }
  29509. }
  29510. };
  29511. const SSR_INTERPOLATE = Symbol(`ssrInterpolate`);
  29512. const SSR_RENDER_VNODE = Symbol(`ssrRenderVNode`);
  29513. const SSR_RENDER_COMPONENT = Symbol(`ssrRenderComponent`);
  29514. const SSR_RENDER_SLOT = Symbol(`ssrRenderSlot`);
  29515. const SSR_RENDER_SLOT_INNER = Symbol(`ssrRenderSlotInner`);
  29516. const SSR_RENDER_CLASS = Symbol(`ssrRenderClass`);
  29517. const SSR_RENDER_STYLE = Symbol(`ssrRenderStyle`);
  29518. const SSR_RENDER_ATTRS = Symbol(`ssrRenderAttrs`);
  29519. const SSR_RENDER_ATTR = Symbol(`ssrRenderAttr`);
  29520. const SSR_RENDER_DYNAMIC_ATTR = Symbol(`ssrRenderDynamicAttr`);
  29521. const SSR_RENDER_LIST = Symbol(`ssrRenderList`);
  29522. const SSR_INCLUDE_BOOLEAN_ATTR = Symbol(`ssrIncludeBooleanAttr`);
  29523. const SSR_LOOSE_EQUAL = Symbol(`ssrLooseEqual`);
  29524. const SSR_LOOSE_CONTAIN = Symbol(`ssrLooseContain`);
  29525. const SSR_RENDER_DYNAMIC_MODEL = Symbol(`ssrRenderDynamicModel`);
  29526. const SSR_GET_DYNAMIC_MODEL_PROPS = Symbol(`ssrGetDynamicModelProps`);
  29527. const SSR_RENDER_TELEPORT = Symbol(`ssrRenderTeleport`);
  29528. const SSR_RENDER_SUSPENSE = Symbol(`ssrRenderSuspense`);
  29529. const SSR_GET_DIRECTIVE_PROPS = Symbol(`ssrGetDirectiveProps`);
  29530. const ssrHelpers = {
  29531. [SSR_INTERPOLATE]: `ssrInterpolate`,
  29532. [SSR_RENDER_VNODE]: `ssrRenderVNode`,
  29533. [SSR_RENDER_COMPONENT]: `ssrRenderComponent`,
  29534. [SSR_RENDER_SLOT]: `ssrRenderSlot`,
  29535. [SSR_RENDER_SLOT_INNER]: `ssrRenderSlotInner`,
  29536. [SSR_RENDER_CLASS]: `ssrRenderClass`,
  29537. [SSR_RENDER_STYLE]: `ssrRenderStyle`,
  29538. [SSR_RENDER_ATTRS]: `ssrRenderAttrs`,
  29539. [SSR_RENDER_ATTR]: `ssrRenderAttr`,
  29540. [SSR_RENDER_DYNAMIC_ATTR]: `ssrRenderDynamicAttr`,
  29541. [SSR_RENDER_LIST]: `ssrRenderList`,
  29542. [SSR_INCLUDE_BOOLEAN_ATTR]: `ssrIncludeBooleanAttr`,
  29543. [SSR_LOOSE_EQUAL]: `ssrLooseEqual`,
  29544. [SSR_LOOSE_CONTAIN]: `ssrLooseContain`,
  29545. [SSR_RENDER_DYNAMIC_MODEL]: `ssrRenderDynamicModel`,
  29546. [SSR_GET_DYNAMIC_MODEL_PROPS]: `ssrGetDynamicModelProps`,
  29547. [SSR_RENDER_TELEPORT]: `ssrRenderTeleport`,
  29548. [SSR_RENDER_SUSPENSE]: `ssrRenderSuspense`,
  29549. [SSR_GET_DIRECTIVE_PROPS]: `ssrGetDirectiveProps`
  29550. };
  29551. // Note: these are helpers imported from @vue/server-renderer
  29552. // make sure the names match!
  29553. registerRuntimeHelpers(ssrHelpers);
  29554. // Plugin for the first transform pass, which simply constructs the AST node
  29555. const ssrTransformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, processIf);
  29556. // This is called during the 2nd transform pass to construct the SSR-specific
  29557. // codegen nodes.
  29558. function ssrProcessIf(node, context, disableNestedFragments = false) {
  29559. const [rootBranch] = node.branches;
  29560. const ifStatement = createIfStatement(rootBranch.condition, processIfBranch(rootBranch, context, disableNestedFragments));
  29561. context.pushStatement(ifStatement);
  29562. let currentIf = ifStatement;
  29563. for (let i = 1; i < node.branches.length; i++) {
  29564. const branch = node.branches[i];
  29565. const branchBlockStatement = processIfBranch(branch, context, disableNestedFragments);
  29566. if (branch.condition) {
  29567. // else-if
  29568. currentIf = currentIf.alternate = createIfStatement(branch.condition, branchBlockStatement);
  29569. }
  29570. else {
  29571. // else
  29572. currentIf.alternate = branchBlockStatement;
  29573. }
  29574. }
  29575. if (!currentIf.alternate) {
  29576. currentIf.alternate = createBlockStatement([
  29577. createCallExpression(`_push`, ['`<!---->`'])
  29578. ]);
  29579. }
  29580. }
  29581. function processIfBranch(branch, context, disableNestedFragments = false) {
  29582. const { children } = branch;
  29583. const needFragmentWrapper = !disableNestedFragments &&
  29584. (children.length !== 1 || children[0].type !== 1 /* NodeTypes.ELEMENT */) &&
  29585. // optimize away nested fragments when the only child is a ForNode
  29586. !(children.length === 1 && children[0].type === 11 /* NodeTypes.FOR */);
  29587. return processChildrenAsStatement(branch, context, needFragmentWrapper);
  29588. }
  29589. // Plugin for the first transform pass, which simply constructs the AST node
  29590. const ssrTransformFor = createStructuralDirectiveTransform('for', processFor);
  29591. // This is called during the 2nd transform pass to construct the SSR-specific
  29592. // codegen nodes.
  29593. function ssrProcessFor(node, context, disableNestedFragments = false) {
  29594. const needFragmentWrapper = !disableNestedFragments &&
  29595. (node.children.length !== 1 || node.children[0].type !== 1 /* NodeTypes.ELEMENT */);
  29596. const renderLoop = createFunctionExpression(createForLoopParams(node.parseResult));
  29597. renderLoop.body = processChildrenAsStatement(node, context, needFragmentWrapper);
  29598. // v-for always renders a fragment unless explicitly disabled
  29599. if (!disableNestedFragments) {
  29600. context.pushStringPart(`<!--[-->`);
  29601. }
  29602. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_LIST), [
  29603. node.source,
  29604. renderLoop
  29605. ]));
  29606. if (!disableNestedFragments) {
  29607. context.pushStringPart(`<!--]-->`);
  29608. }
  29609. }
  29610. const ssrTransformSlotOutlet = (node, context) => {
  29611. if (isSlotOutlet(node)) {
  29612. const { slotName, slotProps } = processSlotOutlet(node, context);
  29613. const args = [
  29614. `_ctx.$slots`,
  29615. slotName,
  29616. slotProps || `{}`,
  29617. // fallback content placeholder. will be replaced in the process phase
  29618. `null`,
  29619. `_push`,
  29620. `_parent`
  29621. ];
  29622. // inject slot scope id if current template uses :slotted
  29623. if (context.scopeId && context.slotted !== false) {
  29624. args.push(`"${context.scopeId}-s"`);
  29625. }
  29626. let method = SSR_RENDER_SLOT;
  29627. // #3989
  29628. // check if this is a single slot inside a transition wrapper - since
  29629. // transition will unwrap the slot fragment into a single vnode at runtime,
  29630. // we need to avoid rendering the slot as a fragment.
  29631. const parent = context.parent;
  29632. if (parent &&
  29633. parent.type === 1 /* NodeTypes.ELEMENT */ &&
  29634. parent.tagType === 1 /* ElementTypes.COMPONENT */ &&
  29635. resolveComponentType(parent, context, true) === TRANSITION &&
  29636. parent.children.filter(c => c.type === 1 /* NodeTypes.ELEMENT */).length === 1) {
  29637. method = SSR_RENDER_SLOT_INNER;
  29638. if (!(context.scopeId && context.slotted !== false)) {
  29639. args.push('null');
  29640. }
  29641. args.push('true');
  29642. }
  29643. node.ssrCodegenNode = createCallExpression(context.helper(method), args);
  29644. }
  29645. };
  29646. function ssrProcessSlotOutlet(node, context) {
  29647. const renderCall = node.ssrCodegenNode;
  29648. // has fallback content
  29649. if (node.children.length) {
  29650. const fallbackRenderFn = createFunctionExpression([]);
  29651. fallbackRenderFn.body = processChildrenAsStatement(node, context);
  29652. // _renderSlot(slots, name, props, fallback, ...)
  29653. renderCall.arguments[3] = fallbackRenderFn;
  29654. }
  29655. // Forwarded <slot/>. Merge slot scope ids
  29656. if (context.withSlotScopeId) {
  29657. const slotScopeId = renderCall.arguments[6];
  29658. renderCall.arguments[6] = slotScopeId
  29659. ? `${slotScopeId} + _scopeId`
  29660. : `_scopeId`;
  29661. }
  29662. context.pushStatement(node.ssrCodegenNode);
  29663. }
  29664. function createSSRCompilerError(code, loc) {
  29665. return createCompilerError(code, loc, SSRErrorMessages);
  29666. }
  29667. const SSRErrorMessages = {
  29668. [62 /* SSRErrorCodes.X_SSR_UNSAFE_ATTR_NAME */]: `Unsafe attribute name for SSR.`,
  29669. [63 /* SSRErrorCodes.X_SSR_NO_TELEPORT_TARGET */]: `Missing the 'to' prop on teleport element.`,
  29670. [64 /* SSRErrorCodes.X_SSR_INVALID_AST_NODE */]: `Invalid AST node during SSR transform.`
  29671. };
  29672. // Note: this is a 2nd-pass codegen transform.
  29673. function ssrProcessTeleport(node, context) {
  29674. const targetProp = findProp(node, 'to');
  29675. if (!targetProp) {
  29676. context.onError(createSSRCompilerError(63 /* SSRErrorCodes.X_SSR_NO_TELEPORT_TARGET */, node.loc));
  29677. return;
  29678. }
  29679. let target;
  29680. if (targetProp.type === 6 /* NodeTypes.ATTRIBUTE */) {
  29681. target =
  29682. targetProp.value && createSimpleExpression(targetProp.value.content, true);
  29683. }
  29684. else {
  29685. target = targetProp.exp;
  29686. }
  29687. if (!target) {
  29688. context.onError(createSSRCompilerError(63 /* SSRErrorCodes.X_SSR_NO_TELEPORT_TARGET */, targetProp.loc));
  29689. return;
  29690. }
  29691. const disabledProp = findProp(node, 'disabled', false, true /* allow empty */);
  29692. const disabled = disabledProp
  29693. ? disabledProp.type === 6 /* NodeTypes.ATTRIBUTE */
  29694. ? `true`
  29695. : disabledProp.exp || `false`
  29696. : `false`;
  29697. const contentRenderFn = createFunctionExpression([`_push`], undefined, // Body is added later
  29698. true, // newline
  29699. false, // isSlot
  29700. node.loc);
  29701. contentRenderFn.body = processChildrenAsStatement(node, context);
  29702. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_TELEPORT), [
  29703. `_push`,
  29704. contentRenderFn,
  29705. target,
  29706. disabled,
  29707. `_parent`
  29708. ]));
  29709. }
  29710. const wipMap$2 = new WeakMap();
  29711. // phase 1
  29712. function ssrTransformSuspense(node, context) {
  29713. return () => {
  29714. if (node.children.length) {
  29715. const wipEntry = {
  29716. slotsExp: null,
  29717. wipSlots: []
  29718. };
  29719. wipMap$2.set(node, wipEntry);
  29720. wipEntry.slotsExp = buildSlots(node, context, (_props, children, loc) => {
  29721. const fn = createFunctionExpression([], undefined, // no return, assign body later
  29722. true, // newline
  29723. false, // suspense slots are not treated as normal slots
  29724. loc);
  29725. wipEntry.wipSlots.push({
  29726. fn,
  29727. children
  29728. });
  29729. return fn;
  29730. }).slots;
  29731. }
  29732. };
  29733. }
  29734. // phase 2
  29735. function ssrProcessSuspense(node, context) {
  29736. // complete wip slots with ssr code
  29737. const wipEntry = wipMap$2.get(node);
  29738. if (!wipEntry) {
  29739. return;
  29740. }
  29741. const { slotsExp, wipSlots } = wipEntry;
  29742. for (let i = 0; i < wipSlots.length; i++) {
  29743. const slot = wipSlots[i];
  29744. slot.fn.body = processChildrenAsStatement(slot, context);
  29745. }
  29746. // _push(ssrRenderSuspense(slots))
  29747. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_SUSPENSE), [
  29748. `_push`,
  29749. slotsExp
  29750. ]));
  29751. }
  29752. // for directives with children overwrite (e.g. v-html & v-text), we need to
  29753. // store the raw children so that they can be added in the 2nd pass.
  29754. const rawChildrenMap = new WeakMap();
  29755. const ssrTransformElement = (node, context) => {
  29756. if (node.type !== 1 /* NodeTypes.ELEMENT */ ||
  29757. node.tagType !== 0 /* ElementTypes.ELEMENT */) {
  29758. return;
  29759. }
  29760. return function ssrPostTransformElement() {
  29761. // element
  29762. // generate the template literal representing the open tag.
  29763. const openTag = [`<${node.tag}`];
  29764. // some tags need to be passed to runtime for special checks
  29765. const needTagForRuntime = node.tag === 'textarea' || node.tag.indexOf('-') > 0;
  29766. // v-bind="obj", v-bind:[key] and custom directives can potentially
  29767. // overwrite other static attrs and can affect final rendering result,
  29768. // so when they are present we need to bail out to full `renderAttrs`
  29769. const hasDynamicVBind = hasDynamicKeyVBind(node);
  29770. const hasCustomDir = node.props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && !isBuiltInDirective(p.name));
  29771. const needMergeProps = hasDynamicVBind || hasCustomDir;
  29772. if (needMergeProps) {
  29773. const { props, directives } = buildProps(node, context, node.props, false /* isComponent */, false /* isDynamicComponent */, true /* ssr */);
  29774. if (props || directives.length) {
  29775. const mergedProps = buildSSRProps(props, directives, context);
  29776. const propsExp = createCallExpression(context.helper(SSR_RENDER_ATTRS), [mergedProps]);
  29777. if (node.tag === 'textarea') {
  29778. const existingText = node.children[0];
  29779. // If interpolation, this is dynamic <textarea> content, potentially
  29780. // injected by v-model and takes higher priority than v-bind value
  29781. if (!existingText || existingText.type !== 5 /* NodeTypes.INTERPOLATION */) {
  29782. // <textarea> with dynamic v-bind. We don't know if the final props
  29783. // will contain .value, so we will have to do something special:
  29784. // assign the merged props to a temp variable, and check whether
  29785. // it contains value (if yes, render is as children).
  29786. const tempId = `_temp${context.temps++}`;
  29787. propsExp.arguments = [
  29788. createAssignmentExpression(createSimpleExpression(tempId, false), mergedProps)
  29789. ];
  29790. rawChildrenMap.set(node, createCallExpression(context.helper(SSR_INTERPOLATE), [
  29791. createConditionalExpression(createSimpleExpression(`"value" in ${tempId}`, false), createSimpleExpression(`${tempId}.value`, false), createSimpleExpression(existingText ? existingText.content : ``, true), false)
  29792. ]));
  29793. }
  29794. }
  29795. else if (node.tag === 'input') {
  29796. // <input v-bind="obj" v-model>
  29797. // we need to determine the props to render for the dynamic v-model
  29798. // and merge it with the v-bind expression.
  29799. const vModel = findVModel(node);
  29800. if (vModel) {
  29801. // 1. save the props (san v-model) in a temp variable
  29802. const tempId = `_temp${context.temps++}`;
  29803. const tempExp = createSimpleExpression(tempId, false);
  29804. propsExp.arguments = [
  29805. createSequenceExpression([
  29806. createAssignmentExpression(tempExp, mergedProps),
  29807. createCallExpression(context.helper(MERGE_PROPS), [
  29808. tempExp,
  29809. createCallExpression(context.helper(SSR_GET_DYNAMIC_MODEL_PROPS), [
  29810. tempExp,
  29811. vModel.exp // model
  29812. ])
  29813. ])
  29814. ])
  29815. ];
  29816. }
  29817. }
  29818. if (needTagForRuntime) {
  29819. propsExp.arguments.push(`"${node.tag}"`);
  29820. }
  29821. openTag.push(propsExp);
  29822. }
  29823. }
  29824. // book keeping static/dynamic class merging.
  29825. let dynamicClassBinding = undefined;
  29826. let staticClassBinding = undefined;
  29827. // all style bindings are converted to dynamic by transformStyle.
  29828. // but we need to make sure to merge them.
  29829. let dynamicStyleBinding = undefined;
  29830. for (let i = 0; i < node.props.length; i++) {
  29831. const prop = node.props[i];
  29832. // ignore true-value/false-value on input
  29833. if (node.tag === 'input' && isTrueFalseValue(prop)) {
  29834. continue;
  29835. }
  29836. // special cases with children override
  29837. if (prop.type === 7 /* NodeTypes.DIRECTIVE */) {
  29838. if (prop.name === 'html' && prop.exp) {
  29839. rawChildrenMap.set(node, prop.exp);
  29840. }
  29841. else if (prop.name === 'text' && prop.exp) {
  29842. node.children = [createInterpolation(prop.exp, prop.loc)];
  29843. }
  29844. else if (prop.name === 'slot') {
  29845. context.onError(createCompilerError(40 /* ErrorCodes.X_V_SLOT_MISPLACED */, prop.loc));
  29846. }
  29847. else if (isTextareaWithValue(node, prop) && prop.exp) {
  29848. if (!needMergeProps) {
  29849. node.children = [createInterpolation(prop.exp, prop.loc)];
  29850. }
  29851. }
  29852. else if (!needMergeProps && prop.name !== 'on') {
  29853. // Directive transforms.
  29854. const directiveTransform = context.directiveTransforms[prop.name];
  29855. if (directiveTransform) {
  29856. const { props, ssrTagParts } = directiveTransform(prop, node, context);
  29857. if (ssrTagParts) {
  29858. openTag.push(...ssrTagParts);
  29859. }
  29860. for (let j = 0; j < props.length; j++) {
  29861. const { key, value } = props[j];
  29862. if (isStaticExp(key)) {
  29863. let attrName = key.content;
  29864. // static key attr
  29865. if (attrName === 'key' || attrName === 'ref') {
  29866. continue;
  29867. }
  29868. if (attrName === 'class') {
  29869. openTag.push(` class="`, (dynamicClassBinding = createCallExpression(context.helper(SSR_RENDER_CLASS), [value])), `"`);
  29870. }
  29871. else if (attrName === 'style') {
  29872. if (dynamicStyleBinding) {
  29873. // already has style binding, merge into it.
  29874. mergeCall(dynamicStyleBinding, value);
  29875. }
  29876. else {
  29877. openTag.push(` style="`, (dynamicStyleBinding = createCallExpression(context.helper(SSR_RENDER_STYLE), [value])), `"`);
  29878. }
  29879. }
  29880. else {
  29881. attrName =
  29882. node.tag.indexOf('-') > 0
  29883. ? attrName // preserve raw name on custom elements
  29884. : propsToAttrMap[attrName] || attrName.toLowerCase();
  29885. if (isBooleanAttr(attrName)) {
  29886. openTag.push(createConditionalExpression(createCallExpression(context.helper(SSR_INCLUDE_BOOLEAN_ATTR), [value]), createSimpleExpression(' ' + attrName, true), createSimpleExpression('', true), false /* no newline */));
  29887. }
  29888. else if (isSSRSafeAttrName(attrName)) {
  29889. openTag.push(createCallExpression(context.helper(SSR_RENDER_ATTR), [
  29890. key,
  29891. value
  29892. ]));
  29893. }
  29894. else {
  29895. context.onError(createSSRCompilerError(62 /* SSRErrorCodes.X_SSR_UNSAFE_ATTR_NAME */, key.loc));
  29896. }
  29897. }
  29898. }
  29899. else {
  29900. // dynamic key attr
  29901. // this branch is only encountered for custom directive
  29902. // transforms that returns properties with dynamic keys
  29903. const args = [key, value];
  29904. if (needTagForRuntime) {
  29905. args.push(`"${node.tag}"`);
  29906. }
  29907. openTag.push(createCallExpression(context.helper(SSR_RENDER_DYNAMIC_ATTR), args));
  29908. }
  29909. }
  29910. }
  29911. }
  29912. }
  29913. else {
  29914. // special case: value on <textarea>
  29915. if (node.tag === 'textarea' && prop.name === 'value' && prop.value) {
  29916. rawChildrenMap.set(node, escapeHtml(prop.value.content));
  29917. }
  29918. else if (!needMergeProps) {
  29919. if (prop.name === 'key' || prop.name === 'ref') {
  29920. continue;
  29921. }
  29922. // static prop
  29923. if (prop.name === 'class' && prop.value) {
  29924. staticClassBinding = JSON.stringify(prop.value.content);
  29925. }
  29926. openTag.push(` ${prop.name}` +
  29927. (prop.value ? `="${escapeHtml(prop.value.content)}"` : ``));
  29928. }
  29929. }
  29930. }
  29931. // handle co-existence of dynamic + static class bindings
  29932. if (dynamicClassBinding && staticClassBinding) {
  29933. mergeCall(dynamicClassBinding, staticClassBinding);
  29934. removeStaticBinding(openTag, 'class');
  29935. }
  29936. if (context.scopeId) {
  29937. openTag.push(` ${context.scopeId}`);
  29938. }
  29939. node.ssrCodegenNode = createTemplateLiteral(openTag);
  29940. };
  29941. };
  29942. function buildSSRProps(props, directives, context) {
  29943. let mergePropsArgs = [];
  29944. if (props) {
  29945. if (props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  29946. // already a mergeProps call
  29947. mergePropsArgs = props.arguments;
  29948. }
  29949. else {
  29950. mergePropsArgs.push(props);
  29951. }
  29952. }
  29953. if (directives.length) {
  29954. for (const dir of directives) {
  29955. mergePropsArgs.push(createCallExpression(context.helper(SSR_GET_DIRECTIVE_PROPS), [
  29956. `_ctx`,
  29957. ...buildDirectiveArgs(dir, context).elements
  29958. ]));
  29959. }
  29960. }
  29961. return mergePropsArgs.length > 1
  29962. ? createCallExpression(context.helper(MERGE_PROPS), mergePropsArgs)
  29963. : mergePropsArgs[0];
  29964. }
  29965. function isTrueFalseValue(prop) {
  29966. if (prop.type === 7 /* NodeTypes.DIRECTIVE */) {
  29967. return (prop.name === 'bind' &&
  29968. prop.arg &&
  29969. isStaticExp(prop.arg) &&
  29970. (prop.arg.content === 'true-value' || prop.arg.content === 'false-value'));
  29971. }
  29972. else {
  29973. return prop.name === 'true-value' || prop.name === 'false-value';
  29974. }
  29975. }
  29976. function isTextareaWithValue(node, prop) {
  29977. return !!(node.tag === 'textarea' &&
  29978. prop.name === 'bind' &&
  29979. isStaticArgOf(prop.arg, 'value'));
  29980. }
  29981. function mergeCall(call, arg) {
  29982. const existing = call.arguments[0];
  29983. if (existing.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */) {
  29984. existing.elements.push(arg);
  29985. }
  29986. else {
  29987. call.arguments[0] = createArrayExpression([existing, arg]);
  29988. }
  29989. }
  29990. function removeStaticBinding(tag, binding) {
  29991. const regExp = new RegExp(`^ ${binding}=".+"$`);
  29992. const i = tag.findIndex(e => typeof e === 'string' && regExp.test(e));
  29993. if (i > -1) {
  29994. tag.splice(i, 1);
  29995. }
  29996. }
  29997. function findVModel(node) {
  29998. return node.props.find(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'model' && p.exp);
  29999. }
  30000. function ssrProcessElement(node, context) {
  30001. const isVoidTag = context.options.isVoidTag || NO;
  30002. const elementsToAdd = node.ssrCodegenNode.elements;
  30003. for (let j = 0; j < elementsToAdd.length; j++) {
  30004. context.pushStringPart(elementsToAdd[j]);
  30005. }
  30006. // Handle slot scopeId
  30007. if (context.withSlotScopeId) {
  30008. context.pushStringPart(createSimpleExpression(`_scopeId`, false));
  30009. }
  30010. // close open tag
  30011. context.pushStringPart(`>`);
  30012. const rawChildren = rawChildrenMap.get(node);
  30013. if (rawChildren) {
  30014. context.pushStringPart(rawChildren);
  30015. }
  30016. else if (node.children.length) {
  30017. processChildren(node, context);
  30018. }
  30019. if (!isVoidTag(node.tag)) {
  30020. // push closing tag
  30021. context.pushStringPart(`</${node.tag}>`);
  30022. }
  30023. }
  30024. const wipMap$1 = new WeakMap();
  30025. // phase 1: build props
  30026. function ssrTransformTransitionGroup(node, context) {
  30027. return () => {
  30028. const tag = findProp(node, 'tag');
  30029. if (tag) {
  30030. const otherProps = node.props.filter(p => p !== tag);
  30031. const { props, directives } = buildProps(node, context, otherProps, true /* isComponent */, false /* isDynamicComponent */, true /* ssr (skip event listeners) */);
  30032. let propsExp = null;
  30033. if (props || directives.length) {
  30034. propsExp = createCallExpression(context.helper(SSR_RENDER_ATTRS), [
  30035. buildSSRProps(props, directives, context)
  30036. ]);
  30037. }
  30038. wipMap$1.set(node, {
  30039. tag,
  30040. propsExp
  30041. });
  30042. }
  30043. };
  30044. }
  30045. // phase 2: process children
  30046. function ssrProcessTransitionGroup(node, context) {
  30047. const entry = wipMap$1.get(node);
  30048. if (entry) {
  30049. const { tag, propsExp } = entry;
  30050. if (tag.type === 7 /* NodeTypes.DIRECTIVE */) {
  30051. // dynamic :tag
  30052. context.pushStringPart(`<`);
  30053. context.pushStringPart(tag.exp);
  30054. if (propsExp) {
  30055. context.pushStringPart(propsExp);
  30056. }
  30057. context.pushStringPart(`>`);
  30058. processChildren(node, context, false,
  30059. /**
  30060. * TransitionGroup has the special runtime behavior of flattening and
  30061. * concatenating all children into a single fragment (in order for them to
  30062. * be patched using the same key map) so we need to account for that here
  30063. * by disabling nested fragment wrappers from being generated.
  30064. */
  30065. true);
  30066. context.pushStringPart(`</`);
  30067. context.pushStringPart(tag.exp);
  30068. context.pushStringPart(`>`);
  30069. }
  30070. else {
  30071. // static tag
  30072. context.pushStringPart(`<${tag.value.content}`);
  30073. if (propsExp) {
  30074. context.pushStringPart(propsExp);
  30075. }
  30076. context.pushStringPart(`>`);
  30077. processChildren(node, context, false, true);
  30078. context.pushStringPart(`</${tag.value.content}>`);
  30079. }
  30080. }
  30081. else {
  30082. // fragment
  30083. processChildren(node, context, true, true);
  30084. }
  30085. }
  30086. // We need to construct the slot functions in the 1st pass to ensure proper
  30087. // scope tracking, but the children of each slot cannot be processed until
  30088. // the 2nd pass, so we store the WIP slot functions in a weakMap during the 1st
  30089. // pass and complete them in the 2nd pass.
  30090. const wipMap = new WeakMap();
  30091. const WIP_SLOT = Symbol();
  30092. const componentTypeMap = new WeakMap();
  30093. // ssr component transform is done in two phases:
  30094. // In phase 1. we use `buildSlot` to analyze the children of the component into
  30095. // WIP slot functions (it must be done in phase 1 because `buildSlot` relies on
  30096. // the core transform context).
  30097. // In phase 2. we convert the WIP slots from phase 1 into ssr-specific codegen
  30098. // nodes.
  30099. const ssrTransformComponent = (node, context) => {
  30100. if (node.type !== 1 /* NodeTypes.ELEMENT */ ||
  30101. node.tagType !== 1 /* ElementTypes.COMPONENT */) {
  30102. return;
  30103. }
  30104. const component = resolveComponentType(node, context, true /* ssr */);
  30105. const isDynamicComponent = isObject$2(component) && component.callee === RESOLVE_DYNAMIC_COMPONENT;
  30106. componentTypeMap.set(node, component);
  30107. if (isSymbol$1(component)) {
  30108. if (component === SUSPENSE) {
  30109. return ssrTransformSuspense(node, context);
  30110. }
  30111. if (component === TRANSITION_GROUP) {
  30112. return ssrTransformTransitionGroup(node, context);
  30113. }
  30114. return; // other built-in components: fallthrough
  30115. }
  30116. // Build the fallback vnode-based branch for the component's slots.
  30117. // We need to clone the node into a fresh copy and use the buildSlots' logic
  30118. // to get access to the children of each slot. We then compile them with
  30119. // a child transform pipeline using vnode-based transforms (instead of ssr-
  30120. // based ones), and save the result branch (a ReturnStatement) in an array.
  30121. // The branch is retrieved when processing slots again in ssr mode.
  30122. const vnodeBranches = [];
  30123. const clonedNode = clone(node);
  30124. return function ssrPostTransformComponent() {
  30125. // Using the cloned node, build the normal VNode-based branches (for
  30126. // fallback in case the child is render-fn based). Store them in an array
  30127. // for later use.
  30128. if (clonedNode.children.length) {
  30129. buildSlots(clonedNode, context, (props, children) => {
  30130. vnodeBranches.push(createVNodeSlotBranch(props, children, context));
  30131. return createFunctionExpression(undefined);
  30132. });
  30133. }
  30134. let propsExp = `null`;
  30135. if (node.props.length) {
  30136. // note we are not passing ssr: true here because for components, v-on
  30137. // handlers should still be passed
  30138. const { props, directives } = buildProps(node, context, undefined, true, isDynamicComponent);
  30139. if (props || directives.length) {
  30140. propsExp = buildSSRProps(props, directives, context);
  30141. }
  30142. }
  30143. const wipEntries = [];
  30144. wipMap.set(node, wipEntries);
  30145. const buildSSRSlotFn = (props, children, loc) => {
  30146. const param0 = (props && stringifyExpression(props)) || `_`;
  30147. const fn = createFunctionExpression([param0, `_push`, `_parent`, `_scopeId`], undefined, // no return, assign body later
  30148. true, // newline
  30149. true, // isSlot
  30150. loc);
  30151. wipEntries.push({
  30152. type: WIP_SLOT,
  30153. fn,
  30154. children,
  30155. // also collect the corresponding vnode branch built earlier
  30156. vnodeBranch: vnodeBranches[wipEntries.length]
  30157. });
  30158. return fn;
  30159. };
  30160. const slots = node.children.length
  30161. ? buildSlots(node, context, buildSSRSlotFn).slots
  30162. : `null`;
  30163. if (typeof component !== 'string') {
  30164. // dynamic component that resolved to a `resolveDynamicComponent` call
  30165. // expression - since the resolved result may be a plain element (string)
  30166. // or a VNode, handle it with `renderVNode`.
  30167. node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_VNODE), [
  30168. `_push`,
  30169. createCallExpression(context.helper(CREATE_VNODE), [
  30170. component,
  30171. propsExp,
  30172. slots
  30173. ]),
  30174. `_parent`
  30175. ]);
  30176. }
  30177. else {
  30178. node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_COMPONENT), [component, propsExp, slots, `_parent`]);
  30179. }
  30180. };
  30181. };
  30182. function ssrProcessComponent(node, context, parent) {
  30183. const component = componentTypeMap.get(node);
  30184. if (!node.ssrCodegenNode) {
  30185. // this is a built-in component that fell-through.
  30186. if (component === TELEPORT) {
  30187. return ssrProcessTeleport(node, context);
  30188. }
  30189. else if (component === SUSPENSE) {
  30190. return ssrProcessSuspense(node, context);
  30191. }
  30192. else if (component === TRANSITION_GROUP) {
  30193. return ssrProcessTransitionGroup(node, context);
  30194. }
  30195. else {
  30196. // real fall-through: Transition / KeepAlive
  30197. // just render its children.
  30198. // #5352: if is at root level of a slot, push an empty string.
  30199. // this does not affect the final output, but avoids all-comment slot
  30200. // content of being treated as empty by ssrRenderSlot().
  30201. if (parent.type === WIP_SLOT) {
  30202. context.pushStringPart(``);
  30203. }
  30204. // #5351: filter out comment children inside transition
  30205. if (component === TRANSITION) {
  30206. node.children = node.children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */);
  30207. }
  30208. processChildren(node, context);
  30209. }
  30210. }
  30211. else {
  30212. // finish up slot function expressions from the 1st pass.
  30213. const wipEntries = wipMap.get(node) || [];
  30214. for (let i = 0; i < wipEntries.length; i++) {
  30215. const { fn, vnodeBranch } = wipEntries[i];
  30216. // For each slot, we generate two branches: one SSR-optimized branch and
  30217. // one normal vnode-based branch. The branches are taken based on the
  30218. // presence of the 2nd `_push` argument (which is only present if the slot
  30219. // is called by `_ssrRenderSlot`.
  30220. fn.body = createIfStatement(createSimpleExpression(`_push`, false), processChildrenAsStatement(wipEntries[i], context, false, true /* withSlotScopeId */), vnodeBranch);
  30221. }
  30222. // component is inside a slot, inherit slot scope Id
  30223. if (context.withSlotScopeId) {
  30224. node.ssrCodegenNode.arguments.push(`_scopeId`);
  30225. }
  30226. if (typeof component === 'string') {
  30227. // static component
  30228. context.pushStatement(createCallExpression(`_push`, [node.ssrCodegenNode]));
  30229. }
  30230. else {
  30231. // dynamic component (`resolveDynamicComponent` call)
  30232. // the codegen node is a `renderVNode` call
  30233. context.pushStatement(node.ssrCodegenNode);
  30234. }
  30235. }
  30236. }
  30237. const rawOptionsMap = new WeakMap();
  30238. const [baseNodeTransforms, baseDirectiveTransforms] = getBaseTransformPreset(true);
  30239. const vnodeNodeTransforms = [...baseNodeTransforms, ...DOMNodeTransforms];
  30240. const vnodeDirectiveTransforms = Object.assign(Object.assign({}, baseDirectiveTransforms), DOMDirectiveTransforms);
  30241. function createVNodeSlotBranch(props, children, parentContext) {
  30242. // apply a sub-transform using vnode-based transforms.
  30243. const rawOptions = rawOptionsMap.get(parentContext.root);
  30244. const subOptions = Object.assign(Object.assign({}, rawOptions), {
  30245. // overwrite with vnode-based transforms
  30246. nodeTransforms: [
  30247. ...vnodeNodeTransforms,
  30248. ...(rawOptions.nodeTransforms || [])
  30249. ], directiveTransforms: Object.assign(Object.assign({}, vnodeDirectiveTransforms), (rawOptions.directiveTransforms || {})) });
  30250. // wrap the children with a wrapper template for proper children treatment.
  30251. const wrapperNode = {
  30252. type: 1 /* NodeTypes.ELEMENT */,
  30253. ns: 0 /* Namespaces.HTML */,
  30254. tag: 'template',
  30255. tagType: 3 /* ElementTypes.TEMPLATE */,
  30256. isSelfClosing: false,
  30257. // important: provide v-slot="props" on the wrapper for proper
  30258. // scope analysis
  30259. props: [
  30260. {
  30261. type: 7 /* NodeTypes.DIRECTIVE */,
  30262. name: 'slot',
  30263. exp: props,
  30264. arg: undefined,
  30265. modifiers: [],
  30266. loc: locStub
  30267. }
  30268. ],
  30269. children,
  30270. loc: locStub,
  30271. codegenNode: undefined
  30272. };
  30273. subTransform(wrapperNode, subOptions, parentContext);
  30274. return createReturnStatement(children);
  30275. }
  30276. function subTransform(node, options, parentContext) {
  30277. const childRoot = createRoot([node]);
  30278. const childContext = createTransformContext(childRoot, options);
  30279. // this sub transform is for vnode fallback branch so it should be handled
  30280. // like normal render functions
  30281. childContext.ssr = false;
  30282. // inherit parent scope analysis state
  30283. childContext.scopes = Object.assign({}, parentContext.scopes);
  30284. childContext.identifiers = Object.assign({}, parentContext.identifiers);
  30285. childContext.imports = parentContext.imports;
  30286. // traverse
  30287. traverseNode(childRoot, childContext);
  30288. ['helpers', 'components', 'directives'].forEach(key => {
  30289. childContext[key].forEach((value, helperKey) => {
  30290. if (key === 'helpers') {
  30291. const parentCount = parentContext.helpers.get(helperKey);
  30292. if (parentCount === undefined) {
  30293. parentContext.helpers.set(helperKey, value);
  30294. }
  30295. else {
  30296. parentContext.helpers.set(helperKey, value + parentCount);
  30297. }
  30298. }
  30299. else {
  30300. parentContext[key].add(value);
  30301. }
  30302. });
  30303. });
  30304. // imports/hoists are not merged because:
  30305. // - imports are only used for asset urls and should be consistent between
  30306. // node/client branches
  30307. // - hoists are not enabled for the client branch here
  30308. }
  30309. function clone(v) {
  30310. if (isArray$3(v)) {
  30311. return v.map(clone);
  30312. }
  30313. else if (isObject$2(v)) {
  30314. const res = {};
  30315. for (const key in v) {
  30316. res[key] = clone(v[key]);
  30317. }
  30318. return res;
  30319. }
  30320. else {
  30321. return v;
  30322. }
  30323. }
  30324. // Because SSR codegen output is completely different from client-side output
  30325. // (e.g. multiple elements can be concatenated into a single template literal
  30326. // instead of each getting a corresponding call), we need to apply an extra
  30327. // transform pass to convert the template AST into a fresh JS AST before
  30328. // passing it to codegen.
  30329. function ssrCodegenTransform(ast, options) {
  30330. const context = createSSRTransformContext(ast, options);
  30331. // inject SFC <style> CSS variables
  30332. // we do this instead of inlining the expression to ensure the vars are
  30333. // only resolved once per render
  30334. if (options.ssrCssVars) {
  30335. const cssContext = createTransformContext(createRoot([]), options);
  30336. const varsExp = processExpression(createSimpleExpression(options.ssrCssVars, false), cssContext);
  30337. context.body.push(createCompoundExpression([`const _cssVars = { style: `, varsExp, `}`]));
  30338. Array.from(cssContext.helpers.keys()).forEach(helper => {
  30339. ast.helpers.add(helper);
  30340. });
  30341. }
  30342. const isFragment = ast.children.length > 1 && ast.children.some(c => !isText$1(c));
  30343. processChildren(ast, context, isFragment);
  30344. ast.codegenNode = createBlockStatement(context.body);
  30345. // Finalize helpers.
  30346. // We need to separate helpers imported from 'vue' vs. '@vue/server-renderer'
  30347. ast.ssrHelpers = Array.from(new Set([
  30348. ...Array.from(ast.helpers).filter(h => h in ssrHelpers),
  30349. ...context.helpers
  30350. ]));
  30351. ast.helpers = new Set(Array.from(ast.helpers).filter(h => !(h in ssrHelpers)));
  30352. }
  30353. function createSSRTransformContext(root, options, helpers = new Set(), withSlotScopeId = false) {
  30354. const body = [];
  30355. let currentString = null;
  30356. return {
  30357. root,
  30358. options,
  30359. body,
  30360. helpers,
  30361. withSlotScopeId,
  30362. onError: options.onError ||
  30363. (e => {
  30364. throw e;
  30365. }),
  30366. helper(name) {
  30367. helpers.add(name);
  30368. return name;
  30369. },
  30370. pushStringPart(part) {
  30371. if (!currentString) {
  30372. const currentCall = createCallExpression(`_push`);
  30373. body.push(currentCall);
  30374. currentString = createTemplateLiteral([]);
  30375. currentCall.arguments.push(currentString);
  30376. }
  30377. const bufferedElements = currentString.elements;
  30378. const lastItem = bufferedElements[bufferedElements.length - 1];
  30379. if (isString$2(part) && isString$2(lastItem)) {
  30380. bufferedElements[bufferedElements.length - 1] += part;
  30381. }
  30382. else {
  30383. bufferedElements.push(part);
  30384. }
  30385. },
  30386. pushStatement(statement) {
  30387. // close current string
  30388. currentString = null;
  30389. body.push(statement);
  30390. }
  30391. };
  30392. }
  30393. function createChildContext(parent, withSlotScopeId = parent.withSlotScopeId) {
  30394. // ensure child inherits parent helpers
  30395. return createSSRTransformContext(parent.root, parent.options, parent.helpers, withSlotScopeId);
  30396. }
  30397. function processChildren(parent, context, asFragment = false, disableNestedFragments = false) {
  30398. if (asFragment) {
  30399. context.pushStringPart(`<!--[-->`);
  30400. }
  30401. const { children } = parent;
  30402. for (let i = 0; i < children.length; i++) {
  30403. const child = children[i];
  30404. switch (child.type) {
  30405. case 1 /* NodeTypes.ELEMENT */:
  30406. switch (child.tagType) {
  30407. case 0 /* ElementTypes.ELEMENT */:
  30408. ssrProcessElement(child, context);
  30409. break;
  30410. case 1 /* ElementTypes.COMPONENT */:
  30411. ssrProcessComponent(child, context, parent);
  30412. break;
  30413. case 2 /* ElementTypes.SLOT */:
  30414. ssrProcessSlotOutlet(child, context);
  30415. break;
  30416. case 3 /* ElementTypes.TEMPLATE */:
  30417. // TODO
  30418. break;
  30419. default:
  30420. context.onError(createSSRCompilerError(64 /* SSRErrorCodes.X_SSR_INVALID_AST_NODE */, child.loc));
  30421. // make sure we exhaust all possible types
  30422. const exhaustiveCheck = child;
  30423. return exhaustiveCheck;
  30424. }
  30425. break;
  30426. case 2 /* NodeTypes.TEXT */:
  30427. context.pushStringPart(escapeHtml(child.content));
  30428. break;
  30429. case 3 /* NodeTypes.COMMENT */:
  30430. // no need to escape comment here because the AST can only
  30431. // contain valid comments.
  30432. context.pushStringPart(`<!--${child.content}-->`);
  30433. break;
  30434. case 5 /* NodeTypes.INTERPOLATION */:
  30435. context.pushStringPart(createCallExpression(context.helper(SSR_INTERPOLATE), [child.content]));
  30436. break;
  30437. case 9 /* NodeTypes.IF */:
  30438. ssrProcessIf(child, context, disableNestedFragments);
  30439. break;
  30440. case 11 /* NodeTypes.FOR */:
  30441. ssrProcessFor(child, context, disableNestedFragments);
  30442. break;
  30443. case 10 /* NodeTypes.IF_BRANCH */:
  30444. // no-op - handled by ssrProcessIf
  30445. break;
  30446. case 12 /* NodeTypes.TEXT_CALL */:
  30447. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  30448. // no-op - these two types can never appear as template child node since
  30449. // `transformText` is not used during SSR compile.
  30450. break;
  30451. default:
  30452. context.onError(createSSRCompilerError(64 /* SSRErrorCodes.X_SSR_INVALID_AST_NODE */, child.loc));
  30453. // make sure we exhaust all possible types
  30454. const exhaustiveCheck = child;
  30455. return exhaustiveCheck;
  30456. }
  30457. }
  30458. if (asFragment) {
  30459. context.pushStringPart(`<!--]-->`);
  30460. }
  30461. }
  30462. function processChildrenAsStatement(parent, parentContext, asFragment = false, withSlotScopeId = parentContext.withSlotScopeId) {
  30463. const childContext = createChildContext(parentContext, withSlotScopeId);
  30464. processChildren(parent, childContext, asFragment);
  30465. return createBlockStatement(childContext.body);
  30466. }
  30467. const ssrTransformModel = (dir, node, context) => {
  30468. const model = dir.exp;
  30469. function checkDuplicatedValue() {
  30470. const value = findProp(node, 'value');
  30471. if (value) {
  30472. context.onError(createDOMCompilerError(58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  30473. }
  30474. }
  30475. if (node.tagType === 0 /* ElementTypes.ELEMENT */) {
  30476. const res = { props: [] };
  30477. const defaultProps = [
  30478. // default value binding for text type inputs
  30479. createObjectProperty(`value`, model)
  30480. ];
  30481. if (node.tag === 'input') {
  30482. const type = findProp(node, 'type');
  30483. if (type) {
  30484. const value = findValueBinding(node);
  30485. if (type.type === 7 /* NodeTypes.DIRECTIVE */) {
  30486. // dynamic type
  30487. res.ssrTagParts = [
  30488. createCallExpression(context.helper(SSR_RENDER_DYNAMIC_MODEL), [
  30489. type.exp,
  30490. model,
  30491. value
  30492. ])
  30493. ];
  30494. }
  30495. else if (type.value) {
  30496. // static type
  30497. switch (type.value.content) {
  30498. case 'radio':
  30499. res.props = [
  30500. createObjectProperty(`checked`, createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  30501. model,
  30502. value
  30503. ]))
  30504. ];
  30505. break;
  30506. case 'checkbox':
  30507. const trueValueBinding = findProp(node, 'true-value');
  30508. if (trueValueBinding) {
  30509. const trueValue = trueValueBinding.type === 6 /* NodeTypes.ATTRIBUTE */
  30510. ? JSON.stringify(trueValueBinding.value.content)
  30511. : trueValueBinding.exp;
  30512. res.props = [
  30513. createObjectProperty(`checked`, createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  30514. model,
  30515. trueValue
  30516. ]))
  30517. ];
  30518. }
  30519. else {
  30520. res.props = [
  30521. createObjectProperty(`checked`, createConditionalExpression(createCallExpression(`Array.isArray`, [model]), createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [
  30522. model,
  30523. value
  30524. ]), model))
  30525. ];
  30526. }
  30527. break;
  30528. case 'file':
  30529. context.onError(createDOMCompilerError(57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  30530. break;
  30531. default:
  30532. checkDuplicatedValue();
  30533. res.props = defaultProps;
  30534. break;
  30535. }
  30536. }
  30537. }
  30538. else if (hasDynamicKeyVBind(node)) ;
  30539. else {
  30540. // text type
  30541. checkDuplicatedValue();
  30542. res.props = defaultProps;
  30543. }
  30544. }
  30545. else if (node.tag === 'textarea') {
  30546. checkDuplicatedValue();
  30547. node.children = [createInterpolation(model, model.loc)];
  30548. }
  30549. else if (node.tag === 'select') ;
  30550. else {
  30551. context.onError(createDOMCompilerError(55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  30552. }
  30553. return res;
  30554. }
  30555. else {
  30556. // component v-model
  30557. return transformModel$1(dir, node, context);
  30558. }
  30559. };
  30560. function findValueBinding(node) {
  30561. const valueBinding = findProp(node, 'value');
  30562. return valueBinding
  30563. ? valueBinding.type === 7 /* NodeTypes.DIRECTIVE */
  30564. ? valueBinding.exp
  30565. : createSimpleExpression(valueBinding.value.content, true)
  30566. : createSimpleExpression(`null`, false);
  30567. }
  30568. const ssrTransformShow = (dir, node, context) => {
  30569. if (!dir.exp) {
  30570. context.onError(createDOMCompilerError(59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */));
  30571. }
  30572. return {
  30573. props: [
  30574. createObjectProperty(`style`, createConditionalExpression(dir.exp, createSimpleExpression(`null`, false), createObjectExpression([
  30575. createObjectProperty(`display`, createSimpleExpression(`none`, true))
  30576. ]), false /* no newline */))
  30577. ]
  30578. };
  30579. };
  30580. const filterChild = (node) => node.children.filter(n => n.type !== 3 /* NodeTypes.COMMENT */);
  30581. const hasSingleChild = (node) => filterChild(node).length === 1;
  30582. const ssrInjectFallthroughAttrs = (node, context) => {
  30583. // _attrs is provided as a function argument.
  30584. // mark it as a known identifier so that it doesn't get prefixed by
  30585. // transformExpression.
  30586. if (node.type === 0 /* NodeTypes.ROOT */) {
  30587. context.identifiers._attrs = 1;
  30588. }
  30589. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  30590. node.tagType === 1 /* ElementTypes.COMPONENT */ &&
  30591. (isBuiltInType(node.tag, 'Transition') ||
  30592. isBuiltInType(node.tag, 'KeepAlive'))) {
  30593. const rootChildren = filterChild(context.root);
  30594. if (rootChildren.length === 1 && rootChildren[0] === node) {
  30595. if (hasSingleChild(node)) {
  30596. injectFallthroughAttrs(node.children[0]);
  30597. }
  30598. return;
  30599. }
  30600. }
  30601. const parent = context.parent;
  30602. if (!parent || parent.type !== 0 /* NodeTypes.ROOT */) {
  30603. return;
  30604. }
  30605. if (node.type === 10 /* NodeTypes.IF_BRANCH */ && hasSingleChild(node)) {
  30606. // detect cases where the parent v-if is not the only root level node
  30607. let hasEncounteredIf = false;
  30608. for (const c of filterChild(parent)) {
  30609. if (c.type === 9 /* NodeTypes.IF */ ||
  30610. (c.type === 1 /* NodeTypes.ELEMENT */ && findDir(c, 'if'))) {
  30611. // multiple root v-if
  30612. if (hasEncounteredIf)
  30613. return;
  30614. hasEncounteredIf = true;
  30615. }
  30616. else if (
  30617. // node before v-if
  30618. !hasEncounteredIf ||
  30619. // non else nodes
  30620. !(c.type === 1 /* NodeTypes.ELEMENT */ && findDir(c, /else/, true))) {
  30621. return;
  30622. }
  30623. }
  30624. injectFallthroughAttrs(node.children[0]);
  30625. }
  30626. else if (hasSingleChild(parent)) {
  30627. injectFallthroughAttrs(node);
  30628. }
  30629. };
  30630. function injectFallthroughAttrs(node) {
  30631. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  30632. (node.tagType === 0 /* ElementTypes.ELEMENT */ ||
  30633. node.tagType === 1 /* ElementTypes.COMPONENT */) &&
  30634. !findDir(node, 'for')) {
  30635. node.props.push({
  30636. type: 7 /* NodeTypes.DIRECTIVE */,
  30637. name: 'bind',
  30638. arg: undefined,
  30639. exp: createSimpleExpression(`_attrs`, false),
  30640. modifiers: [],
  30641. loc: locStub
  30642. });
  30643. }
  30644. }
  30645. const ssrInjectCssVars = (node, context) => {
  30646. if (!context.ssrCssVars) {
  30647. return;
  30648. }
  30649. // _cssVars is initialized once per render function
  30650. // the code is injected in ssrCodegenTransform when creating the
  30651. // ssr transform context
  30652. if (node.type === 0 /* NodeTypes.ROOT */) {
  30653. context.identifiers._cssVars = 1;
  30654. }
  30655. const parent = context.parent;
  30656. if (!parent || parent.type !== 0 /* NodeTypes.ROOT */) {
  30657. return;
  30658. }
  30659. if (node.type === 10 /* NodeTypes.IF_BRANCH */) {
  30660. for (const child of node.children) {
  30661. injectCssVars(child);
  30662. }
  30663. }
  30664. else {
  30665. injectCssVars(node);
  30666. }
  30667. };
  30668. function injectCssVars(node) {
  30669. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  30670. (node.tagType === 0 /* ElementTypes.ELEMENT */ ||
  30671. node.tagType === 1 /* ElementTypes.COMPONENT */) &&
  30672. !findDir(node, 'for')) {
  30673. if (isBuiltInType(node.tag, 'Suspense')) {
  30674. for (const child of node.children) {
  30675. if (child.type === 1 /* NodeTypes.ELEMENT */ &&
  30676. child.tagType === 3 /* ElementTypes.TEMPLATE */) {
  30677. // suspense slot
  30678. child.children.forEach(injectCssVars);
  30679. }
  30680. else {
  30681. injectCssVars(child);
  30682. }
  30683. }
  30684. }
  30685. else {
  30686. node.props.push({
  30687. type: 7 /* NodeTypes.DIRECTIVE */,
  30688. name: 'bind',
  30689. arg: undefined,
  30690. exp: createSimpleExpression(`_cssVars`, false),
  30691. modifiers: [],
  30692. loc: locStub
  30693. });
  30694. }
  30695. }
  30696. }
  30697. function compile(template, options = {}) {
  30698. options = Object.assign(Object.assign(Object.assign({}, options), parserOptions), { ssr: true, inSSR: true, scopeId: options.mode === 'function' ? null : options.scopeId,
  30699. // always prefix since compiler-ssr doesn't have size concern
  30700. prefixIdentifiers: true,
  30701. // disable optimizations that are unnecessary for ssr
  30702. cacheHandlers: false, hoistStatic: false });
  30703. const ast = baseParse(template, options);
  30704. // Save raw options for AST. This is needed when performing sub-transforms
  30705. // on slot vnode branches.
  30706. rawOptionsMap.set(ast, options);
  30707. transform$1(ast, Object.assign(Object.assign({}, options), { hoistStatic: false, nodeTransforms: [
  30708. ssrTransformIf,
  30709. ssrTransformFor,
  30710. trackVForSlotScopes,
  30711. transformExpression,
  30712. ssrTransformSlotOutlet,
  30713. ssrInjectFallthroughAttrs,
  30714. ssrInjectCssVars,
  30715. ssrTransformElement,
  30716. ssrTransformComponent,
  30717. trackSlotScopes,
  30718. transformStyle,
  30719. ...(options.nodeTransforms || []) // user transforms
  30720. ], directiveTransforms: Object.assign({
  30721. // reusing core v-bind
  30722. bind: transformBind, on: transformOn$1,
  30723. // model and show has dedicated SSR handling
  30724. model: ssrTransformModel, show: ssrTransformShow,
  30725. // the following are ignored during SSR
  30726. // on: noopDirectiveTransform,
  30727. cloak: noopDirectiveTransform, once: noopDirectiveTransform, memo: noopDirectiveTransform }, (options.directiveTransforms || {}) // user transforms
  30728. ) }));
  30729. // traverse the template AST and convert into SSR codegen AST
  30730. // by replacing ast.codegenNode.
  30731. ssrCodegenTransform(ast, options);
  30732. return generate(ast, options);
  30733. }
  30734. var CompilerSSR = /*#__PURE__*/Object.freeze({
  30735. __proto__: null,
  30736. compile: compile
  30737. });
  30738. var _polyfillNode_fs = {};
  30739. var _polyfillNode_fs$1 = /*#__PURE__*/Object.freeze({
  30740. __proto__: null,
  30741. default: _polyfillNode_fs
  30742. });
  30743. var require$$0$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_fs$1);
  30744. var require$$2$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_path);
  30745. var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util$1);
  30746. const hasWarned$1 = {};
  30747. function warnOnce$4(msg) {
  30748. const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
  30749. if (!isNodeProd && !false && !hasWarned$1[msg]) {
  30750. hasWarned$1[msg] = true;
  30751. warn$1(msg);
  30752. }
  30753. }
  30754. function warn$1(msg) {
  30755. console.warn(`\x1b[1m\x1b[33m[@vue/compiler-sfc]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
  30756. }
  30757. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  30758. // Consolidate exposes a callback based API, but the callback is in fact
  30759. // called synchronously for most templating engines. In our case, we have to
  30760. // expose a synchronous API so that it is usable in Jest transforms (which
  30761. // have to be sync because they are applied via Node.js require hooks)
  30762. let res = '';
  30763. let err = null;
  30764. preprocessor.render(source, Object.assign({ filename }, preprocessOptions), (_err, _res) => {
  30765. if (_err)
  30766. err = _err;
  30767. res = _res;
  30768. });
  30769. if (err)
  30770. throw err;
  30771. return res;
  30772. }
  30773. function compileTemplate(options) {
  30774. const { preprocessLang, preprocessCustomRequire } = options;
  30775. if (preprocessLang &&
  30776. !preprocessCustomRequire) {
  30777. throw new Error(`[@vue/compiler-sfc] Template preprocessing in the browser build must ` +
  30778. `provide the \`preprocessCustomRequire\` option to return the in-browser ` +
  30779. `version of the preprocessor in the shape of { render(): string }.`);
  30780. }
  30781. const preprocessor = preprocessLang
  30782. ? preprocessCustomRequire
  30783. ? preprocessCustomRequire(preprocessLang)
  30784. : undefined
  30785. : false;
  30786. if (preprocessor) {
  30787. try {
  30788. return doCompileTemplate(Object.assign(Object.assign({}, options), { source: preprocess$1(options, preprocessor) }));
  30789. }
  30790. catch (e) {
  30791. return {
  30792. code: `export default function render() {}`,
  30793. source: options.source,
  30794. tips: [],
  30795. errors: [e]
  30796. };
  30797. }
  30798. }
  30799. else if (preprocessLang) {
  30800. return {
  30801. code: `export default function render() {}`,
  30802. source: options.source,
  30803. tips: [
  30804. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  30805. ],
  30806. errors: [
  30807. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  30808. ]
  30809. };
  30810. }
  30811. else {
  30812. return doCompileTemplate(options);
  30813. }
  30814. }
  30815. function doCompileTemplate({ filename, id, scoped, slotted, inMap, source, ssr = false, ssrCssVars, isProd = false, compiler = ssr ? CompilerSSR : CompilerDOM, compilerOptions = {}, transformAssetUrls }) {
  30816. const errors = [];
  30817. const warnings = [];
  30818. let nodeTransforms = [];
  30819. if (isObject$2(transformAssetUrls)) {
  30820. const assetOptions = normalizeOptions(transformAssetUrls);
  30821. nodeTransforms = [
  30822. createAssetUrlTransformWithOptions(assetOptions),
  30823. createSrcsetTransformWithOptions(assetOptions)
  30824. ];
  30825. }
  30826. else if (transformAssetUrls !== false) {
  30827. nodeTransforms = [transformAssetUrl, transformSrcset];
  30828. }
  30829. if (ssr && !ssrCssVars) {
  30830. warnOnce$4(`compileTemplate is called with \`ssr: true\` but no ` +
  30831. `corresponding \`cssVars\` option.\`.`);
  30832. }
  30833. if (!id) {
  30834. warnOnce$4(`compileTemplate now requires the \`id\` option.\`.`);
  30835. id = '';
  30836. }
  30837. const shortId = id.replace(/^data-v-/, '');
  30838. const longId = `data-v-${shortId}`;
  30839. let { code, ast, preamble, map } = compiler.compile(source, Object.assign(Object.assign({ mode: 'module', prefixIdentifiers: true, hoistStatic: true, cacheHandlers: true, ssrCssVars: ssr && ssrCssVars && ssrCssVars.length
  30840. ? genCssVarsFromList(ssrCssVars, shortId, isProd, true)
  30841. : '', scopeId: scoped ? longId : undefined, slotted, sourceMap: true }, compilerOptions), { nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []), filename, onError: e => errors.push(e), onWarn: w => warnings.push(w) }));
  30842. // inMap should be the map produced by ./parse.ts which is a simple line-only
  30843. // mapping. If it is present, we need to adjust the final map and errors to
  30844. // reflect the original line numbers.
  30845. if (inMap) {
  30846. if (map) {
  30847. map = mapLines(inMap, map);
  30848. }
  30849. if (errors.length) {
  30850. patchErrors(errors, source, inMap);
  30851. }
  30852. }
  30853. const tips = warnings.map(w => {
  30854. let msg = w.message;
  30855. if (w.loc) {
  30856. msg += `\n${generateCodeFrame(source, w.loc.start.offset, w.loc.end.offset)}`;
  30857. }
  30858. return msg;
  30859. });
  30860. return { code, ast, preamble, source, errors, tips, map };
  30861. }
  30862. function mapLines(oldMap, newMap) {
  30863. if (!oldMap)
  30864. return newMap;
  30865. if (!newMap)
  30866. return oldMap;
  30867. const oldMapConsumer = new SourceMapConsumer$5(oldMap);
  30868. const newMapConsumer = new SourceMapConsumer$5(newMap);
  30869. const mergedMapGenerator = new SourceMapGenerator$6();
  30870. newMapConsumer.eachMapping(m => {
  30871. if (m.originalLine == null) {
  30872. return;
  30873. }
  30874. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  30875. line: m.originalLine,
  30876. column: m.originalColumn
  30877. });
  30878. if (origPosInOldMap.source == null) {
  30879. return;
  30880. }
  30881. mergedMapGenerator.addMapping({
  30882. generated: {
  30883. line: m.generatedLine,
  30884. column: m.generatedColumn
  30885. },
  30886. original: {
  30887. line: origPosInOldMap.line,
  30888. // use current column, since the oldMap produced by @vue/compiler-sfc
  30889. // does not
  30890. column: m.originalColumn
  30891. },
  30892. source: origPosInOldMap.source,
  30893. name: origPosInOldMap.name
  30894. });
  30895. });
  30896. // source-map's type definition is incomplete
  30897. const generator = mergedMapGenerator;
  30898. oldMapConsumer.sources.forEach((sourceFile) => {
  30899. generator._sources.add(sourceFile);
  30900. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  30901. if (sourceContent != null) {
  30902. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  30903. }
  30904. });
  30905. generator._sourceRoot = oldMap.sourceRoot;
  30906. generator._file = oldMap.file;
  30907. return generator.toJSON();
  30908. }
  30909. function patchErrors(errors, source, inMap) {
  30910. const originalSource = inMap.sourcesContent[0];
  30911. const offset = originalSource.indexOf(source);
  30912. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  30913. errors.forEach(err => {
  30914. if (err.loc) {
  30915. err.loc.start.line += lineOffset;
  30916. err.loc.start.offset += offset;
  30917. if (err.loc.end !== err.loc.start) {
  30918. err.loc.end.line += lineOffset;
  30919. err.loc.end.offset += offset;
  30920. }
  30921. }
  30922. });
  30923. }
  30924. const defaultExportRE = /((?:^|\n|;)\s*)export(\s*)default/;
  30925. const namedDefaultExportRE = /((?:^|\n|;)\s*)export(.+)(?:as)?(\s*)default/s;
  30926. const exportDefaultClassRE = /((?:^|\n|;)\s*)export\s+default\s+class\s+([\w$]+)/;
  30927. /**
  30928. * Utility for rewriting `export default` in a script block into a variable
  30929. * declaration so that we can inject things into it
  30930. */
  30931. function rewriteDefault(input, as, parserPlugins) {
  30932. if (!hasDefaultExport(input)) {
  30933. return input + `\nconst ${as} = {}`;
  30934. }
  30935. let replaced;
  30936. const classMatch = input.match(exportDefaultClassRE);
  30937. if (classMatch) {
  30938. replaced =
  30939. input.replace(exportDefaultClassRE, '$1class $2') +
  30940. `\nconst ${as} = ${classMatch[2]}`;
  30941. }
  30942. else {
  30943. replaced = input.replace(defaultExportRE, `$1const ${as} =`);
  30944. }
  30945. if (!hasDefaultExport(replaced)) {
  30946. return replaced;
  30947. }
  30948. // if the script somehow still contains `default export`, it probably has
  30949. // multi-line comments or template strings. fallback to a full parse.
  30950. const s = new MagicString$1(input);
  30951. const ast = parse_1$1(input, {
  30952. sourceType: 'module',
  30953. plugins: parserPlugins
  30954. }).program.body;
  30955. ast.forEach(node => {
  30956. if (node.type === 'ExportDefaultDeclaration') {
  30957. if (node.declaration.type === 'ClassDeclaration') {
  30958. s.overwrite(node.start, node.declaration.id.start, `class `);
  30959. s.append(`\nconst ${as} = ${node.declaration.id.name}`);
  30960. }
  30961. else {
  30962. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  30963. }
  30964. }
  30965. if (node.type === 'ExportNamedDeclaration') {
  30966. for (const specifier of node.specifiers) {
  30967. if (specifier.type === 'ExportSpecifier' &&
  30968. specifier.exported.type === 'Identifier' &&
  30969. specifier.exported.name === 'default') {
  30970. if (node.source) {
  30971. if (specifier.local.name === 'default') {
  30972. const end = specifierEnd(input, specifier.local.end, node.end);
  30973. s.prepend(`import { default as __VUE_DEFAULT__ } from '${node.source.value}'\n`);
  30974. s.overwrite(specifier.start, end, ``);
  30975. s.append(`\nconst ${as} = __VUE_DEFAULT__`);
  30976. continue;
  30977. }
  30978. else {
  30979. const end = specifierEnd(input, specifier.exported.end, node.end);
  30980. s.prepend(`import { ${input.slice(specifier.local.start, specifier.local.end)} } from '${node.source.value}'\n`);
  30981. s.overwrite(specifier.start, end, ``);
  30982. s.append(`\nconst ${as} = ${specifier.local.name}`);
  30983. continue;
  30984. }
  30985. }
  30986. const end = specifierEnd(input, specifier.end, node.end);
  30987. s.overwrite(specifier.start, end, ``);
  30988. s.append(`\nconst ${as} = ${specifier.local.name}`);
  30989. }
  30990. }
  30991. }
  30992. });
  30993. return s.toString();
  30994. }
  30995. function hasDefaultExport(input) {
  30996. return defaultExportRE.test(input) || namedDefaultExportRE.test(input);
  30997. }
  30998. function specifierEnd(input, end, nodeEnd) {
  30999. // export { default , foo } ...
  31000. let hasCommas = false;
  31001. let oldEnd = end;
  31002. while (end < nodeEnd) {
  31003. if (/\s/.test(input.charAt(end))) {
  31004. end++;
  31005. }
  31006. else if (input.charAt(end) === ',') {
  31007. end++;
  31008. hasCommas = true;
  31009. break;
  31010. }
  31011. else if (input.charAt(end) === '}') {
  31012. break;
  31013. }
  31014. }
  31015. return hasCommas ? end : oldEnd;
  31016. }
  31017. const CONVERT_SYMBOL = '$';
  31018. const ESCAPE_SYMBOL = '$$';
  31019. const IMPORT_SOURCE = 'vue/macros';
  31020. const shorthands = ['ref', 'computed', 'shallowRef', 'toRef', 'customRef'];
  31021. const transformCheckRE = /[^\w]\$(?:\$|ref|computed|shallowRef)?\s*(\(|\<)/;
  31022. function shouldTransform(src) {
  31023. return transformCheckRE.test(src);
  31024. }
  31025. function transform(src, { filename, sourceMap, parserPlugins, importHelpersFrom = 'vue' } = {}) {
  31026. const plugins = parserPlugins || [];
  31027. if (filename) {
  31028. if (/\.tsx?$/.test(filename)) {
  31029. plugins.push('typescript');
  31030. }
  31031. if (filename.endsWith('x')) {
  31032. plugins.push('jsx');
  31033. }
  31034. }
  31035. const ast = parse_1$1(src, {
  31036. sourceType: 'module',
  31037. plugins
  31038. });
  31039. const s = new MagicString$1(src);
  31040. const res = transformAST(ast.program, s, 0);
  31041. // inject helper imports
  31042. if (res.importedHelpers.length) {
  31043. s.prepend(`import { ${res.importedHelpers
  31044. .map(h => `${h} as _${h}`)
  31045. .join(', ')} } from '${importHelpersFrom}'\n`);
  31046. }
  31047. return Object.assign(Object.assign({}, res), { code: s.toString(), map: sourceMap
  31048. ? s.generateMap({
  31049. source: filename,
  31050. hires: true,
  31051. includeContent: true
  31052. })
  31053. : null });
  31054. }
  31055. function transformAST(ast, s, offset = 0, knownRefs, knownProps) {
  31056. // TODO remove when out of experimental
  31057. warnExperimental();
  31058. const userImports = Object.create(null);
  31059. for (const node of ast.body) {
  31060. if (node.type !== 'ImportDeclaration')
  31061. continue;
  31062. walkImportDeclaration(node);
  31063. }
  31064. // macro import handling
  31065. let convertSymbol;
  31066. let escapeSymbol;
  31067. for (const { local, imported, source, specifier } of Object.values(userImports)) {
  31068. if (source === IMPORT_SOURCE) {
  31069. if (imported === ESCAPE_SYMBOL) {
  31070. escapeSymbol = local;
  31071. }
  31072. else if (imported === CONVERT_SYMBOL) {
  31073. convertSymbol = local;
  31074. }
  31075. else if (imported !== local) {
  31076. error(`macro imports for ref-creating methods do not support aliasing.`, specifier);
  31077. }
  31078. }
  31079. }
  31080. // default symbol
  31081. if (!convertSymbol && !userImports[CONVERT_SYMBOL]) {
  31082. convertSymbol = CONVERT_SYMBOL;
  31083. }
  31084. if (!escapeSymbol && !userImports[ESCAPE_SYMBOL]) {
  31085. escapeSymbol = ESCAPE_SYMBOL;
  31086. }
  31087. const importedHelpers = new Set();
  31088. const rootScope = {};
  31089. const scopeStack = [rootScope];
  31090. let currentScope = rootScope;
  31091. let escapeScope; // inside $$()
  31092. const excludedIds = new WeakSet();
  31093. const parentStack = [];
  31094. const propsLocalToPublicMap = Object.create(null);
  31095. if (knownRefs) {
  31096. for (const key of knownRefs) {
  31097. rootScope[key] = {};
  31098. }
  31099. }
  31100. if (knownProps) {
  31101. for (const key in knownProps) {
  31102. const { local, isConst } = knownProps[key];
  31103. rootScope[local] = {
  31104. isProp: true,
  31105. isConst: !!isConst
  31106. };
  31107. propsLocalToPublicMap[local] = key;
  31108. }
  31109. }
  31110. function walkImportDeclaration(node) {
  31111. const source = node.source.value;
  31112. if (source === IMPORT_SOURCE) {
  31113. s.remove(node.start + offset, node.end + offset);
  31114. }
  31115. for (const specifier of node.specifiers) {
  31116. const local = specifier.local.name;
  31117. const imported = (specifier.type === 'ImportSpecifier' &&
  31118. specifier.imported.type === 'Identifier' &&
  31119. specifier.imported.name) ||
  31120. 'default';
  31121. userImports[local] = {
  31122. source,
  31123. local,
  31124. imported,
  31125. specifier
  31126. };
  31127. }
  31128. }
  31129. function isRefCreationCall(callee) {
  31130. if (!convertSymbol || currentScope[convertSymbol] !== undefined) {
  31131. return false;
  31132. }
  31133. if (callee === convertSymbol) {
  31134. return convertSymbol;
  31135. }
  31136. if (callee[0] === '$' && shorthands.includes(callee.slice(1))) {
  31137. return callee;
  31138. }
  31139. return false;
  31140. }
  31141. function error(msg, node) {
  31142. const e = new Error(msg);
  31143. e.node = node;
  31144. throw e;
  31145. }
  31146. function helper(msg) {
  31147. importedHelpers.add(msg);
  31148. return `_${msg}`;
  31149. }
  31150. function registerBinding(id, binding) {
  31151. excludedIds.add(id);
  31152. if (currentScope) {
  31153. currentScope[id.name] = binding ? binding : false;
  31154. }
  31155. else {
  31156. error('registerBinding called without active scope, something is wrong.', id);
  31157. }
  31158. }
  31159. const registerRefBinding = (id, isConst = false) => registerBinding(id, { isConst });
  31160. let tempVarCount = 0;
  31161. function genTempVar() {
  31162. return `__$temp_${++tempVarCount}`;
  31163. }
  31164. function snip(node) {
  31165. return s.original.slice(node.start + offset, node.end + offset);
  31166. }
  31167. function walkScope(node, isRoot = false) {
  31168. for (const stmt of node.body) {
  31169. if (stmt.type === 'VariableDeclaration') {
  31170. walkVariableDeclaration(stmt, isRoot);
  31171. }
  31172. else if (stmt.type === 'FunctionDeclaration' ||
  31173. stmt.type === 'ClassDeclaration') {
  31174. if (stmt.declare || !stmt.id)
  31175. continue;
  31176. registerBinding(stmt.id);
  31177. }
  31178. else if ((stmt.type === 'ForOfStatement' || stmt.type === 'ForInStatement') &&
  31179. stmt.left.type === 'VariableDeclaration') {
  31180. walkVariableDeclaration(stmt.left);
  31181. }
  31182. else if (stmt.type === 'ExportNamedDeclaration' &&
  31183. stmt.declaration &&
  31184. stmt.declaration.type === 'VariableDeclaration') {
  31185. walkVariableDeclaration(stmt.declaration, isRoot);
  31186. }
  31187. else if (stmt.type === 'LabeledStatement' &&
  31188. stmt.body.type === 'VariableDeclaration') {
  31189. walkVariableDeclaration(stmt.body, isRoot);
  31190. }
  31191. }
  31192. }
  31193. function walkVariableDeclaration(stmt, isRoot = false) {
  31194. if (stmt.declare) {
  31195. return;
  31196. }
  31197. for (const decl of stmt.declarations) {
  31198. let refCall;
  31199. const isCall = decl.init &&
  31200. decl.init.type === 'CallExpression' &&
  31201. decl.init.callee.type === 'Identifier';
  31202. if (isCall &&
  31203. (refCall = isRefCreationCall(decl.init.callee.name))) {
  31204. processRefDeclaration(refCall, decl.id, decl.init, stmt.kind === 'const');
  31205. }
  31206. else {
  31207. const isProps = isRoot && isCall && decl.init.callee.name === 'defineProps';
  31208. for (const id of extractIdentifiers(decl.id)) {
  31209. if (isProps) {
  31210. // for defineProps destructure, only exclude them since they
  31211. // are already passed in as knownProps
  31212. excludedIds.add(id);
  31213. }
  31214. else {
  31215. registerBinding(id);
  31216. }
  31217. }
  31218. }
  31219. }
  31220. }
  31221. function processRefDeclaration(method, id, call, isConst) {
  31222. excludedIds.add(call.callee);
  31223. if (method === convertSymbol) {
  31224. // $
  31225. // remove macro
  31226. s.remove(call.callee.start + offset, call.callee.end + offset);
  31227. if (id.type === 'Identifier') {
  31228. // single variable
  31229. registerRefBinding(id, isConst);
  31230. }
  31231. else if (id.type === 'ObjectPattern') {
  31232. processRefObjectPattern(id, call, isConst);
  31233. }
  31234. else if (id.type === 'ArrayPattern') {
  31235. processRefArrayPattern(id, call, isConst);
  31236. }
  31237. }
  31238. else {
  31239. // shorthands
  31240. if (id.type === 'Identifier') {
  31241. registerRefBinding(id, isConst);
  31242. // replace call
  31243. s.overwrite(call.start + offset, call.start + method.length + offset, helper(method.slice(1)));
  31244. }
  31245. else {
  31246. error(`${method}() cannot be used with destructure patterns.`, call);
  31247. }
  31248. }
  31249. }
  31250. function processRefObjectPattern(pattern, call, isConst, tempVar, path = []) {
  31251. if (!tempVar) {
  31252. tempVar = genTempVar();
  31253. // const { x } = $(useFoo()) --> const __$temp_1 = useFoo()
  31254. s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
  31255. }
  31256. let nameId;
  31257. for (const p of pattern.properties) {
  31258. let key;
  31259. let defaultValue;
  31260. if (p.type === 'ObjectProperty') {
  31261. if (p.key.start === p.value.start) {
  31262. // shorthand { foo }
  31263. nameId = p.key;
  31264. if (p.value.type === 'Identifier') {
  31265. // avoid shorthand value identifier from being processed
  31266. excludedIds.add(p.value);
  31267. }
  31268. else if (p.value.type === 'AssignmentPattern' &&
  31269. p.value.left.type === 'Identifier') {
  31270. // { foo = 1 }
  31271. excludedIds.add(p.value.left);
  31272. defaultValue = p.value.right;
  31273. }
  31274. }
  31275. else {
  31276. key = p.computed ? p.key : p.key.name;
  31277. if (p.value.type === 'Identifier') {
  31278. // { foo: bar }
  31279. nameId = p.value;
  31280. }
  31281. else if (p.value.type === 'ObjectPattern') {
  31282. processRefObjectPattern(p.value, call, isConst, tempVar, [
  31283. ...path,
  31284. key
  31285. ]);
  31286. }
  31287. else if (p.value.type === 'ArrayPattern') {
  31288. processRefArrayPattern(p.value, call, isConst, tempVar, [
  31289. ...path,
  31290. key
  31291. ]);
  31292. }
  31293. else if (p.value.type === 'AssignmentPattern') {
  31294. if (p.value.left.type === 'Identifier') {
  31295. // { foo: bar = 1 }
  31296. nameId = p.value.left;
  31297. defaultValue = p.value.right;
  31298. }
  31299. else if (p.value.left.type === 'ObjectPattern') {
  31300. processRefObjectPattern(p.value.left, call, isConst, tempVar, [
  31301. ...path,
  31302. [key, p.value.right]
  31303. ]);
  31304. }
  31305. else if (p.value.left.type === 'ArrayPattern') {
  31306. processRefArrayPattern(p.value.left, call, isConst, tempVar, [
  31307. ...path,
  31308. [key, p.value.right]
  31309. ]);
  31310. }
  31311. else ;
  31312. }
  31313. }
  31314. }
  31315. else {
  31316. // rest element { ...foo }
  31317. error(`reactivity destructure does not support rest elements.`, p);
  31318. }
  31319. if (nameId) {
  31320. registerRefBinding(nameId, isConst);
  31321. // inject toRef() after original replaced pattern
  31322. const source = pathToString(tempVar, path);
  31323. const keyStr = isString$2(key)
  31324. ? `'${key}'`
  31325. : key
  31326. ? snip(key)
  31327. : `'${nameId.name}'`;
  31328. const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
  31329. s.appendLeft(call.end + offset, `,\n ${nameId.name} = ${helper('toRef')}(${source}, ${keyStr}${defaultStr})`);
  31330. }
  31331. }
  31332. if (nameId) {
  31333. s.appendLeft(call.end + offset, ';');
  31334. }
  31335. }
  31336. function processRefArrayPattern(pattern, call, isConst, tempVar, path = []) {
  31337. if (!tempVar) {
  31338. // const [x] = $(useFoo()) --> const __$temp_1 = useFoo()
  31339. tempVar = genTempVar();
  31340. s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
  31341. }
  31342. let nameId;
  31343. for (let i = 0; i < pattern.elements.length; i++) {
  31344. const e = pattern.elements[i];
  31345. if (!e)
  31346. continue;
  31347. let defaultValue;
  31348. if (e.type === 'Identifier') {
  31349. // [a] --> [__a]
  31350. nameId = e;
  31351. }
  31352. else if (e.type === 'AssignmentPattern') {
  31353. // [a = 1]
  31354. nameId = e.left;
  31355. defaultValue = e.right;
  31356. }
  31357. else if (e.type === 'RestElement') {
  31358. // [...a]
  31359. error(`reactivity destructure does not support rest elements.`, e);
  31360. }
  31361. else if (e.type === 'ObjectPattern') {
  31362. processRefObjectPattern(e, call, isConst, tempVar, [...path, i]);
  31363. }
  31364. else if (e.type === 'ArrayPattern') {
  31365. processRefArrayPattern(e, call, isConst, tempVar, [...path, i]);
  31366. }
  31367. if (nameId) {
  31368. registerRefBinding(nameId, isConst);
  31369. // inject toRef() after original replaced pattern
  31370. const source = pathToString(tempVar, path);
  31371. const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
  31372. s.appendLeft(call.end + offset, `,\n ${nameId.name} = ${helper('toRef')}(${source}, ${i}${defaultStr})`);
  31373. }
  31374. }
  31375. if (nameId) {
  31376. s.appendLeft(call.end + offset, ';');
  31377. }
  31378. }
  31379. function pathToString(source, path) {
  31380. if (path.length) {
  31381. for (const seg of path) {
  31382. if (isArray$3(seg)) {
  31383. source = `(${source}${segToString(seg[0])} || ${snip(seg[1])})`;
  31384. }
  31385. else {
  31386. source += segToString(seg);
  31387. }
  31388. }
  31389. }
  31390. return source;
  31391. }
  31392. function segToString(seg) {
  31393. if (typeof seg === 'number') {
  31394. return `[${seg}]`;
  31395. }
  31396. else if (typeof seg === 'string') {
  31397. return `.${seg}`;
  31398. }
  31399. else {
  31400. return snip(seg);
  31401. }
  31402. }
  31403. function rewriteId(scope, id, parent, parentStack) {
  31404. if (hasOwn(scope, id.name)) {
  31405. const binding = scope[id.name];
  31406. if (binding) {
  31407. if (binding.isConst &&
  31408. ((parent.type === 'AssignmentExpression' && id === parent.left) ||
  31409. parent.type === 'UpdateExpression')) {
  31410. error(`Assignment to constant variable.`, id);
  31411. }
  31412. const { isProp } = binding;
  31413. if (isStaticProperty(parent) && parent.shorthand) {
  31414. // let binding used in a property shorthand
  31415. // skip for destructure patterns
  31416. if (!parent.inPattern ||
  31417. isInDestructureAssignment(parent, parentStack)) {
  31418. if (isProp) {
  31419. if (escapeScope) {
  31420. // prop binding in $$()
  31421. // { prop } -> { prop: __props_prop }
  31422. registerEscapedPropBinding(id);
  31423. s.appendLeft(id.end + offset, `: __props_${propsLocalToPublicMap[id.name]}`);
  31424. }
  31425. else {
  31426. // { prop } -> { prop: __props.prop }
  31427. s.appendLeft(id.end + offset, `: ${genPropsAccessExp(propsLocalToPublicMap[id.name])}`);
  31428. }
  31429. }
  31430. else {
  31431. // { foo } -> { foo: foo.value }
  31432. s.appendLeft(id.end + offset, `: ${id.name}.value`);
  31433. }
  31434. }
  31435. }
  31436. else {
  31437. if (isProp) {
  31438. if (escapeScope) {
  31439. // x --> __props_x
  31440. registerEscapedPropBinding(id);
  31441. s.overwrite(id.start + offset, id.end + offset, `__props_${propsLocalToPublicMap[id.name]}`);
  31442. }
  31443. else {
  31444. // x --> __props.x
  31445. s.overwrite(id.start + offset, id.end + offset, genPropsAccessExp(propsLocalToPublicMap[id.name]));
  31446. }
  31447. }
  31448. else {
  31449. // x --> x.value
  31450. s.appendLeft(id.end + offset, '.value');
  31451. }
  31452. }
  31453. }
  31454. return true;
  31455. }
  31456. return false;
  31457. }
  31458. const propBindingRefs = {};
  31459. function registerEscapedPropBinding(id) {
  31460. if (!propBindingRefs.hasOwnProperty(id.name)) {
  31461. propBindingRefs[id.name] = true;
  31462. const publicKey = propsLocalToPublicMap[id.name];
  31463. s.prependRight(offset, `const __props_${publicKey} = ${helper(`toRef`)}(__props, '${publicKey}');\n`);
  31464. }
  31465. }
  31466. // check root scope first
  31467. walkScope(ast, true);
  31468. walk$1(ast, {
  31469. enter(node, parent) {
  31470. parent && parentStack.push(parent);
  31471. // function scopes
  31472. if (isFunctionType(node)) {
  31473. scopeStack.push((currentScope = {}));
  31474. walkFunctionParams(node, registerBinding);
  31475. if (node.body.type === 'BlockStatement') {
  31476. walkScope(node.body);
  31477. }
  31478. return;
  31479. }
  31480. // catch param
  31481. if (node.type === 'CatchClause') {
  31482. scopeStack.push((currentScope = {}));
  31483. if (node.param && node.param.type === 'Identifier') {
  31484. registerBinding(node.param);
  31485. }
  31486. walkScope(node.body);
  31487. return;
  31488. }
  31489. // non-function block scopes
  31490. if (node.type === 'BlockStatement' && !isFunctionType(parent)) {
  31491. scopeStack.push((currentScope = {}));
  31492. walkScope(node);
  31493. return;
  31494. }
  31495. // skip type nodes
  31496. if (parent &&
  31497. parent.type.startsWith('TS') &&
  31498. parent.type !== 'TSAsExpression' &&
  31499. parent.type !== 'TSNonNullExpression' &&
  31500. parent.type !== 'TSTypeAssertion') {
  31501. return this.skip();
  31502. }
  31503. if (node.type === 'Identifier') {
  31504. const binding = rootScope[node.name];
  31505. if (
  31506. // if inside $$(), skip unless this is a destructured prop binding
  31507. !(escapeScope && (!binding || !binding.isProp)) &&
  31508. isReferencedIdentifier(node, parent, parentStack) &&
  31509. !excludedIds.has(node)) {
  31510. // walk up the scope chain to check if id should be appended .value
  31511. let i = scopeStack.length;
  31512. while (i--) {
  31513. if (rewriteId(scopeStack[i], node, parent, parentStack)) {
  31514. return;
  31515. }
  31516. }
  31517. }
  31518. }
  31519. if (node.type === 'CallExpression' && node.callee.type === 'Identifier') {
  31520. const callee = node.callee.name;
  31521. const refCall = isRefCreationCall(callee);
  31522. if (refCall && (!parent || parent.type !== 'VariableDeclarator')) {
  31523. return error(`${refCall} can only be used as the initializer of ` +
  31524. `a variable declaration.`, node);
  31525. }
  31526. if (escapeSymbol &&
  31527. currentScope[escapeSymbol] === undefined &&
  31528. callee === escapeSymbol) {
  31529. escapeScope = node;
  31530. s.remove(node.callee.start + offset, node.callee.end + offset);
  31531. if ((parent === null || parent === void 0 ? void 0 : parent.type) === 'ExpressionStatement') {
  31532. // edge case where the call expression is an expression statement
  31533. // if its own - prepend semicolon to avoid it being parsed as
  31534. // function invocation of previous line
  31535. let i = (node.leadingComments
  31536. ? node.leadingComments[0].start
  31537. : node.start) + offset;
  31538. while (i--) {
  31539. const char = s.original.charAt(i);
  31540. if (char === '\n') {
  31541. // only insert semi if it's actually the fisrt thign after
  31542. // newline
  31543. s.prependRight(node.start + offset, ';');
  31544. break;
  31545. }
  31546. else if (!/\s/.test(char)) {
  31547. break;
  31548. }
  31549. }
  31550. }
  31551. }
  31552. // TODO remove when out of experimental
  31553. if (callee === '$raw') {
  31554. error(`$raw() has been replaced by $$(). ` +
  31555. `See ${RFC_LINK} for latest updates.`, node);
  31556. }
  31557. if (callee === '$fromRef') {
  31558. error(`$fromRef() has been replaced by $(). ` +
  31559. `See ${RFC_LINK} for latest updates.`, node);
  31560. }
  31561. }
  31562. },
  31563. leave(node, parent) {
  31564. parent && parentStack.pop();
  31565. if ((node.type === 'BlockStatement' && !isFunctionType(parent)) ||
  31566. isFunctionType(node)) {
  31567. scopeStack.pop();
  31568. currentScope = scopeStack[scopeStack.length - 1] || null;
  31569. }
  31570. if (node === escapeScope) {
  31571. escapeScope = undefined;
  31572. }
  31573. }
  31574. });
  31575. return {
  31576. rootRefs: Object.keys(rootScope).filter(key => {
  31577. const binding = rootScope[key];
  31578. return binding && !binding.isProp;
  31579. }),
  31580. importedHelpers: [...importedHelpers]
  31581. };
  31582. }
  31583. const RFC_LINK = `https://github.com/vuejs/rfcs/discussions/369`;
  31584. const hasWarned = {};
  31585. function warnExperimental() {
  31586. // eslint-disable-next-line
  31587. if (typeof window !== 'undefined') {
  31588. return;
  31589. }
  31590. warnOnce$3(`Reactivity transform is an experimental feature.\n` +
  31591. `Experimental features may change behavior between patch versions.\n` +
  31592. `It is recommended to pin your vue dependencies to exact versions to avoid breakage.\n` +
  31593. `You can follow the proposal's status at ${RFC_LINK}.`);
  31594. }
  31595. function warnOnce$3(msg) {
  31596. const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
  31597. if (!isNodeProd && !false && !hasWarned[msg]) {
  31598. hasWarned[msg] = true;
  31599. warn(msg);
  31600. }
  31601. }
  31602. function warn(msg) {
  31603. console.warn(`\x1b[1m\x1b[33m[@vue/reactivity-transform]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
  31604. }
  31605. // Special compiler macros
  31606. const DEFINE_PROPS = 'defineProps';
  31607. const DEFINE_EMITS = 'defineEmits';
  31608. const DEFINE_EXPOSE = 'defineExpose';
  31609. const WITH_DEFAULTS = 'withDefaults';
  31610. // constants
  31611. const DEFAULT_VAR = `__default__`;
  31612. const isBuiltInDir = makeMap(`once,memo,if,for,else,else-if,slot,text,html,on,bind,model,show,cloak,is`);
  31613. /**
  31614. * Compile `<script setup>`
  31615. * It requires the whole SFC descriptor because we need to handle and merge
  31616. * normal `<script>` + `<script setup>` if both are present.
  31617. */
  31618. function compileScript(sfc, options) {
  31619. var _a;
  31620. let { script, scriptSetup, source, filename } = sfc;
  31621. // feature flags
  31622. // TODO remove support for deprecated options when out of experimental
  31623. const enableReactivityTransform = !!options.reactivityTransform ||
  31624. !!options.refSugar ||
  31625. !!options.refTransform;
  31626. const enablePropsTransform = !!options.reactivityTransform || !!options.propsDestructureTransform;
  31627. const isProd = !!options.isProd;
  31628. const genSourceMap = options.sourceMap !== false;
  31629. let refBindings;
  31630. if (!options.id) {
  31631. warnOnce$4(`compileScript now requires passing the \`id\` option.\n` +
  31632. `Upgrade your vite or vue-loader version for compatibility with ` +
  31633. `the latest experimental proposals.`);
  31634. }
  31635. const scopeId = options.id ? options.id.replace(/^data-v-/, '') : '';
  31636. const cssVars = sfc.cssVars;
  31637. const scriptLang = script && script.lang;
  31638. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  31639. const isTS = scriptLang === 'ts' ||
  31640. scriptLang === 'tsx' ||
  31641. scriptSetupLang === 'ts' ||
  31642. scriptSetupLang === 'tsx';
  31643. // resolve parser plugins
  31644. const plugins = [];
  31645. if (!isTS || scriptLang === 'tsx' || scriptSetupLang === 'tsx') {
  31646. plugins.push('jsx');
  31647. }
  31648. else {
  31649. // If don't match the case of adding jsx, should remove the jsx from the babelParserPlugins
  31650. if (options.babelParserPlugins)
  31651. options.babelParserPlugins = options.babelParserPlugins.filter(n => n !== 'jsx');
  31652. }
  31653. if (options.babelParserPlugins)
  31654. plugins.push(...options.babelParserPlugins);
  31655. if (isTS) {
  31656. plugins.push('typescript');
  31657. if (!plugins.includes('decorators')) {
  31658. plugins.push('decorators-legacy');
  31659. }
  31660. }
  31661. if (!scriptSetup) {
  31662. if (!script) {
  31663. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  31664. }
  31665. if (scriptLang && !isTS && scriptLang !== 'jsx') {
  31666. // do not process non js/ts script blocks
  31667. return script;
  31668. }
  31669. try {
  31670. let content = script.content;
  31671. let map = script.map;
  31672. const scriptAst = parse_1$1(content, {
  31673. plugins,
  31674. sourceType: 'module'
  31675. }).program;
  31676. const bindings = analyzeScriptBindings(scriptAst.body);
  31677. if (enableReactivityTransform && shouldTransform(content)) {
  31678. const s = new MagicString$1(source);
  31679. const startOffset = script.loc.start.offset;
  31680. const endOffset = script.loc.end.offset;
  31681. const { importedHelpers } = transformAST(scriptAst, s, startOffset);
  31682. if (importedHelpers.length) {
  31683. s.prepend(`import { ${importedHelpers
  31684. .map(h => `${h} as _${h}`)
  31685. .join(', ')} } from 'vue'\n`);
  31686. }
  31687. s.remove(0, startOffset);
  31688. s.remove(endOffset, source.length);
  31689. content = s.toString();
  31690. if (genSourceMap) {
  31691. map = s.generateMap({
  31692. source: filename,
  31693. hires: true,
  31694. includeContent: true
  31695. });
  31696. }
  31697. }
  31698. if (cssVars.length) {
  31699. content = rewriteDefault(content, DEFAULT_VAR, plugins);
  31700. content += genNormalScriptCssVarsCode(cssVars, bindings, scopeId, isProd);
  31701. content += `\nexport default ${DEFAULT_VAR}`;
  31702. }
  31703. return Object.assign(Object.assign({}, script), { content,
  31704. map,
  31705. bindings, scriptAst: scriptAst.body });
  31706. }
  31707. catch (e) {
  31708. // silently fallback if parse fails since user may be using custom
  31709. // babel syntax
  31710. return script;
  31711. }
  31712. }
  31713. if (script && scriptLang !== scriptSetupLang) {
  31714. throw new Error(`[@vue/compiler-sfc] <script> and <script setup> must have the same ` +
  31715. `language type.`);
  31716. }
  31717. if (scriptSetupLang && !isTS && scriptSetupLang !== 'jsx') {
  31718. // do not process non js/ts script blocks
  31719. return scriptSetup;
  31720. }
  31721. // metadata that needs to be returned
  31722. const bindingMetadata = {};
  31723. const helperImports = new Set();
  31724. const userImports = Object.create(null);
  31725. const scriptBindings = Object.create(null);
  31726. const setupBindings = Object.create(null);
  31727. let defaultExport;
  31728. let hasDefinePropsCall = false;
  31729. let hasDefineEmitCall = false;
  31730. let hasDefineExposeCall = false;
  31731. let hasDefaultExportName = false;
  31732. let hasDefaultExportRender = false;
  31733. let propsRuntimeDecl;
  31734. let propsRuntimeDefaults;
  31735. let propsDestructureDecl;
  31736. let propsDestructureRestId;
  31737. let propsTypeDecl;
  31738. let propsTypeDeclRaw;
  31739. let propsIdentifier;
  31740. let emitsRuntimeDecl;
  31741. let emitsTypeDecl;
  31742. let emitsTypeDeclRaw;
  31743. let emitIdentifier;
  31744. let hasAwait = false;
  31745. let hasInlinedSsrRenderFn = false;
  31746. // props/emits declared via types
  31747. const typeDeclaredProps = {};
  31748. const typeDeclaredEmits = new Set();
  31749. // record declared types for runtime props type generation
  31750. const declaredTypes = {};
  31751. // props destructure data
  31752. const propsDestructuredBindings = Object.create(null);
  31753. // magic-string state
  31754. const s = new MagicString$1(source);
  31755. const startOffset = scriptSetup.loc.start.offset;
  31756. const endOffset = scriptSetup.loc.end.offset;
  31757. const scriptStartOffset = script && script.loc.start.offset;
  31758. const scriptEndOffset = script && script.loc.end.offset;
  31759. function helper(key) {
  31760. helperImports.add(key);
  31761. return `_${key}`;
  31762. }
  31763. function parse(input, options, offset) {
  31764. try {
  31765. return parse_1$1(input, options).program;
  31766. }
  31767. catch (e) {
  31768. e.message = `[@vue/compiler-sfc] ${e.message}\n\n${sfc.filename}\n${generateCodeFrame(source, e.pos + offset, e.pos + offset + 1)}`;
  31769. throw e;
  31770. }
  31771. }
  31772. function error(msg, node, end = node.end + startOffset) {
  31773. throw new Error(`[@vue/compiler-sfc] ${msg}\n\n${sfc.filename}\n${generateCodeFrame(source, node.start + startOffset, end)}`);
  31774. }
  31775. function hoistNode(node) {
  31776. const start = node.start + startOffset;
  31777. let end = node.end + startOffset;
  31778. // locate comment
  31779. if (node.trailingComments && node.trailingComments.length > 0) {
  31780. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  31781. end = lastCommentNode.end + startOffset;
  31782. }
  31783. // locate the end of whitespace between this statement and the next
  31784. while (end <= source.length) {
  31785. if (!/\s/.test(source.charAt(end))) {
  31786. break;
  31787. }
  31788. end++;
  31789. }
  31790. s.move(start, end, 0);
  31791. }
  31792. function registerUserImport(source, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  31793. // template usage check is only needed in non-inline mode, so we can skip
  31794. // the work if inlineTemplate is true.
  31795. let isUsedInTemplate = needTemplateUsageCheck;
  31796. if (needTemplateUsageCheck &&
  31797. isTS &&
  31798. sfc.template &&
  31799. !sfc.template.src &&
  31800. !sfc.template.lang) {
  31801. isUsedInTemplate = isImportUsed(local, sfc);
  31802. }
  31803. userImports[local] = {
  31804. isType,
  31805. imported: imported || 'default',
  31806. local,
  31807. source,
  31808. isFromSetup,
  31809. isUsedInTemplate
  31810. };
  31811. }
  31812. function processDefineProps(node, declId, declKind) {
  31813. if (!isCallOf(node, DEFINE_PROPS)) {
  31814. return false;
  31815. }
  31816. if (hasDefinePropsCall) {
  31817. error(`duplicate ${DEFINE_PROPS}() call`, node);
  31818. }
  31819. hasDefinePropsCall = true;
  31820. propsRuntimeDecl = node.arguments[0];
  31821. // call has type parameters - infer runtime types from it
  31822. if (node.typeParameters) {
  31823. if (propsRuntimeDecl) {
  31824. error(`${DEFINE_PROPS}() cannot accept both type and non-type arguments ` +
  31825. `at the same time. Use one or the other.`, node);
  31826. }
  31827. propsTypeDeclRaw = node.typeParameters.params[0];
  31828. propsTypeDecl = resolveQualifiedType(propsTypeDeclRaw, node => node.type === 'TSTypeLiteral');
  31829. if (!propsTypeDecl) {
  31830. error(`type argument passed to ${DEFINE_PROPS}() must be a literal type, ` +
  31831. `or a reference to an interface or literal type.`, propsTypeDeclRaw);
  31832. }
  31833. }
  31834. if (declId) {
  31835. const isConst = declKind === 'const';
  31836. if (enablePropsTransform && declId.type === 'ObjectPattern') {
  31837. propsDestructureDecl = declId;
  31838. // props destructure - handle compilation sugar
  31839. for (const prop of declId.properties) {
  31840. if (prop.type === 'ObjectProperty') {
  31841. const propKey = resolveObjectKey(prop.key, prop.computed);
  31842. if (!propKey) {
  31843. error(`${DEFINE_PROPS}() destructure cannot use computed key.`, prop.key);
  31844. }
  31845. if (prop.value.type === 'AssignmentPattern') {
  31846. // default value { foo = 123 }
  31847. const { left, right } = prop.value;
  31848. if (left.type !== 'Identifier') {
  31849. error(`${DEFINE_PROPS}() destructure does not support nested patterns.`, left);
  31850. }
  31851. // store default value
  31852. propsDestructuredBindings[propKey] = {
  31853. local: left.name,
  31854. default: right,
  31855. isConst
  31856. };
  31857. }
  31858. else if (prop.value.type === 'Identifier') {
  31859. // simple destructure
  31860. propsDestructuredBindings[propKey] = {
  31861. local: prop.value.name,
  31862. isConst
  31863. };
  31864. }
  31865. else {
  31866. error(`${DEFINE_PROPS}() destructure does not support nested patterns.`, prop.value);
  31867. }
  31868. }
  31869. else {
  31870. // rest spread
  31871. propsDestructureRestId = prop.argument.name;
  31872. }
  31873. }
  31874. }
  31875. else {
  31876. propsIdentifier = scriptSetup.content.slice(declId.start, declId.end);
  31877. }
  31878. }
  31879. return true;
  31880. }
  31881. function processWithDefaults(node, declId, declKind) {
  31882. if (!isCallOf(node, WITH_DEFAULTS)) {
  31883. return false;
  31884. }
  31885. if (processDefineProps(node.arguments[0], declId, declKind)) {
  31886. if (propsRuntimeDecl) {
  31887. error(`${WITH_DEFAULTS} can only be used with type-based ` +
  31888. `${DEFINE_PROPS} declaration.`, node);
  31889. }
  31890. if (propsDestructureDecl) {
  31891. error(`${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().\n` +
  31892. `Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...).`, node.callee);
  31893. }
  31894. propsRuntimeDefaults = node.arguments[1];
  31895. if (!propsRuntimeDefaults ||
  31896. propsRuntimeDefaults.type !== 'ObjectExpression') {
  31897. error(`The 2nd argument of ${WITH_DEFAULTS} must be an object literal.`, propsRuntimeDefaults || node);
  31898. }
  31899. }
  31900. else {
  31901. error(`${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`, node.arguments[0] || node);
  31902. }
  31903. return true;
  31904. }
  31905. function processDefineEmits(node, declId) {
  31906. if (!isCallOf(node, DEFINE_EMITS)) {
  31907. return false;
  31908. }
  31909. if (hasDefineEmitCall) {
  31910. error(`duplicate ${DEFINE_EMITS}() call`, node);
  31911. }
  31912. hasDefineEmitCall = true;
  31913. emitsRuntimeDecl = node.arguments[0];
  31914. if (node.typeParameters) {
  31915. if (emitsRuntimeDecl) {
  31916. error(`${DEFINE_EMITS}() cannot accept both type and non-type arguments ` +
  31917. `at the same time. Use one or the other.`, node);
  31918. }
  31919. emitsTypeDeclRaw = node.typeParameters.params[0];
  31920. emitsTypeDecl = resolveQualifiedType(emitsTypeDeclRaw, node => node.type === 'TSFunctionType' || node.type === 'TSTypeLiteral');
  31921. if (!emitsTypeDecl) {
  31922. error(`type argument passed to ${DEFINE_EMITS}() must be a function type, ` +
  31923. `a literal type with call signatures, or a reference to the above types.`, emitsTypeDeclRaw);
  31924. }
  31925. }
  31926. if (declId) {
  31927. emitIdentifier =
  31928. declId.type === 'Identifier'
  31929. ? declId.name
  31930. : scriptSetup.content.slice(declId.start, declId.end);
  31931. }
  31932. return true;
  31933. }
  31934. function getAstBody() {
  31935. return scriptAst
  31936. ? [...scriptSetupAst.body, ...scriptAst.body]
  31937. : scriptSetupAst.body;
  31938. }
  31939. function resolveExtendsType(node, qualifier, cache = []) {
  31940. if (node.type === 'TSInterfaceDeclaration' && node.extends) {
  31941. node.extends.forEach(extend => {
  31942. if (extend.type === 'TSExpressionWithTypeArguments' &&
  31943. extend.expression.type === 'Identifier') {
  31944. const body = getAstBody();
  31945. for (const node of body) {
  31946. const qualified = isQualifiedType(node, qualifier, extend.expression.name);
  31947. if (qualified) {
  31948. cache.push(qualified);
  31949. resolveExtendsType(node, qualifier, cache);
  31950. return cache;
  31951. }
  31952. }
  31953. }
  31954. });
  31955. }
  31956. return cache;
  31957. }
  31958. function isQualifiedType(node, qualifier, refName) {
  31959. if (node.type === 'TSInterfaceDeclaration' && node.id.name === refName) {
  31960. return node.body;
  31961. }
  31962. else if (node.type === 'TSTypeAliasDeclaration' &&
  31963. node.id.name === refName &&
  31964. qualifier(node.typeAnnotation)) {
  31965. return node.typeAnnotation;
  31966. }
  31967. else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
  31968. return isQualifiedType(node.declaration, qualifier, refName);
  31969. }
  31970. }
  31971. // filter all extends types to keep the override declaration
  31972. function filterExtendsType(extendsTypes, bodies) {
  31973. extendsTypes.forEach(extend => {
  31974. const body = extend.body;
  31975. body.forEach(newBody => {
  31976. if (newBody.type === 'TSPropertySignature' &&
  31977. newBody.key.type === 'Identifier') {
  31978. const name = newBody.key.name;
  31979. const hasOverride = bodies.some(seenBody => seenBody.type === 'TSPropertySignature' &&
  31980. seenBody.key.type === 'Identifier' &&
  31981. seenBody.key.name === name);
  31982. if (!hasOverride)
  31983. bodies.push(newBody);
  31984. }
  31985. });
  31986. });
  31987. }
  31988. function resolveQualifiedType(node, qualifier) {
  31989. if (qualifier(node)) {
  31990. return node;
  31991. }
  31992. if (node.type === 'TSTypeReference' &&
  31993. node.typeName.type === 'Identifier') {
  31994. const refName = node.typeName.name;
  31995. const body = getAstBody();
  31996. for (let i = 0; i < body.length; i++) {
  31997. const node = body[i];
  31998. let qualified = isQualifiedType(node, qualifier, refName);
  31999. if (qualified) {
  32000. const extendsTypes = resolveExtendsType(node, qualifier);
  32001. if (extendsTypes.length) {
  32002. const bodies = [...qualified.body];
  32003. filterExtendsType(extendsTypes, bodies);
  32004. qualified.body = bodies;
  32005. }
  32006. qualified.__fromNormalScript =
  32007. scriptAst && i >= scriptSetupAst.body.length;
  32008. return qualified;
  32009. }
  32010. }
  32011. }
  32012. }
  32013. function processDefineExpose(node) {
  32014. if (isCallOf(node, DEFINE_EXPOSE)) {
  32015. if (hasDefineExposeCall) {
  32016. error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  32017. }
  32018. hasDefineExposeCall = true;
  32019. return true;
  32020. }
  32021. return false;
  32022. }
  32023. function checkInvalidScopeReference(node, method) {
  32024. if (!node)
  32025. return;
  32026. walkIdentifiers(node, id => {
  32027. if (setupBindings[id.name]) {
  32028. error(`\`${method}()\` in <script setup> cannot reference locally ` +
  32029. `declared variables because it will be hoisted outside of the ` +
  32030. `setup() function. If your component options require initialization ` +
  32031. `in the module scope, use a separate normal <script> to export ` +
  32032. `the options instead.`, id);
  32033. }
  32034. });
  32035. }
  32036. /**
  32037. * await foo()
  32038. * -->
  32039. * ;(
  32040. * ([__temp,__restore] = withAsyncContext(() => foo())),
  32041. * await __temp,
  32042. * __restore()
  32043. * )
  32044. *
  32045. * const a = await foo()
  32046. * -->
  32047. * const a = (
  32048. * ([__temp, __restore] = withAsyncContext(() => foo())),
  32049. * __temp = await __temp,
  32050. * __restore(),
  32051. * __temp
  32052. * )
  32053. */
  32054. function processAwait(node, needSemi, isStatement) {
  32055. const argumentStart = node.argument.extra && node.argument.extra.parenthesized
  32056. ? node.argument.extra.parenStart
  32057. : node.argument.start;
  32058. const argumentStr = source.slice(argumentStart + startOffset, node.argument.end + startOffset);
  32059. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  32060. s.overwrite(node.start + startOffset, argumentStart + startOffset, `${needSemi ? `;` : ``}(\n ([__temp,__restore] = ${helper(`withAsyncContext`)}(${containsNestedAwait ? `async ` : ``}() => `);
  32061. s.appendLeft(node.end + startOffset, `)),\n ${isStatement ? `` : `__temp = `}await __temp,\n __restore()${isStatement ? `` : `,\n __temp`}\n)`);
  32062. }
  32063. /**
  32064. * check defaults. If the default object is an object literal with only
  32065. * static properties, we can directly generate more optimized default
  32066. * declarations. Otherwise we will have to fallback to runtime merging.
  32067. */
  32068. function hasStaticWithDefaults() {
  32069. return (propsRuntimeDefaults &&
  32070. propsRuntimeDefaults.type === 'ObjectExpression' &&
  32071. propsRuntimeDefaults.properties.every(node => (node.type === 'ObjectProperty' &&
  32072. (!node.computed || node.key.type.endsWith('Literal'))) ||
  32073. node.type === 'ObjectMethod'));
  32074. }
  32075. function genRuntimeProps(props) {
  32076. const keys = Object.keys(props);
  32077. if (!keys.length) {
  32078. return ``;
  32079. }
  32080. const hasStaticDefaults = hasStaticWithDefaults();
  32081. const scriptSetupSource = scriptSetup.content;
  32082. let propsDecls = `{
  32083. ${keys
  32084. .map(key => {
  32085. let defaultString;
  32086. const destructured = genDestructuredDefaultValue(key);
  32087. if (destructured) {
  32088. defaultString = `default: ${destructured}`;
  32089. }
  32090. else if (hasStaticDefaults) {
  32091. const prop = propsRuntimeDefaults.properties.find(node => {
  32092. if (node.type === 'SpreadElement')
  32093. return false;
  32094. return resolveObjectKey(node.key, node.computed) === key;
  32095. });
  32096. if (prop) {
  32097. if (prop.type === 'ObjectProperty') {
  32098. // prop has corresponding static default value
  32099. defaultString = `default: ${scriptSetupSource.slice(prop.value.start, prop.value.end)}`;
  32100. }
  32101. else {
  32102. defaultString = `${prop.async ? 'async ' : ''}${prop.kind !== 'method' ? `${prop.kind} ` : ''}default() ${scriptSetupSource.slice(prop.body.start, prop.body.end)}`;
  32103. }
  32104. }
  32105. }
  32106. const { type, required } = props[key];
  32107. if (!isProd) {
  32108. return `${key}: { type: ${toRuntimeTypeString(type)}, required: ${required}${defaultString ? `, ${defaultString}` : ``} }`;
  32109. }
  32110. else if (type.some(el => el === 'Boolean' ||
  32111. ((!hasStaticDefaults || defaultString) && el === 'Function'))) {
  32112. // #4783 for boolean, should keep the type
  32113. // #7111 for function, if default value exists or it's not static, should keep it
  32114. // in production
  32115. return `${key}: { type: ${toRuntimeTypeString(type)}${defaultString ? `, ${defaultString}` : ``} }`;
  32116. }
  32117. else {
  32118. // production: checks are useless
  32119. return `${key}: ${defaultString ? `{ ${defaultString} }` : 'null'}`;
  32120. }
  32121. })
  32122. .join(',\n ')}\n }`;
  32123. if (propsRuntimeDefaults && !hasStaticDefaults) {
  32124. propsDecls = `${helper('mergeDefaults')}(${propsDecls}, ${source.slice(propsRuntimeDefaults.start + startOffset, propsRuntimeDefaults.end + startOffset)})`;
  32125. }
  32126. return `\n props: ${propsDecls},`;
  32127. }
  32128. function genDestructuredDefaultValue(key) {
  32129. const destructured = propsDestructuredBindings[key];
  32130. if (destructured && destructured.default) {
  32131. const value = scriptSetup.content.slice(destructured.default.start, destructured.default.end);
  32132. const isLiteral = destructured.default.type.endsWith('Literal');
  32133. return isLiteral ? value : `() => (${value})`;
  32134. }
  32135. }
  32136. function genSetupPropsType(node) {
  32137. const scriptSource = node.__fromNormalScript
  32138. ? script.content
  32139. : scriptSetup.content;
  32140. if (hasStaticWithDefaults()) {
  32141. // if withDefaults() is used, we need to remove the optional flags
  32142. // on props that have default values
  32143. let res = `{ `;
  32144. const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
  32145. for (const m of members) {
  32146. if ((m.type === 'TSPropertySignature' ||
  32147. m.type === 'TSMethodSignature') &&
  32148. m.typeAnnotation &&
  32149. m.key.type === 'Identifier') {
  32150. if (propsRuntimeDefaults.properties.some(p => {
  32151. if (p.type === 'SpreadElement')
  32152. return false;
  32153. return (resolveObjectKey(p.key, p.computed) ===
  32154. m.key.name);
  32155. })) {
  32156. res +=
  32157. m.key.name +
  32158. (m.type === 'TSMethodSignature' ? '()' : '') +
  32159. scriptSource.slice(m.typeAnnotation.start, m.typeAnnotation.end) +
  32160. ', ';
  32161. }
  32162. else {
  32163. res += scriptSource.slice(m.start, m.typeAnnotation.end) + `, `;
  32164. }
  32165. }
  32166. }
  32167. return (res.length ? res.slice(0, -2) : res) + ` }`;
  32168. }
  32169. else {
  32170. return scriptSource.slice(node.start, node.end);
  32171. }
  32172. }
  32173. // 0. parse both <script> and <script setup> blocks
  32174. const scriptAst = script &&
  32175. parse(script.content, {
  32176. plugins,
  32177. sourceType: 'module'
  32178. }, scriptStartOffset);
  32179. const scriptSetupAst = parse(scriptSetup.content, {
  32180. plugins: [
  32181. ...plugins,
  32182. // allow top level await but only inside <script setup>
  32183. 'topLevelAwait'
  32184. ],
  32185. sourceType: 'module'
  32186. }, startOffset);
  32187. // 1.1 walk import delcarations of <script>
  32188. if (scriptAst) {
  32189. for (const node of scriptAst.body) {
  32190. if (node.type === 'ImportDeclaration') {
  32191. // record imports for dedupe
  32192. for (const specifier of node.specifiers) {
  32193. const imported = specifier.type === 'ImportSpecifier' &&
  32194. specifier.imported.type === 'Identifier' &&
  32195. specifier.imported.name;
  32196. registerUserImport(node.source.value, specifier.local.name, imported, node.importKind === 'type' ||
  32197. (specifier.type === 'ImportSpecifier' &&
  32198. specifier.importKind === 'type'), false, !options.inlineTemplate);
  32199. }
  32200. }
  32201. }
  32202. }
  32203. // 1.2 walk import declarations of <script setup>
  32204. for (const node of scriptSetupAst.body) {
  32205. if (node.type === 'ImportDeclaration') {
  32206. // import declarations are moved to top
  32207. hoistNode(node);
  32208. // dedupe imports
  32209. let removed = 0;
  32210. const removeSpecifier = (i) => {
  32211. const removeLeft = i > removed;
  32212. removed++;
  32213. const current = node.specifiers[i];
  32214. const next = node.specifiers[i + 1];
  32215. s.remove(removeLeft
  32216. ? node.specifiers[i - 1].end + startOffset
  32217. : current.start + startOffset, next && !removeLeft
  32218. ? next.start + startOffset
  32219. : current.end + startOffset);
  32220. };
  32221. for (let i = 0; i < node.specifiers.length; i++) {
  32222. const specifier = node.specifiers[i];
  32223. const local = specifier.local.name;
  32224. let imported = specifier.type === 'ImportSpecifier' &&
  32225. specifier.imported.type === 'Identifier' &&
  32226. specifier.imported.name;
  32227. if (specifier.type === 'ImportNamespaceSpecifier') {
  32228. imported = '*';
  32229. }
  32230. const source = node.source.value;
  32231. const existing = userImports[local];
  32232. if (source === 'vue' &&
  32233. (imported === DEFINE_PROPS ||
  32234. imported === DEFINE_EMITS ||
  32235. imported === DEFINE_EXPOSE)) {
  32236. warnOnce$4(`\`${imported}\` is a compiler macro and no longer needs to be imported.`);
  32237. removeSpecifier(i);
  32238. }
  32239. else if (existing) {
  32240. if (existing.source === source && existing.imported === imported) {
  32241. // already imported in <script setup>, dedupe
  32242. removeSpecifier(i);
  32243. }
  32244. else {
  32245. error(`different imports aliased to same local name.`, specifier);
  32246. }
  32247. }
  32248. else {
  32249. registerUserImport(source, local, imported, node.importKind === 'type' ||
  32250. (specifier.type === 'ImportSpecifier' &&
  32251. specifier.importKind === 'type'), true, !options.inlineTemplate);
  32252. }
  32253. }
  32254. if (node.specifiers.length && removed === node.specifiers.length) {
  32255. s.remove(node.start + startOffset, node.end + startOffset);
  32256. }
  32257. }
  32258. }
  32259. // 1.3 resolve possible user import alias of `ref` and `reactive`
  32260. const vueImportAliases = {};
  32261. for (const key in userImports) {
  32262. const { source, imported, local } = userImports[key];
  32263. if (source === 'vue')
  32264. vueImportAliases[imported] = local;
  32265. }
  32266. // 2.1 process normal <script> body
  32267. if (script && scriptAst) {
  32268. for (const node of scriptAst.body) {
  32269. if (node.type === 'ExportDefaultDeclaration') {
  32270. // export default
  32271. defaultExport = node;
  32272. // check if user has manually specified `name` or 'render` option in
  32273. // export default
  32274. // if has name, skip name inference
  32275. // if has render and no template, generate return object instead of
  32276. // empty render function (#4980)
  32277. let optionProperties;
  32278. if (defaultExport.declaration.type === 'ObjectExpression') {
  32279. optionProperties = defaultExport.declaration.properties;
  32280. }
  32281. else if (defaultExport.declaration.type === 'CallExpression' &&
  32282. defaultExport.declaration.arguments[0].type === 'ObjectExpression') {
  32283. optionProperties = defaultExport.declaration.arguments[0].properties;
  32284. }
  32285. if (optionProperties) {
  32286. for (const s of optionProperties) {
  32287. if (s.type === 'ObjectProperty' &&
  32288. s.key.type === 'Identifier' &&
  32289. s.key.name === 'name') {
  32290. hasDefaultExportName = true;
  32291. }
  32292. if ((s.type === 'ObjectMethod' || s.type === 'ObjectProperty') &&
  32293. s.key.type === 'Identifier' &&
  32294. s.key.name === 'render') {
  32295. // TODO warn when we provide a better way to do it?
  32296. hasDefaultExportRender = true;
  32297. }
  32298. }
  32299. }
  32300. // export default { ... } --> const __default__ = { ... }
  32301. const start = node.start + scriptStartOffset;
  32302. const end = node.declaration.start + scriptStartOffset;
  32303. s.overwrite(start, end, `const ${DEFAULT_VAR} = `);
  32304. }
  32305. else if (node.type === 'ExportNamedDeclaration') {
  32306. const defaultSpecifier = node.specifiers.find(s => s.exported.type === 'Identifier' && s.exported.name === 'default');
  32307. if (defaultSpecifier) {
  32308. defaultExport = node;
  32309. // 1. remove specifier
  32310. if (node.specifiers.length > 1) {
  32311. s.remove(defaultSpecifier.start + scriptStartOffset, defaultSpecifier.end + scriptStartOffset);
  32312. }
  32313. else {
  32314. s.remove(node.start + scriptStartOffset, node.end + scriptStartOffset);
  32315. }
  32316. if (node.source) {
  32317. // export { x as default } from './x'
  32318. // rewrite to `import { x as __default__ } from './x'` and
  32319. // add to top
  32320. s.prepend(`import { ${defaultSpecifier.local.name} as ${DEFAULT_VAR} } from '${node.source.value}'\n`);
  32321. }
  32322. else {
  32323. // export { x as default }
  32324. // rewrite to `const __default__ = x` and move to end
  32325. s.appendLeft(scriptEndOffset, `\nconst ${DEFAULT_VAR} = ${defaultSpecifier.local.name}\n`);
  32326. }
  32327. }
  32328. if (node.declaration) {
  32329. walkDeclaration(node.declaration, scriptBindings, vueImportAliases);
  32330. }
  32331. }
  32332. else if ((node.type === 'VariableDeclaration' ||
  32333. node.type === 'FunctionDeclaration' ||
  32334. node.type === 'ClassDeclaration' ||
  32335. node.type === 'TSEnumDeclaration') &&
  32336. !node.declare) {
  32337. walkDeclaration(node, scriptBindings, vueImportAliases);
  32338. }
  32339. }
  32340. // apply reactivity transform
  32341. if (enableReactivityTransform && shouldTransform(script.content)) {
  32342. const { rootRefs, importedHelpers } = transformAST(scriptAst, s, scriptStartOffset);
  32343. refBindings = rootRefs;
  32344. for (const h of importedHelpers) {
  32345. helperImports.add(h);
  32346. }
  32347. }
  32348. // <script> after <script setup>
  32349. // we need to move the block up so that `const __default__` is
  32350. // declared before being used in the actual component definition
  32351. if (scriptStartOffset > startOffset) {
  32352. // if content doesn't end with newline, add one
  32353. if (!/\n$/.test(script.content.trim())) {
  32354. s.appendLeft(scriptEndOffset, `\n`);
  32355. }
  32356. s.move(scriptStartOffset, scriptEndOffset, 0);
  32357. }
  32358. }
  32359. // 2.2 process <script setup> body
  32360. for (const node of scriptSetupAst.body) {
  32361. // (Dropped) `ref: x` bindings
  32362. // TODO remove when out of experimental
  32363. if (node.type === 'LabeledStatement' &&
  32364. node.label.name === 'ref' &&
  32365. node.body.type === 'ExpressionStatement') {
  32366. error(`ref sugar using the label syntax was an experimental proposal and ` +
  32367. `has been dropped based on community feedback. Please check out ` +
  32368. `the new proposal at https://github.com/vuejs/rfcs/discussions/369`, node);
  32369. }
  32370. if (node.type === 'ExpressionStatement') {
  32371. // process `defineProps` and `defineEmit(s)` calls
  32372. if (processDefineProps(node.expression) ||
  32373. processDefineEmits(node.expression) ||
  32374. processWithDefaults(node.expression)) {
  32375. s.remove(node.start + startOffset, node.end + startOffset);
  32376. }
  32377. else if (processDefineExpose(node.expression)) {
  32378. // defineExpose({}) -> expose({})
  32379. const callee = node.expression.callee;
  32380. s.overwrite(callee.start + startOffset, callee.end + startOffset, 'expose');
  32381. }
  32382. }
  32383. if (node.type === 'VariableDeclaration' && !node.declare) {
  32384. const total = node.declarations.length;
  32385. let left = total;
  32386. for (let i = 0; i < total; i++) {
  32387. const decl = node.declarations[i];
  32388. if (decl.init) {
  32389. // defineProps / defineEmits
  32390. const isDefineProps = processDefineProps(decl.init, decl.id, node.kind) ||
  32391. processWithDefaults(decl.init, decl.id, node.kind);
  32392. const isDefineEmits = processDefineEmits(decl.init, decl.id);
  32393. if (isDefineProps || isDefineEmits) {
  32394. if (left === 1) {
  32395. s.remove(node.start + startOffset, node.end + startOffset);
  32396. }
  32397. else {
  32398. let start = decl.start + startOffset;
  32399. let end = decl.end + startOffset;
  32400. if (i === 0) {
  32401. // first one, locate the start of the next
  32402. end = node.declarations[i + 1].start + startOffset;
  32403. }
  32404. else {
  32405. // not first one, locate the end of the prev
  32406. start = node.declarations[i - 1].end + startOffset;
  32407. }
  32408. s.remove(start, end);
  32409. left--;
  32410. }
  32411. }
  32412. }
  32413. }
  32414. }
  32415. // walk declarations to record declared bindings
  32416. if ((node.type === 'VariableDeclaration' ||
  32417. node.type === 'FunctionDeclaration' ||
  32418. node.type === 'ClassDeclaration') &&
  32419. !node.declare) {
  32420. walkDeclaration(node, setupBindings, vueImportAliases);
  32421. }
  32422. // walk statements & named exports / variable declarations for top level
  32423. // await
  32424. if ((node.type === 'VariableDeclaration' && !node.declare) ||
  32425. node.type.endsWith('Statement')) {
  32426. const scope = [scriptSetupAst.body];
  32427. walk$1(node, {
  32428. enter(child, parent) {
  32429. if (isFunctionType(child)) {
  32430. this.skip();
  32431. }
  32432. if (child.type === 'BlockStatement') {
  32433. scope.push(child.body);
  32434. }
  32435. if (child.type === 'AwaitExpression') {
  32436. hasAwait = true;
  32437. // if the await expression is an expression statement and
  32438. // - is in the root scope
  32439. // - or is not the first statement in a nested block scope
  32440. // then it needs a semicolon before the generated code.
  32441. const currentScope = scope[scope.length - 1];
  32442. const needsSemi = currentScope.some((n, i) => {
  32443. return ((scope.length === 1 || i > 0) &&
  32444. n.type === 'ExpressionStatement' &&
  32445. n.start === child.start);
  32446. });
  32447. processAwait(child, needsSemi, parent.type === 'ExpressionStatement');
  32448. }
  32449. },
  32450. exit(node) {
  32451. if (node.type === 'BlockStatement')
  32452. scope.pop();
  32453. }
  32454. });
  32455. }
  32456. if ((node.type === 'ExportNamedDeclaration' && node.exportKind !== 'type') ||
  32457. node.type === 'ExportAllDeclaration' ||
  32458. node.type === 'ExportDefaultDeclaration') {
  32459. error(`<script setup> cannot contain ES module exports. ` +
  32460. `If you are using a previous version of <script setup>, please ` +
  32461. `consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.`, node);
  32462. }
  32463. if (isTS) {
  32464. // runtime enum
  32465. if (node.type === 'TSEnumDeclaration') {
  32466. registerBinding(setupBindings, node.id, "setup-const" /* BindingTypes.SETUP_CONST */);
  32467. }
  32468. // move all Type declarations to outer scope
  32469. if (node.type.startsWith('TS') ||
  32470. (node.type === 'ExportNamedDeclaration' &&
  32471. node.exportKind === 'type') ||
  32472. (node.type === 'VariableDeclaration' && node.declare)) {
  32473. recordType(node, declaredTypes);
  32474. hoistNode(node);
  32475. }
  32476. }
  32477. }
  32478. // 3. Apply reactivity transform
  32479. if ((enableReactivityTransform &&
  32480. // normal <script> had ref bindings that maybe used in <script setup>
  32481. (refBindings || shouldTransform(scriptSetup.content))) ||
  32482. propsDestructureDecl) {
  32483. const { rootRefs, importedHelpers } = transformAST(scriptSetupAst, s, startOffset, refBindings, propsDestructuredBindings);
  32484. refBindings = refBindings ? [...refBindings, ...rootRefs] : rootRefs;
  32485. for (const h of importedHelpers) {
  32486. helperImports.add(h);
  32487. }
  32488. }
  32489. // 4. extract runtime props/emits code from setup context type
  32490. if (propsTypeDecl) {
  32491. extractRuntimeProps(propsTypeDecl, typeDeclaredProps, declaredTypes);
  32492. }
  32493. if (emitsTypeDecl) {
  32494. extractRuntimeEmits(emitsTypeDecl, typeDeclaredEmits);
  32495. }
  32496. // 5. check useOptions args to make sure it doesn't reference setup scope
  32497. // variables
  32498. checkInvalidScopeReference(propsRuntimeDecl, DEFINE_PROPS);
  32499. checkInvalidScopeReference(propsRuntimeDefaults, DEFINE_PROPS);
  32500. checkInvalidScopeReference(propsDestructureDecl, DEFINE_PROPS);
  32501. checkInvalidScopeReference(emitsRuntimeDecl, DEFINE_EMITS);
  32502. // 6. remove non-script content
  32503. if (script) {
  32504. if (startOffset < scriptStartOffset) {
  32505. // <script setup> before <script>
  32506. s.remove(0, startOffset);
  32507. s.remove(endOffset, scriptStartOffset);
  32508. s.remove(scriptEndOffset, source.length);
  32509. }
  32510. else {
  32511. // <script> before <script setup>
  32512. s.remove(0, scriptStartOffset);
  32513. s.remove(scriptEndOffset, startOffset);
  32514. s.remove(endOffset, source.length);
  32515. }
  32516. }
  32517. else {
  32518. // only <script setup>
  32519. s.remove(0, startOffset);
  32520. s.remove(endOffset, source.length);
  32521. }
  32522. // 7. analyze binding metadata
  32523. if (scriptAst) {
  32524. Object.assign(bindingMetadata, analyzeScriptBindings(scriptAst.body));
  32525. }
  32526. if (propsRuntimeDecl) {
  32527. for (const key of getObjectOrArrayExpressionKeys(propsRuntimeDecl)) {
  32528. bindingMetadata[key] = "props" /* BindingTypes.PROPS */;
  32529. }
  32530. }
  32531. for (const key in typeDeclaredProps) {
  32532. bindingMetadata[key] = "props" /* BindingTypes.PROPS */;
  32533. }
  32534. // props aliases
  32535. if (propsDestructureDecl) {
  32536. if (propsDestructureRestId) {
  32537. bindingMetadata[propsDestructureRestId] =
  32538. "setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */;
  32539. }
  32540. for (const key in propsDestructuredBindings) {
  32541. const { local } = propsDestructuredBindings[key];
  32542. if (local !== key) {
  32543. bindingMetadata[local] = "props-aliased" /* BindingTypes.PROPS_ALIASED */;
  32544. (bindingMetadata.__propsAliases ||
  32545. (bindingMetadata.__propsAliases = {}))[local] = key;
  32546. }
  32547. }
  32548. }
  32549. for (const [key, { isType, imported, source }] of Object.entries(userImports)) {
  32550. if (isType)
  32551. continue;
  32552. bindingMetadata[key] =
  32553. imported === '*' ||
  32554. (imported === 'default' && source.endsWith('.vue')) ||
  32555. source === 'vue'
  32556. ? "setup-const" /* BindingTypes.SETUP_CONST */
  32557. : "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */;
  32558. }
  32559. for (const key in scriptBindings) {
  32560. bindingMetadata[key] = scriptBindings[key];
  32561. }
  32562. for (const key in setupBindings) {
  32563. bindingMetadata[key] = setupBindings[key];
  32564. }
  32565. // known ref bindings
  32566. if (refBindings) {
  32567. for (const key of refBindings) {
  32568. bindingMetadata[key] = "setup-ref" /* BindingTypes.SETUP_REF */;
  32569. }
  32570. }
  32571. // 8. inject `useCssVars` calls
  32572. if (cssVars.length &&
  32573. // no need to do this when targeting SSR
  32574. !(options.inlineTemplate && ((_a = options.templateOptions) === null || _a === void 0 ? void 0 : _a.ssr))) {
  32575. helperImports.add(CSS_VARS_HELPER);
  32576. helperImports.add('unref');
  32577. s.prependRight(startOffset, `\n${genCssVarsCode(cssVars, bindingMetadata, scopeId, isProd)}\n`);
  32578. }
  32579. // 9. finalize setup() argument signature
  32580. let args = `__props`;
  32581. if (propsTypeDecl) {
  32582. // mark as any and only cast on assignment
  32583. // since the user defined complex types may be incompatible with the
  32584. // inferred type from generated runtime declarations
  32585. args += `: any`;
  32586. }
  32587. // inject user assignment of props
  32588. // we use a default __props so that template expressions referencing props
  32589. // can use it directly
  32590. if (propsIdentifier) {
  32591. s.prependLeft(startOffset, `\nconst ${propsIdentifier} = __props${propsTypeDecl ? ` as ${genSetupPropsType(propsTypeDecl)}` : ``};\n`);
  32592. }
  32593. if (propsDestructureRestId) {
  32594. s.prependLeft(startOffset, `\nconst ${propsDestructureRestId} = ${helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(Object.keys(propsDestructuredBindings))});\n`);
  32595. }
  32596. // inject temp variables for async context preservation
  32597. if (hasAwait) {
  32598. const any = isTS ? `: any` : ``;
  32599. s.prependLeft(startOffset, `\nlet __temp${any}, __restore${any}\n`);
  32600. }
  32601. const destructureElements = hasDefineExposeCall || !options.inlineTemplate ? [`expose`] : [];
  32602. if (emitIdentifier) {
  32603. destructureElements.push(emitIdentifier === `emit` ? `emit` : `emit: ${emitIdentifier}`);
  32604. }
  32605. if (destructureElements.length) {
  32606. args += `, { ${destructureElements.join(', ')} }`;
  32607. if (emitsTypeDecl) {
  32608. const content = emitsTypeDecl.__fromNormalScript
  32609. ? script.content
  32610. : scriptSetup.content;
  32611. args += `: { emit: (${content.slice(emitsTypeDecl.start, emitsTypeDecl.end)}), expose: any, slots: any, attrs: any }`;
  32612. }
  32613. }
  32614. // 10. generate return statement
  32615. let returned;
  32616. if (!options.inlineTemplate || (!sfc.template && hasDefaultExportRender)) {
  32617. // non-inline mode, or has manual render in normal <script>
  32618. // return bindings from script and script setup
  32619. const allBindings = Object.assign(Object.assign({}, scriptBindings), setupBindings);
  32620. for (const key in userImports) {
  32621. if (!userImports[key].isType && userImports[key].isUsedInTemplate) {
  32622. allBindings[key] = true;
  32623. }
  32624. }
  32625. returned = `{ `;
  32626. for (const key in allBindings) {
  32627. if (allBindings[key] === true &&
  32628. userImports[key].source !== 'vue' &&
  32629. !userImports[key].source.endsWith('.vue')) {
  32630. // generate getter for import bindings
  32631. // skip vue imports since we know they will never change
  32632. returned += `get ${key}() { return ${key} }, `;
  32633. }
  32634. else if (bindingMetadata[key] === "setup-let" /* BindingTypes.SETUP_LET */) {
  32635. // local let binding, also add setter
  32636. const setArg = key === 'v' ? `_v` : `v`;
  32637. returned +=
  32638. `get ${key}() { return ${key} }, ` +
  32639. `set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  32640. }
  32641. else {
  32642. returned += `${key}, `;
  32643. }
  32644. }
  32645. returned = returned.replace(/, $/, '') + ` }`;
  32646. }
  32647. else {
  32648. // inline mode
  32649. if (sfc.template && !sfc.template.src) {
  32650. if (options.templateOptions && options.templateOptions.ssr) {
  32651. hasInlinedSsrRenderFn = true;
  32652. }
  32653. // inline render function mode - we are going to compile the template and
  32654. // inline it right here
  32655. const { code, ast, preamble, tips, errors } = compileTemplate(Object.assign(Object.assign({ filename, source: sfc.template.content, inMap: sfc.template.map }, options.templateOptions), { id: scopeId, scoped: sfc.styles.some(s => s.scoped), isProd: options.isProd, ssrCssVars: sfc.cssVars, compilerOptions: Object.assign(Object.assign({}, (options.templateOptions &&
  32656. options.templateOptions.compilerOptions)), { inline: true, isTS,
  32657. bindingMetadata }) }));
  32658. if (tips.length) {
  32659. tips.forEach(warnOnce$4);
  32660. }
  32661. const err = errors[0];
  32662. if (typeof err === 'string') {
  32663. throw new Error(err);
  32664. }
  32665. else if (err) {
  32666. if (err.loc) {
  32667. err.message +=
  32668. `\n\n` +
  32669. sfc.filename +
  32670. '\n' +
  32671. generateCodeFrame(source, err.loc.start.offset, err.loc.end.offset) +
  32672. `\n`;
  32673. }
  32674. throw err;
  32675. }
  32676. if (preamble) {
  32677. s.prepend(preamble);
  32678. }
  32679. // avoid duplicated unref import
  32680. // as this may get injected by the render function preamble OR the
  32681. // css vars codegen
  32682. if (ast && ast.helpers.has(UNREF)) {
  32683. helperImports.delete('unref');
  32684. }
  32685. returned = code;
  32686. }
  32687. else {
  32688. returned = `() => {}`;
  32689. }
  32690. }
  32691. if (!options.inlineTemplate && !false) {
  32692. // in non-inline mode, the `__isScriptSetup: true` flag is used by
  32693. // componentPublicInstance proxy to allow properties that start with $ or _
  32694. s.appendRight(endOffset, `\nconst __returned__ = ${returned}\n` +
  32695. `Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })\n` +
  32696. `return __returned__` +
  32697. `\n}\n\n`);
  32698. }
  32699. else {
  32700. s.appendRight(endOffset, `\nreturn ${returned}\n}\n\n`);
  32701. }
  32702. // 11. finalize default export
  32703. let runtimeOptions = ``;
  32704. if (!hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  32705. const match = filename.match(/([^/\\]+)\.\w+$/);
  32706. if (match) {
  32707. runtimeOptions += `\n __name: '${match[1]}',`;
  32708. }
  32709. }
  32710. if (hasInlinedSsrRenderFn) {
  32711. runtimeOptions += `\n __ssrInlineRender: true,`;
  32712. }
  32713. if (propsRuntimeDecl) {
  32714. let declCode = scriptSetup.content
  32715. .slice(propsRuntimeDecl.start, propsRuntimeDecl.end)
  32716. .trim();
  32717. if (propsDestructureDecl) {
  32718. const defaults = [];
  32719. for (const key in propsDestructuredBindings) {
  32720. const d = genDestructuredDefaultValue(key);
  32721. if (d)
  32722. defaults.push(`${key}: ${d}`);
  32723. }
  32724. if (defaults.length) {
  32725. declCode = `${helper(`mergeDefaults`)}(${declCode}, {\n ${defaults.join(',\n ')}\n})`;
  32726. }
  32727. }
  32728. runtimeOptions += `\n props: ${declCode},`;
  32729. }
  32730. else if (propsTypeDecl) {
  32731. runtimeOptions += genRuntimeProps(typeDeclaredProps);
  32732. }
  32733. if (emitsRuntimeDecl) {
  32734. runtimeOptions += `\n emits: ${scriptSetup.content
  32735. .slice(emitsRuntimeDecl.start, emitsRuntimeDecl.end)
  32736. .trim()},`;
  32737. }
  32738. else if (emitsTypeDecl) {
  32739. runtimeOptions += genRuntimeEmits(typeDeclaredEmits);
  32740. }
  32741. // <script setup> components are closed by default. If the user did not
  32742. // explicitly call `defineExpose`, call expose() with no args.
  32743. const exposeCall = hasDefineExposeCall || options.inlineTemplate ? `` : ` expose();\n`;
  32744. // wrap setup code with function.
  32745. if (isTS) {
  32746. // for TS, make sure the exported type is still valid type with
  32747. // correct props information
  32748. // we have to use object spread for types to be merged properly
  32749. // user's TS setting should compile it down to proper targets
  32750. // export default defineComponent({ ...__default__, ... })
  32751. const def = defaultExport ? `\n ...${DEFAULT_VAR},` : ``;
  32752. s.prependLeft(startOffset, `\nexport default /*#__PURE__*/${helper(`defineComponent`)}({${def}${runtimeOptions}\n ${hasAwait ? `async ` : ``}setup(${args}) {\n${exposeCall}`);
  32753. s.appendRight(endOffset, `})`);
  32754. }
  32755. else {
  32756. if (defaultExport) {
  32757. // without TS, can't rely on rest spread, so we use Object.assign
  32758. // export default Object.assign(__default__, { ... })
  32759. s.prependLeft(startOffset, `\nexport default /*#__PURE__*/Object.assign(${DEFAULT_VAR}, {${runtimeOptions}\n ` +
  32760. `${hasAwait ? `async ` : ``}setup(${args}) {\n${exposeCall}`);
  32761. s.appendRight(endOffset, `})`);
  32762. }
  32763. else {
  32764. s.prependLeft(startOffset, `\nexport default {${runtimeOptions}\n ` +
  32765. `${hasAwait ? `async ` : ``}setup(${args}) {\n${exposeCall}`);
  32766. s.appendRight(endOffset, `}`);
  32767. }
  32768. }
  32769. // 12. finalize Vue helper imports
  32770. if (helperImports.size > 0) {
  32771. s.prepend(`import { ${[...helperImports]
  32772. .map(h => `${h} as _${h}`)
  32773. .join(', ')} } from 'vue'\n`);
  32774. }
  32775. s.trim();
  32776. return Object.assign(Object.assign({}, scriptSetup), { bindings: bindingMetadata, imports: userImports, content: s.toString(), map: genSourceMap
  32777. ? s.generateMap({
  32778. source: filename,
  32779. hires: true,
  32780. includeContent: true
  32781. })
  32782. : undefined, scriptAst: scriptAst === null || scriptAst === void 0 ? void 0 : scriptAst.body, scriptSetupAst: scriptSetupAst === null || scriptSetupAst === void 0 ? void 0 : scriptSetupAst.body });
  32783. }
  32784. function registerBinding(bindings, node, type) {
  32785. bindings[node.name] = type;
  32786. }
  32787. function walkDeclaration(node, bindings, userImportAliases) {
  32788. if (node.type === 'VariableDeclaration') {
  32789. const isConst = node.kind === 'const';
  32790. // export const foo = ...
  32791. for (const { id, init } of node.declarations) {
  32792. const isDefineCall = !!(isConst &&
  32793. isCallOf(init, c => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS));
  32794. if (id.type === 'Identifier') {
  32795. let bindingType;
  32796. const userReactiveBinding = userImportAliases['reactive'];
  32797. if (isCallOf(init, userReactiveBinding)) {
  32798. // treat reactive() calls as let since it's meant to be mutable
  32799. bindingType = isConst
  32800. ? "setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */
  32801. : "setup-let" /* BindingTypes.SETUP_LET */;
  32802. }
  32803. else if (
  32804. // if a declaration is a const literal, we can mark it so that
  32805. // the generated render fn code doesn't need to unref() it
  32806. isDefineCall ||
  32807. (isConst && canNeverBeRef(init, userReactiveBinding))) {
  32808. bindingType = isCallOf(init, DEFINE_PROPS)
  32809. ? "setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */
  32810. : "setup-const" /* BindingTypes.SETUP_CONST */;
  32811. }
  32812. else if (isConst) {
  32813. if (isCallOf(init, userImportAliases['ref'])) {
  32814. bindingType = "setup-ref" /* BindingTypes.SETUP_REF */;
  32815. }
  32816. else {
  32817. bindingType = "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */;
  32818. }
  32819. }
  32820. else {
  32821. bindingType = "setup-let" /* BindingTypes.SETUP_LET */;
  32822. }
  32823. registerBinding(bindings, id, bindingType);
  32824. }
  32825. else {
  32826. if (isCallOf(init, DEFINE_PROPS)) {
  32827. continue;
  32828. }
  32829. if (id.type === 'ObjectPattern') {
  32830. walkObjectPattern(id, bindings, isConst, isDefineCall);
  32831. }
  32832. else if (id.type === 'ArrayPattern') {
  32833. walkArrayPattern(id, bindings, isConst, isDefineCall);
  32834. }
  32835. }
  32836. }
  32837. }
  32838. else if (node.type === 'TSEnumDeclaration' ||
  32839. node.type === 'FunctionDeclaration' ||
  32840. node.type === 'ClassDeclaration') {
  32841. // export function foo() {} / export class Foo {}
  32842. // export declarations must be named.
  32843. bindings[node.id.name] = "setup-const" /* BindingTypes.SETUP_CONST */;
  32844. }
  32845. }
  32846. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  32847. for (const p of node.properties) {
  32848. if (p.type === 'ObjectProperty') {
  32849. if (p.key.type === 'Identifier' && p.key === p.value) {
  32850. // shorthand: const { x } = ...
  32851. const type = isDefineCall
  32852. ? "setup-const" /* BindingTypes.SETUP_CONST */
  32853. : isConst
  32854. ? "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */
  32855. : "setup-let" /* BindingTypes.SETUP_LET */;
  32856. registerBinding(bindings, p.key, type);
  32857. }
  32858. else {
  32859. walkPattern(p.value, bindings, isConst, isDefineCall);
  32860. }
  32861. }
  32862. else {
  32863. // ...rest
  32864. // argument can only be identifier when destructuring
  32865. const type = isConst ? "setup-const" /* BindingTypes.SETUP_CONST */ : "setup-let" /* BindingTypes.SETUP_LET */;
  32866. registerBinding(bindings, p.argument, type);
  32867. }
  32868. }
  32869. }
  32870. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  32871. for (const e of node.elements) {
  32872. e && walkPattern(e, bindings, isConst, isDefineCall);
  32873. }
  32874. }
  32875. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  32876. if (node.type === 'Identifier') {
  32877. const type = isDefineCall
  32878. ? "setup-const" /* BindingTypes.SETUP_CONST */
  32879. : isConst
  32880. ? "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */
  32881. : "setup-let" /* BindingTypes.SETUP_LET */;
  32882. registerBinding(bindings, node, type);
  32883. }
  32884. else if (node.type === 'RestElement') {
  32885. // argument can only be identifier when destructuring
  32886. const type = isConst ? "setup-const" /* BindingTypes.SETUP_CONST */ : "setup-let" /* BindingTypes.SETUP_LET */;
  32887. registerBinding(bindings, node.argument, type);
  32888. }
  32889. else if (node.type === 'ObjectPattern') {
  32890. walkObjectPattern(node, bindings, isConst);
  32891. }
  32892. else if (node.type === 'ArrayPattern') {
  32893. walkArrayPattern(node, bindings, isConst);
  32894. }
  32895. else if (node.type === 'AssignmentPattern') {
  32896. if (node.left.type === 'Identifier') {
  32897. const type = isDefineCall
  32898. ? "setup-const" /* BindingTypes.SETUP_CONST */
  32899. : isConst
  32900. ? "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */
  32901. : "setup-let" /* BindingTypes.SETUP_LET */;
  32902. registerBinding(bindings, node.left, type);
  32903. }
  32904. else {
  32905. walkPattern(node.left, bindings, isConst);
  32906. }
  32907. }
  32908. }
  32909. function recordType(node, declaredTypes) {
  32910. if (node.type === 'TSInterfaceDeclaration') {
  32911. declaredTypes[node.id.name] = [`Object`];
  32912. }
  32913. else if (node.type === 'TSTypeAliasDeclaration') {
  32914. declaredTypes[node.id.name] = inferRuntimeType(node.typeAnnotation, declaredTypes);
  32915. }
  32916. else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
  32917. recordType(node.declaration, declaredTypes);
  32918. }
  32919. }
  32920. function extractRuntimeProps(node, props, declaredTypes, isProd) {
  32921. const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
  32922. for (const m of members) {
  32923. if ((m.type === 'TSPropertySignature' || m.type === 'TSMethodSignature') &&
  32924. m.key.type === 'Identifier') {
  32925. let type;
  32926. if (m.type === 'TSMethodSignature') {
  32927. type = ['Function'];
  32928. }
  32929. else if (m.typeAnnotation) {
  32930. type = inferRuntimeType(m.typeAnnotation.typeAnnotation, declaredTypes);
  32931. }
  32932. props[m.key.name] = {
  32933. key: m.key.name,
  32934. required: !m.optional,
  32935. type: type || [`null`]
  32936. };
  32937. }
  32938. }
  32939. }
  32940. function inferRuntimeType(node, declaredTypes) {
  32941. switch (node.type) {
  32942. case 'TSStringKeyword':
  32943. return ['String'];
  32944. case 'TSNumberKeyword':
  32945. return ['Number'];
  32946. case 'TSBooleanKeyword':
  32947. return ['Boolean'];
  32948. case 'TSObjectKeyword':
  32949. return ['Object'];
  32950. case 'TSTypeLiteral':
  32951. // TODO (nice to have) generate runtime property validation
  32952. return ['Object'];
  32953. case 'TSFunctionType':
  32954. return ['Function'];
  32955. case 'TSArrayType':
  32956. case 'TSTupleType':
  32957. // TODO (nice to have) generate runtime element type/length checks
  32958. return ['Array'];
  32959. case 'TSLiteralType':
  32960. switch (node.literal.type) {
  32961. case 'StringLiteral':
  32962. return ['String'];
  32963. case 'BooleanLiteral':
  32964. return ['Boolean'];
  32965. case 'NumericLiteral':
  32966. case 'BigIntLiteral':
  32967. return ['Number'];
  32968. default:
  32969. return [`null`];
  32970. }
  32971. case 'TSTypeReference':
  32972. if (node.typeName.type === 'Identifier') {
  32973. if (declaredTypes[node.typeName.name]) {
  32974. return declaredTypes[node.typeName.name];
  32975. }
  32976. switch (node.typeName.name) {
  32977. case 'Array':
  32978. case 'Function':
  32979. case 'Object':
  32980. case 'Set':
  32981. case 'Map':
  32982. case 'WeakSet':
  32983. case 'WeakMap':
  32984. case 'Date':
  32985. case 'Promise':
  32986. return [node.typeName.name];
  32987. case 'Record':
  32988. case 'Partial':
  32989. case 'Readonly':
  32990. case 'Pick':
  32991. case 'Omit':
  32992. case 'Exclude':
  32993. case 'Extract':
  32994. case 'Required':
  32995. case 'InstanceType':
  32996. return ['Object'];
  32997. }
  32998. }
  32999. return [`null`];
  33000. case 'TSParenthesizedType':
  33001. return inferRuntimeType(node.typeAnnotation, declaredTypes);
  33002. case 'TSUnionType':
  33003. return [
  33004. ...new Set([].concat(...node.types.map(t => inferRuntimeType(t, declaredTypes))))
  33005. ];
  33006. case 'TSIntersectionType':
  33007. return ['Object'];
  33008. case 'TSSymbolKeyword':
  33009. return ['Symbol'];
  33010. default:
  33011. return [`null`]; // no runtime check
  33012. }
  33013. }
  33014. function toRuntimeTypeString(types) {
  33015. return types.length > 1 ? `[${types.join(', ')}]` : types[0];
  33016. }
  33017. function extractRuntimeEmits(node, emits) {
  33018. if (node.type === 'TSTypeLiteral' || node.type === 'TSInterfaceBody') {
  33019. const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
  33020. for (let t of members) {
  33021. if (t.type === 'TSCallSignatureDeclaration') {
  33022. extractEventNames(t.parameters[0], emits);
  33023. }
  33024. }
  33025. return;
  33026. }
  33027. else {
  33028. extractEventNames(node.parameters[0], emits);
  33029. }
  33030. }
  33031. function extractEventNames(eventName, emits) {
  33032. if (eventName.type === 'Identifier' &&
  33033. eventName.typeAnnotation &&
  33034. eventName.typeAnnotation.type === 'TSTypeAnnotation') {
  33035. const typeNode = eventName.typeAnnotation.typeAnnotation;
  33036. if (typeNode.type === 'TSLiteralType') {
  33037. if (typeNode.literal.type !== 'UnaryExpression') {
  33038. emits.add(String(typeNode.literal.value));
  33039. }
  33040. }
  33041. else if (typeNode.type === 'TSUnionType') {
  33042. for (const t of typeNode.types) {
  33043. if (t.type === 'TSLiteralType' &&
  33044. t.literal.type !== 'UnaryExpression') {
  33045. emits.add(String(t.literal.value));
  33046. }
  33047. }
  33048. }
  33049. }
  33050. }
  33051. function genRuntimeEmits(emits) {
  33052. return emits.size
  33053. ? `\n emits: [${Array.from(emits)
  33054. .map(p => JSON.stringify(p))
  33055. .join(', ')}],`
  33056. : ``;
  33057. }
  33058. function isCallOf(node, test) {
  33059. return !!(node &&
  33060. test &&
  33061. node.type === 'CallExpression' &&
  33062. node.callee.type === 'Identifier' &&
  33063. (typeof test === 'string'
  33064. ? node.callee.name === test
  33065. : test(node.callee.name)));
  33066. }
  33067. function canNeverBeRef(node, userReactiveImport) {
  33068. if (isCallOf(node, userReactiveImport)) {
  33069. return true;
  33070. }
  33071. switch (node.type) {
  33072. case 'UnaryExpression':
  33073. case 'BinaryExpression':
  33074. case 'ArrayExpression':
  33075. case 'ObjectExpression':
  33076. case 'FunctionExpression':
  33077. case 'ArrowFunctionExpression':
  33078. case 'UpdateExpression':
  33079. case 'ClassExpression':
  33080. case 'TaggedTemplateExpression':
  33081. return true;
  33082. case 'SequenceExpression':
  33083. return canNeverBeRef(node.expressions[node.expressions.length - 1], userReactiveImport);
  33084. default:
  33085. if (node.type.endsWith('Literal')) {
  33086. return true;
  33087. }
  33088. return false;
  33089. }
  33090. }
  33091. /**
  33092. * Analyze bindings in normal `<script>`
  33093. * Note that `compileScriptSetup` already analyzes bindings as part of its
  33094. * compilation process so this should only be used on single `<script>` SFCs.
  33095. */
  33096. function analyzeScriptBindings(ast) {
  33097. for (const node of ast) {
  33098. if (node.type === 'ExportDefaultDeclaration' &&
  33099. node.declaration.type === 'ObjectExpression') {
  33100. return analyzeBindingsFromOptions(node.declaration);
  33101. }
  33102. }
  33103. return {};
  33104. }
  33105. function analyzeBindingsFromOptions(node) {
  33106. const bindings = {};
  33107. // #3270, #3275
  33108. // mark non-script-setup so we don't resolve components/directives from these
  33109. Object.defineProperty(bindings, '__isScriptSetup', {
  33110. enumerable: false,
  33111. value: false
  33112. });
  33113. for (const property of node.properties) {
  33114. if (property.type === 'ObjectProperty' &&
  33115. !property.computed &&
  33116. property.key.type === 'Identifier') {
  33117. // props
  33118. if (property.key.name === 'props') {
  33119. // props: ['foo']
  33120. // props: { foo: ... }
  33121. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  33122. bindings[key] = "props" /* BindingTypes.PROPS */;
  33123. }
  33124. }
  33125. // inject
  33126. else if (property.key.name === 'inject') {
  33127. // inject: ['foo']
  33128. // inject: { foo: {} }
  33129. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  33130. bindings[key] = "options" /* BindingTypes.OPTIONS */;
  33131. }
  33132. }
  33133. // computed & methods
  33134. else if (property.value.type === 'ObjectExpression' &&
  33135. (property.key.name === 'computed' || property.key.name === 'methods')) {
  33136. // methods: { foo() {} }
  33137. // computed: { foo() {} }
  33138. for (const key of getObjectExpressionKeys(property.value)) {
  33139. bindings[key] = "options" /* BindingTypes.OPTIONS */;
  33140. }
  33141. }
  33142. }
  33143. // setup & data
  33144. else if (property.type === 'ObjectMethod' &&
  33145. property.key.type === 'Identifier' &&
  33146. (property.key.name === 'setup' || property.key.name === 'data')) {
  33147. for (const bodyItem of property.body.body) {
  33148. // setup() {
  33149. // return {
  33150. // foo: null
  33151. // }
  33152. // }
  33153. if (bodyItem.type === 'ReturnStatement' &&
  33154. bodyItem.argument &&
  33155. bodyItem.argument.type === 'ObjectExpression') {
  33156. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  33157. bindings[key] =
  33158. property.key.name === 'setup'
  33159. ? "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */
  33160. : "data" /* BindingTypes.DATA */;
  33161. }
  33162. }
  33163. }
  33164. }
  33165. }
  33166. return bindings;
  33167. }
  33168. function getObjectExpressionKeys(node) {
  33169. const keys = [];
  33170. for (const prop of node.properties) {
  33171. if (prop.type === 'SpreadElement')
  33172. continue;
  33173. const key = resolveObjectKey(prop.key, prop.computed);
  33174. if (key)
  33175. keys.push(String(key));
  33176. }
  33177. return keys;
  33178. }
  33179. function getArrayExpressionKeys(node) {
  33180. const keys = [];
  33181. for (const element of node.elements) {
  33182. if (element && element.type === 'StringLiteral') {
  33183. keys.push(element.value);
  33184. }
  33185. }
  33186. return keys;
  33187. }
  33188. function getObjectOrArrayExpressionKeys(value) {
  33189. if (value.type === 'ArrayExpression') {
  33190. return getArrayExpressionKeys(value);
  33191. }
  33192. if (value.type === 'ObjectExpression') {
  33193. return getObjectExpressionKeys(value);
  33194. }
  33195. return [];
  33196. }
  33197. const templateUsageCheckCache = createCache();
  33198. function resolveTemplateUsageCheckString(sfc) {
  33199. const { content, ast } = sfc.template;
  33200. const cached = templateUsageCheckCache.get(content);
  33201. if (cached) {
  33202. return cached;
  33203. }
  33204. let code = '';
  33205. transform$1(createRoot([ast]), {
  33206. nodeTransforms: [
  33207. node => {
  33208. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  33209. if (!parserOptions.isNativeTag(node.tag) &&
  33210. !parserOptions.isBuiltInComponent(node.tag)) {
  33211. code += `,${camelize(node.tag)},${capitalize$1(camelize(node.tag))}`;
  33212. }
  33213. for (let i = 0; i < node.props.length; i++) {
  33214. const prop = node.props[i];
  33215. if (prop.type === 7 /* NodeTypes.DIRECTIVE */) {
  33216. if (!isBuiltInDir(prop.name)) {
  33217. code += `,v${capitalize$1(camelize(prop.name))}`;
  33218. }
  33219. if (prop.exp) {
  33220. code += `,${processExp(prop.exp.content, prop.name)}`;
  33221. }
  33222. }
  33223. }
  33224. }
  33225. else if (node.type === 5 /* NodeTypes.INTERPOLATION */) {
  33226. code += `,${processExp(node.content.content)}`;
  33227. }
  33228. }
  33229. ]
  33230. });
  33231. code += ';';
  33232. templateUsageCheckCache.set(content, code);
  33233. return code;
  33234. }
  33235. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  33236. function processExp(exp, dir) {
  33237. if (/ as\s+\w|<.*>|:/.test(exp)) {
  33238. if (dir === 'slot') {
  33239. exp = `(${exp})=>{}`;
  33240. }
  33241. else if (dir === 'on') {
  33242. exp = `()=>{return ${exp}}`;
  33243. }
  33244. else if (dir === 'for') {
  33245. const inMatch = exp.match(forAliasRE);
  33246. if (inMatch) {
  33247. const [, LHS, RHS] = inMatch;
  33248. return processExp(`(${LHS})=>{}`) + processExp(RHS);
  33249. }
  33250. }
  33251. let ret = '';
  33252. // has potential type cast or generic arguments that uses types
  33253. const ast = parseExpression_1(exp, { plugins: ['typescript'] });
  33254. walkIdentifiers(ast, node => {
  33255. ret += `,` + node.name;
  33256. });
  33257. return ret;
  33258. }
  33259. return stripStrings(exp);
  33260. }
  33261. function stripStrings(exp) {
  33262. return exp
  33263. .replace(/'[^']*'|"[^"]*"/g, '')
  33264. .replace(/`[^`]+`/g, stripTemplateString);
  33265. }
  33266. function stripTemplateString(str) {
  33267. const interpMatch = str.match(/\${[^}]+}/g);
  33268. if (interpMatch) {
  33269. return interpMatch.map(m => m.slice(2, -1)).join(',');
  33270. }
  33271. return '';
  33272. }
  33273. function isImportUsed(local, sfc) {
  33274. return new RegExp(
  33275. // #4274 escape $ since it's a special char in regex
  33276. // (and is the only regex special char that is valid in identifiers)
  33277. `[^\\w$_]${local.replace(/\$/g, '\\$')}[^\\w$_]`).test(resolveTemplateUsageCheckString(sfc));
  33278. }
  33279. /**
  33280. * Note: this comparison assumes the prev/next script are already identical,
  33281. * and only checks the special case where <script setup lang="ts"> unused import
  33282. * pruning result changes due to template changes.
  33283. */
  33284. function hmrShouldReload(prevImports, next) {
  33285. if (!next.scriptSetup ||
  33286. (next.scriptSetup.lang !== 'ts' && next.scriptSetup.lang !== 'tsx')) {
  33287. return false;
  33288. }
  33289. // for each previous import, check if its used status remain the same based on
  33290. // the next descriptor's template
  33291. for (const key in prevImports) {
  33292. // if an import was previous unused, but now is used, we need to force
  33293. // reload so that the script now includes that import.
  33294. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  33295. return true;
  33296. }
  33297. }
  33298. return false;
  33299. }
  33300. function resolveObjectKey(node, computed) {
  33301. switch (node.type) {
  33302. case 'StringLiteral':
  33303. case 'NumericLiteral':
  33304. return node.value;
  33305. case 'Identifier':
  33306. if (!computed)
  33307. return node.name;
  33308. }
  33309. return undefined;
  33310. }
  33311. const DEFAULT_FILENAME = 'anonymous.vue';
  33312. const sourceToSFC = createCache();
  33313. function parse$5(source, { sourceMap = true, filename = DEFAULT_FILENAME, sourceRoot = '', pad = false, ignoreEmpty = true, compiler = CompilerDOM } = {}) {
  33314. const sourceKey = source + sourceMap + filename + sourceRoot + pad + compiler.parse;
  33315. const cache = sourceToSFC.get(sourceKey);
  33316. if (cache) {
  33317. return cache;
  33318. }
  33319. const descriptor = {
  33320. filename,
  33321. source,
  33322. template: null,
  33323. script: null,
  33324. scriptSetup: null,
  33325. styles: [],
  33326. customBlocks: [],
  33327. cssVars: [],
  33328. slotted: false,
  33329. shouldForceReload: prevImports => hmrShouldReload(prevImports, descriptor)
  33330. };
  33331. const errors = [];
  33332. const ast = compiler.parse(source, {
  33333. // there are no components at SFC parsing level
  33334. isNativeTag: () => true,
  33335. // preserve all whitespaces
  33336. isPreTag: () => true,
  33337. getTextMode: ({ tag, props }, parent) => {
  33338. // all top level elements except <template> are parsed as raw text
  33339. // containers
  33340. if ((!parent && tag !== 'template') ||
  33341. // <template lang="xxx"> should also be treated as raw text
  33342. (tag === 'template' &&
  33343. props.some(p => p.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  33344. p.name === 'lang' &&
  33345. p.value &&
  33346. p.value.content &&
  33347. p.value.content !== 'html'))) {
  33348. return 2 /* TextModes.RAWTEXT */;
  33349. }
  33350. else {
  33351. return 0 /* TextModes.DATA */;
  33352. }
  33353. },
  33354. onError: e => {
  33355. errors.push(e);
  33356. }
  33357. });
  33358. ast.children.forEach(node => {
  33359. if (node.type !== 1 /* NodeTypes.ELEMENT */) {
  33360. return;
  33361. }
  33362. // we only want to keep the nodes that are not empty (when the tag is not a template)
  33363. if (ignoreEmpty &&
  33364. node.tag !== 'template' &&
  33365. isEmpty(node) &&
  33366. !hasSrc(node)) {
  33367. return;
  33368. }
  33369. switch (node.tag) {
  33370. case 'template':
  33371. if (!descriptor.template) {
  33372. const templateBlock = (descriptor.template = createBlock(node, source, false));
  33373. templateBlock.ast = node;
  33374. // warn against 2.x <template functional>
  33375. if (templateBlock.attrs.functional) {
  33376. const err = new SyntaxError(`<template functional> is no longer supported in Vue 3, since ` +
  33377. `functional components no longer have significant performance ` +
  33378. `difference from stateful ones. Just use a normal <template> ` +
  33379. `instead.`);
  33380. err.loc = node.props.find(p => p.name === 'functional').loc;
  33381. errors.push(err);
  33382. }
  33383. }
  33384. else {
  33385. errors.push(createDuplicateBlockError(node));
  33386. }
  33387. break;
  33388. case 'script':
  33389. const scriptBlock = createBlock(node, source, pad);
  33390. const isSetup = !!scriptBlock.attrs.setup;
  33391. if (isSetup && !descriptor.scriptSetup) {
  33392. descriptor.scriptSetup = scriptBlock;
  33393. break;
  33394. }
  33395. if (!isSetup && !descriptor.script) {
  33396. descriptor.script = scriptBlock;
  33397. break;
  33398. }
  33399. errors.push(createDuplicateBlockError(node, isSetup));
  33400. break;
  33401. case 'style':
  33402. const styleBlock = createBlock(node, source, pad);
  33403. if (styleBlock.attrs.vars) {
  33404. errors.push(new SyntaxError(`<style vars> has been replaced by a new proposal: ` +
  33405. `https://github.com/vuejs/rfcs/pull/231`));
  33406. }
  33407. descriptor.styles.push(styleBlock);
  33408. break;
  33409. default:
  33410. descriptor.customBlocks.push(createBlock(node, source, pad));
  33411. break;
  33412. }
  33413. });
  33414. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  33415. errors.push(new SyntaxError(`At least one <template> or <script> is required in a single file component.`));
  33416. }
  33417. if (descriptor.scriptSetup) {
  33418. if (descriptor.scriptSetup.src) {
  33419. errors.push(new SyntaxError(`<script setup> cannot use the "src" attribute because ` +
  33420. `its syntax will be ambiguous outside of the component.`));
  33421. descriptor.scriptSetup = null;
  33422. }
  33423. if (descriptor.script && descriptor.script.src) {
  33424. errors.push(new SyntaxError(`<script> cannot use the "src" attribute when <script setup> is ` +
  33425. `also present because they must be processed together.`));
  33426. descriptor.script = null;
  33427. }
  33428. }
  33429. if (sourceMap) {
  33430. const genMap = (block) => {
  33431. if (block && !block.src) {
  33432. block.map = generateSourceMap(filename, source, block.content, sourceRoot, !pad || block.type === 'template' ? block.loc.start.line - 1 : 0);
  33433. }
  33434. };
  33435. genMap(descriptor.template);
  33436. genMap(descriptor.script);
  33437. descriptor.styles.forEach(genMap);
  33438. descriptor.customBlocks.forEach(genMap);
  33439. }
  33440. // parse CSS vars
  33441. descriptor.cssVars = parseCssVars(descriptor);
  33442. // check if the SFC uses :slotted
  33443. const slottedRE = /(?:::v-|:)slotted\(/;
  33444. descriptor.slotted = descriptor.styles.some(s => s.scoped && slottedRE.test(s.content));
  33445. const result = {
  33446. descriptor,
  33447. errors
  33448. };
  33449. sourceToSFC.set(sourceKey, result);
  33450. return result;
  33451. }
  33452. function createDuplicateBlockError(node, isScriptSetup = false) {
  33453. const err = new SyntaxError(`Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`);
  33454. err.loc = node.loc;
  33455. return err;
  33456. }
  33457. function createBlock(node, source, pad) {
  33458. const type = node.tag;
  33459. let { start, end } = node.loc;
  33460. let content = '';
  33461. if (node.children.length) {
  33462. start = node.children[0].loc.start;
  33463. end = node.children[node.children.length - 1].loc.end;
  33464. content = source.slice(start.offset, end.offset);
  33465. }
  33466. else {
  33467. const offset = node.loc.source.indexOf(`</`);
  33468. if (offset > -1) {
  33469. start = {
  33470. line: start.line,
  33471. column: start.column + offset,
  33472. offset: start.offset + offset
  33473. };
  33474. }
  33475. end = Object.assign({}, start);
  33476. }
  33477. const loc = {
  33478. source: content,
  33479. start,
  33480. end
  33481. };
  33482. const attrs = {};
  33483. const block = {
  33484. type,
  33485. content,
  33486. loc,
  33487. attrs
  33488. };
  33489. if (pad) {
  33490. block.content = padContent(source, block, pad) + block.content;
  33491. }
  33492. node.props.forEach(p => {
  33493. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  33494. attrs[p.name] = p.value ? p.value.content || true : true;
  33495. if (p.name === 'lang') {
  33496. block.lang = p.value && p.value.content;
  33497. }
  33498. else if (p.name === 'src') {
  33499. block.src = p.value && p.value.content;
  33500. }
  33501. else if (type === 'style') {
  33502. if (p.name === 'scoped') {
  33503. block.scoped = true;
  33504. }
  33505. else if (p.name === 'module') {
  33506. block.module = attrs[p.name];
  33507. }
  33508. }
  33509. else if (type === 'script' && p.name === 'setup') {
  33510. block.setup = attrs.setup;
  33511. }
  33512. }
  33513. });
  33514. return block;
  33515. }
  33516. const splitRE = /\r?\n/g;
  33517. const emptyRE = /^(?:\/\/)?\s*$/;
  33518. const replaceRE = /./g;
  33519. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset) {
  33520. const map = new SourceMapGenerator$6({
  33521. file: filename.replace(/\\/g, '/'),
  33522. sourceRoot: sourceRoot.replace(/\\/g, '/')
  33523. });
  33524. map.setSourceContent(filename, source);
  33525. generated.split(splitRE).forEach((line, index) => {
  33526. if (!emptyRE.test(line)) {
  33527. const originalLine = index + 1 + lineOffset;
  33528. const generatedLine = index + 1;
  33529. for (let i = 0; i < line.length; i++) {
  33530. if (!/\s/.test(line[i])) {
  33531. map.addMapping({
  33532. source: filename,
  33533. original: {
  33534. line: originalLine,
  33535. column: i
  33536. },
  33537. generated: {
  33538. line: generatedLine,
  33539. column: i
  33540. }
  33541. });
  33542. }
  33543. }
  33544. }
  33545. });
  33546. return JSON.parse(map.toString());
  33547. }
  33548. function padContent(content, block, pad) {
  33549. content = content.slice(0, block.loc.start.offset);
  33550. if (pad === 'space') {
  33551. return content.replace(replaceRE, ' ');
  33552. }
  33553. else {
  33554. const offset = content.split(splitRE).length;
  33555. const padChar = block.type === 'script' && !block.lang ? '//\n' : '\n';
  33556. return Array(offset).join(padChar);
  33557. }
  33558. }
  33559. function hasSrc(node) {
  33560. return node.props.some(p => {
  33561. if (p.type !== 6 /* NodeTypes.ATTRIBUTE */) {
  33562. return false;
  33563. }
  33564. return p.name === 'src';
  33565. });
  33566. }
  33567. /**
  33568. * Returns true if the node has no children
  33569. * once the empty text nodes (trimmed content) have been filtered out.
  33570. */
  33571. function isEmpty(node) {
  33572. for (let i = 0; i < node.children.length; i++) {
  33573. const child = node.children[i];
  33574. if (child.type !== 2 /* NodeTypes.TEXT */ || child.content.trim() !== '') {
  33575. return false;
  33576. }
  33577. }
  33578. return true;
  33579. }
  33580. var picocolors = {exports: {}};
  33581. // MIT lisence
  33582. // from https://github.com/substack/tty-browserify/blob/1ba769a6429d242f36226538835b4034bf6b7886/index.js
  33583. function isatty() {
  33584. return false;
  33585. }
  33586. function ReadStream() {
  33587. throw new Error('tty.ReadStream is not implemented');
  33588. }
  33589. function WriteStream() {
  33590. throw new Error('tty.ReadStream is not implemented');
  33591. }
  33592. var _polyfillNode_tty = {
  33593. isatty: isatty,
  33594. ReadStream: ReadStream,
  33595. WriteStream: WriteStream
  33596. };
  33597. var _polyfillNode_tty$1 = /*#__PURE__*/Object.freeze({
  33598. __proto__: null,
  33599. ReadStream: ReadStream,
  33600. WriteStream: WriteStream,
  33601. default: _polyfillNode_tty,
  33602. isatty: isatty
  33603. });
  33604. var require$$0 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_tty$1);
  33605. let tty = require$$0;
  33606. let isColorSupported =
  33607. !("NO_COLOR" in ({}) || browser$1.argv.includes("--no-color")) &&
  33608. ("FORCE_COLOR" in ({}) ||
  33609. browser$1.argv.includes("--color") ||
  33610. "" === "win32" ||
  33611. (tty.isatty(1) && browser$1.env.TERM !== "dumb") ||
  33612. "CI" in ({}));
  33613. let formatter =
  33614. (open, close, replace = open) =>
  33615. input => {
  33616. let string = "" + input;
  33617. let index = string.indexOf(close, open.length);
  33618. return ~index
  33619. ? open + replaceClose(string, close, replace, index) + close
  33620. : open + string + close
  33621. };
  33622. let replaceClose = (string, close, replace, index) => {
  33623. let start = string.substring(0, index) + replace;
  33624. let end = string.substring(index + close.length);
  33625. let nextIndex = end.indexOf(close);
  33626. return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
  33627. };
  33628. let createColors = (enabled = isColorSupported) => ({
  33629. isColorSupported: enabled,
  33630. reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
  33631. bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
  33632. dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
  33633. italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
  33634. underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
  33635. inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
  33636. hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
  33637. strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
  33638. black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
  33639. red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
  33640. green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
  33641. yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
  33642. blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
  33643. magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
  33644. cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
  33645. white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
  33646. gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
  33647. bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
  33648. bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
  33649. bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
  33650. bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
  33651. bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
  33652. bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
  33653. bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
  33654. bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
  33655. });
  33656. picocolors.exports = createColors();
  33657. picocolors.exports.createColors = createColors;
  33658. const SINGLE_QUOTE = "'".charCodeAt(0);
  33659. const DOUBLE_QUOTE = '"'.charCodeAt(0);
  33660. const BACKSLASH = '\\'.charCodeAt(0);
  33661. const SLASH = '/'.charCodeAt(0);
  33662. const NEWLINE = '\n'.charCodeAt(0);
  33663. const SPACE = ' '.charCodeAt(0);
  33664. const FEED = '\f'.charCodeAt(0);
  33665. const TAB = '\t'.charCodeAt(0);
  33666. const CR = '\r'.charCodeAt(0);
  33667. const OPEN_SQUARE = '['.charCodeAt(0);
  33668. const CLOSE_SQUARE = ']'.charCodeAt(0);
  33669. const OPEN_PARENTHESES = '('.charCodeAt(0);
  33670. const CLOSE_PARENTHESES = ')'.charCodeAt(0);
  33671. const OPEN_CURLY = '{'.charCodeAt(0);
  33672. const CLOSE_CURLY = '}'.charCodeAt(0);
  33673. const SEMICOLON = ';'.charCodeAt(0);
  33674. const ASTERISK = '*'.charCodeAt(0);
  33675. const COLON = ':'.charCodeAt(0);
  33676. const AT = '@'.charCodeAt(0);
  33677. const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
  33678. const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
  33679. const RE_BAD_BRACKET = /.[\n"'(/\\]/;
  33680. const RE_HEX_ESCAPE = /[\da-f]/i;
  33681. var tokenize$1 = function tokenizer(input, options = {}) {
  33682. let css = input.css.valueOf();
  33683. let ignore = options.ignoreErrors;
  33684. let code, next, quote, content, escape;
  33685. let escaped, escapePos, prev, n, currentToken;
  33686. let length = css.length;
  33687. let pos = 0;
  33688. let buffer = [];
  33689. let returned = [];
  33690. function position() {
  33691. return pos
  33692. }
  33693. function unclosed(what) {
  33694. throw input.error('Unclosed ' + what, pos)
  33695. }
  33696. function endOfFile() {
  33697. return returned.length === 0 && pos >= length
  33698. }
  33699. function nextToken(opts) {
  33700. if (returned.length) return returned.pop()
  33701. if (pos >= length) return
  33702. let ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
  33703. code = css.charCodeAt(pos);
  33704. switch (code) {
  33705. case NEWLINE:
  33706. case SPACE:
  33707. case TAB:
  33708. case CR:
  33709. case FEED: {
  33710. next = pos;
  33711. do {
  33712. next += 1;
  33713. code = css.charCodeAt(next);
  33714. } while (
  33715. code === SPACE ||
  33716. code === NEWLINE ||
  33717. code === TAB ||
  33718. code === CR ||
  33719. code === FEED
  33720. )
  33721. currentToken = ['space', css.slice(pos, next)];
  33722. pos = next - 1;
  33723. break
  33724. }
  33725. case OPEN_SQUARE:
  33726. case CLOSE_SQUARE:
  33727. case OPEN_CURLY:
  33728. case CLOSE_CURLY:
  33729. case COLON:
  33730. case SEMICOLON:
  33731. case CLOSE_PARENTHESES: {
  33732. let controlChar = String.fromCharCode(code);
  33733. currentToken = [controlChar, controlChar, pos];
  33734. break
  33735. }
  33736. case OPEN_PARENTHESES: {
  33737. prev = buffer.length ? buffer.pop()[1] : '';
  33738. n = css.charCodeAt(pos + 1);
  33739. if (
  33740. prev === 'url' &&
  33741. n !== SINGLE_QUOTE &&
  33742. n !== DOUBLE_QUOTE &&
  33743. n !== SPACE &&
  33744. n !== NEWLINE &&
  33745. n !== TAB &&
  33746. n !== FEED &&
  33747. n !== CR
  33748. ) {
  33749. next = pos;
  33750. do {
  33751. escaped = false;
  33752. next = css.indexOf(')', next + 1);
  33753. if (next === -1) {
  33754. if (ignore || ignoreUnclosed) {
  33755. next = pos;
  33756. break
  33757. } else {
  33758. unclosed('bracket');
  33759. }
  33760. }
  33761. escapePos = next;
  33762. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  33763. escapePos -= 1;
  33764. escaped = !escaped;
  33765. }
  33766. } while (escaped)
  33767. currentToken = ['brackets', css.slice(pos, next + 1), pos, next];
  33768. pos = next;
  33769. } else {
  33770. next = css.indexOf(')', pos + 1);
  33771. content = css.slice(pos, next + 1);
  33772. if (next === -1 || RE_BAD_BRACKET.test(content)) {
  33773. currentToken = ['(', '(', pos];
  33774. } else {
  33775. currentToken = ['brackets', content, pos, next];
  33776. pos = next;
  33777. }
  33778. }
  33779. break
  33780. }
  33781. case SINGLE_QUOTE:
  33782. case DOUBLE_QUOTE: {
  33783. quote = code === SINGLE_QUOTE ? "'" : '"';
  33784. next = pos;
  33785. do {
  33786. escaped = false;
  33787. next = css.indexOf(quote, next + 1);
  33788. if (next === -1) {
  33789. if (ignore || ignoreUnclosed) {
  33790. next = pos + 1;
  33791. break
  33792. } else {
  33793. unclosed('string');
  33794. }
  33795. }
  33796. escapePos = next;
  33797. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  33798. escapePos -= 1;
  33799. escaped = !escaped;
  33800. }
  33801. } while (escaped)
  33802. currentToken = ['string', css.slice(pos, next + 1), pos, next];
  33803. pos = next;
  33804. break
  33805. }
  33806. case AT: {
  33807. RE_AT_END.lastIndex = pos + 1;
  33808. RE_AT_END.test(css);
  33809. if (RE_AT_END.lastIndex === 0) {
  33810. next = css.length - 1;
  33811. } else {
  33812. next = RE_AT_END.lastIndex - 2;
  33813. }
  33814. currentToken = ['at-word', css.slice(pos, next + 1), pos, next];
  33815. pos = next;
  33816. break
  33817. }
  33818. case BACKSLASH: {
  33819. next = pos;
  33820. escape = true;
  33821. while (css.charCodeAt(next + 1) === BACKSLASH) {
  33822. next += 1;
  33823. escape = !escape;
  33824. }
  33825. code = css.charCodeAt(next + 1);
  33826. if (
  33827. escape &&
  33828. code !== SLASH &&
  33829. code !== SPACE &&
  33830. code !== NEWLINE &&
  33831. code !== TAB &&
  33832. code !== CR &&
  33833. code !== FEED
  33834. ) {
  33835. next += 1;
  33836. if (RE_HEX_ESCAPE.test(css.charAt(next))) {
  33837. while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) {
  33838. next += 1;
  33839. }
  33840. if (css.charCodeAt(next + 1) === SPACE) {
  33841. next += 1;
  33842. }
  33843. }
  33844. }
  33845. currentToken = ['word', css.slice(pos, next + 1), pos, next];
  33846. pos = next;
  33847. break
  33848. }
  33849. default: {
  33850. if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
  33851. next = css.indexOf('*/', pos + 2) + 1;
  33852. if (next === 0) {
  33853. if (ignore || ignoreUnclosed) {
  33854. next = css.length;
  33855. } else {
  33856. unclosed('comment');
  33857. }
  33858. }
  33859. currentToken = ['comment', css.slice(pos, next + 1), pos, next];
  33860. pos = next;
  33861. } else {
  33862. RE_WORD_END.lastIndex = pos + 1;
  33863. RE_WORD_END.test(css);
  33864. if (RE_WORD_END.lastIndex === 0) {
  33865. next = css.length - 1;
  33866. } else {
  33867. next = RE_WORD_END.lastIndex - 2;
  33868. }
  33869. currentToken = ['word', css.slice(pos, next + 1), pos, next];
  33870. buffer.push(currentToken);
  33871. pos = next;
  33872. }
  33873. break
  33874. }
  33875. }
  33876. pos++;
  33877. return currentToken
  33878. }
  33879. function back(token) {
  33880. returned.push(token);
  33881. }
  33882. return {
  33883. back,
  33884. nextToken,
  33885. endOfFile,
  33886. position
  33887. }
  33888. };
  33889. let pico$1 = picocolors.exports;
  33890. let tokenizer$1 = tokenize$1;
  33891. let Input$5;
  33892. function registerInput(dependant) {
  33893. Input$5 = dependant;
  33894. }
  33895. const HIGHLIGHT_THEME = {
  33896. 'brackets': pico$1.cyan,
  33897. 'at-word': pico$1.cyan,
  33898. 'comment': pico$1.gray,
  33899. 'string': pico$1.green,
  33900. 'class': pico$1.yellow,
  33901. 'hash': pico$1.magenta,
  33902. 'call': pico$1.cyan,
  33903. '(': pico$1.cyan,
  33904. ')': pico$1.cyan,
  33905. '{': pico$1.yellow,
  33906. '}': pico$1.yellow,
  33907. '[': pico$1.yellow,
  33908. ']': pico$1.yellow,
  33909. ':': pico$1.yellow,
  33910. ';': pico$1.yellow
  33911. };
  33912. function getTokenType([type, value], processor) {
  33913. if (type === 'word') {
  33914. if (value[0] === '.') {
  33915. return 'class'
  33916. }
  33917. if (value[0] === '#') {
  33918. return 'hash'
  33919. }
  33920. }
  33921. if (!processor.endOfFile()) {
  33922. let next = processor.nextToken();
  33923. processor.back(next);
  33924. if (next[0] === 'brackets' || next[0] === '(') return 'call'
  33925. }
  33926. return type
  33927. }
  33928. function terminalHighlight$2(css) {
  33929. let processor = tokenizer$1(new Input$5(css), { ignoreErrors: true });
  33930. let result = '';
  33931. while (!processor.endOfFile()) {
  33932. let token = processor.nextToken();
  33933. let color = HIGHLIGHT_THEME[getTokenType(token, processor)];
  33934. if (color) {
  33935. result += token[1]
  33936. .split(/\r?\n/)
  33937. .map(i => color(i))
  33938. .join('\n');
  33939. } else {
  33940. result += token[1];
  33941. }
  33942. }
  33943. return result
  33944. }
  33945. terminalHighlight$2.registerInput = registerInput;
  33946. var terminalHighlight_1 = terminalHighlight$2;
  33947. let pico = picocolors.exports;
  33948. let terminalHighlight$1 = terminalHighlight_1;
  33949. let CssSyntaxError$3 = class CssSyntaxError extends Error {
  33950. constructor(message, line, column, source, file, plugin) {
  33951. super(message);
  33952. this.name = 'CssSyntaxError';
  33953. this.reason = message;
  33954. if (file) {
  33955. this.file = file;
  33956. }
  33957. if (source) {
  33958. this.source = source;
  33959. }
  33960. if (plugin) {
  33961. this.plugin = plugin;
  33962. }
  33963. if (typeof line !== 'undefined' && typeof column !== 'undefined') {
  33964. if (typeof line === 'number') {
  33965. this.line = line;
  33966. this.column = column;
  33967. } else {
  33968. this.line = line.line;
  33969. this.column = line.column;
  33970. this.endLine = column.line;
  33971. this.endColumn = column.column;
  33972. }
  33973. }
  33974. this.setMessage();
  33975. if (Error.captureStackTrace) {
  33976. Error.captureStackTrace(this, CssSyntaxError$3);
  33977. }
  33978. }
  33979. setMessage() {
  33980. this.message = this.plugin ? this.plugin + ': ' : '';
  33981. this.message += this.file ? this.file : '<css input>';
  33982. if (typeof this.line !== 'undefined') {
  33983. this.message += ':' + this.line + ':' + this.column;
  33984. }
  33985. this.message += ': ' + this.reason;
  33986. }
  33987. showSourceCode(color) {
  33988. if (!this.source) return ''
  33989. let css = this.source;
  33990. if (color == null) color = pico.isColorSupported;
  33991. if (terminalHighlight$1) {
  33992. if (color) css = terminalHighlight$1(css);
  33993. }
  33994. let lines = css.split(/\r?\n/);
  33995. let start = Math.max(this.line - 3, 0);
  33996. let end = Math.min(this.line + 2, lines.length);
  33997. let maxWidth = String(end).length;
  33998. let mark, aside;
  33999. if (color) {
  34000. let { bold, red, gray } = pico.createColors(true);
  34001. mark = text => bold(red(text));
  34002. aside = text => gray(text);
  34003. } else {
  34004. mark = aside = str => str;
  34005. }
  34006. return lines
  34007. .slice(start, end)
  34008. .map((line, index) => {
  34009. let number = start + 1 + index;
  34010. let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ';
  34011. if (number === this.line) {
  34012. let spacing =
  34013. aside(gutter.replace(/\d/g, ' ')) +
  34014. line.slice(0, this.column - 1).replace(/[^\t]/g, ' ');
  34015. return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^')
  34016. }
  34017. return ' ' + aside(gutter) + line
  34018. })
  34019. .join('\n')
  34020. }
  34021. toString() {
  34022. let code = this.showSourceCode();
  34023. if (code) {
  34024. code = '\n\n' + code + '\n';
  34025. }
  34026. return this.name + ': ' + this.message + code
  34027. }
  34028. };
  34029. var cssSyntaxError = CssSyntaxError$3;
  34030. CssSyntaxError$3.default = CssSyntaxError$3;
  34031. var symbols = {};
  34032. symbols.isClean = Symbol('isClean');
  34033. symbols.my = Symbol('my');
  34034. const DEFAULT_RAW = {
  34035. colon: ': ',
  34036. indent: ' ',
  34037. beforeDecl: '\n',
  34038. beforeRule: '\n',
  34039. beforeOpen: ' ',
  34040. beforeClose: '\n',
  34041. beforeComment: '\n',
  34042. after: '\n',
  34043. emptyBody: '',
  34044. commentLeft: ' ',
  34045. commentRight: ' ',
  34046. semicolon: false
  34047. };
  34048. function capitalize(str) {
  34049. return str[0].toUpperCase() + str.slice(1)
  34050. }
  34051. let Stringifier$2 = class Stringifier {
  34052. constructor(builder) {
  34053. this.builder = builder;
  34054. }
  34055. stringify(node, semicolon) {
  34056. /* c8 ignore start */
  34057. if (!this[node.type]) {
  34058. throw new Error(
  34059. 'Unknown AST node type ' +
  34060. node.type +
  34061. '. ' +
  34062. 'Maybe you need to change PostCSS stringifier.'
  34063. )
  34064. }
  34065. /* c8 ignore stop */
  34066. this[node.type](node, semicolon);
  34067. }
  34068. document(node) {
  34069. this.body(node);
  34070. }
  34071. root(node) {
  34072. this.body(node);
  34073. if (node.raws.after) this.builder(node.raws.after);
  34074. }
  34075. comment(node) {
  34076. let left = this.raw(node, 'left', 'commentLeft');
  34077. let right = this.raw(node, 'right', 'commentRight');
  34078. this.builder('/*' + left + node.text + right + '*/', node);
  34079. }
  34080. decl(node, semicolon) {
  34081. let between = this.raw(node, 'between', 'colon');
  34082. let string = node.prop + between + this.rawValue(node, 'value');
  34083. if (node.important) {
  34084. string += node.raws.important || ' !important';
  34085. }
  34086. if (semicolon) string += ';';
  34087. this.builder(string, node);
  34088. }
  34089. rule(node) {
  34090. this.block(node, this.rawValue(node, 'selector'));
  34091. if (node.raws.ownSemicolon) {
  34092. this.builder(node.raws.ownSemicolon, node, 'end');
  34093. }
  34094. }
  34095. atrule(node, semicolon) {
  34096. let name = '@' + node.name;
  34097. let params = node.params ? this.rawValue(node, 'params') : '';
  34098. if (typeof node.raws.afterName !== 'undefined') {
  34099. name += node.raws.afterName;
  34100. } else if (params) {
  34101. name += ' ';
  34102. }
  34103. if (node.nodes) {
  34104. this.block(node, name + params);
  34105. } else {
  34106. let end = (node.raws.between || '') + (semicolon ? ';' : '');
  34107. this.builder(name + params + end, node);
  34108. }
  34109. }
  34110. body(node) {
  34111. let last = node.nodes.length - 1;
  34112. while (last > 0) {
  34113. if (node.nodes[last].type !== 'comment') break
  34114. last -= 1;
  34115. }
  34116. let semicolon = this.raw(node, 'semicolon');
  34117. for (let i = 0; i < node.nodes.length; i++) {
  34118. let child = node.nodes[i];
  34119. let before = this.raw(child, 'before');
  34120. if (before) this.builder(before);
  34121. this.stringify(child, last !== i || semicolon);
  34122. }
  34123. }
  34124. block(node, start) {
  34125. let between = this.raw(node, 'between', 'beforeOpen');
  34126. this.builder(start + between + '{', node, 'start');
  34127. let after;
  34128. if (node.nodes && node.nodes.length) {
  34129. this.body(node);
  34130. after = this.raw(node, 'after');
  34131. } else {
  34132. after = this.raw(node, 'after', 'emptyBody');
  34133. }
  34134. if (after) this.builder(after);
  34135. this.builder('}', node, 'end');
  34136. }
  34137. raw(node, own, detect) {
  34138. let value;
  34139. if (!detect) detect = own;
  34140. // Already had
  34141. if (own) {
  34142. value = node.raws[own];
  34143. if (typeof value !== 'undefined') return value
  34144. }
  34145. let parent = node.parent;
  34146. if (detect === 'before') {
  34147. // Hack for first rule in CSS
  34148. if (!parent || (parent.type === 'root' && parent.first === node)) {
  34149. return ''
  34150. }
  34151. // `root` nodes in `document` should use only their own raws
  34152. if (parent && parent.type === 'document') {
  34153. return ''
  34154. }
  34155. }
  34156. // Floating child without parent
  34157. if (!parent) return DEFAULT_RAW[detect]
  34158. // Detect style by other nodes
  34159. let root = node.root();
  34160. if (!root.rawCache) root.rawCache = {};
  34161. if (typeof root.rawCache[detect] !== 'undefined') {
  34162. return root.rawCache[detect]
  34163. }
  34164. if (detect === 'before' || detect === 'after') {
  34165. return this.beforeAfter(node, detect)
  34166. } else {
  34167. let method = 'raw' + capitalize(detect);
  34168. if (this[method]) {
  34169. value = this[method](root, node);
  34170. } else {
  34171. root.walk(i => {
  34172. value = i.raws[own];
  34173. if (typeof value !== 'undefined') return false
  34174. });
  34175. }
  34176. }
  34177. if (typeof value === 'undefined') value = DEFAULT_RAW[detect];
  34178. root.rawCache[detect] = value;
  34179. return value
  34180. }
  34181. rawSemicolon(root) {
  34182. let value;
  34183. root.walk(i => {
  34184. if (i.nodes && i.nodes.length && i.last.type === 'decl') {
  34185. value = i.raws.semicolon;
  34186. if (typeof value !== 'undefined') return false
  34187. }
  34188. });
  34189. return value
  34190. }
  34191. rawEmptyBody(root) {
  34192. let value;
  34193. root.walk(i => {
  34194. if (i.nodes && i.nodes.length === 0) {
  34195. value = i.raws.after;
  34196. if (typeof value !== 'undefined') return false
  34197. }
  34198. });
  34199. return value
  34200. }
  34201. rawIndent(root) {
  34202. if (root.raws.indent) return root.raws.indent
  34203. let value;
  34204. root.walk(i => {
  34205. let p = i.parent;
  34206. if (p && p !== root && p.parent && p.parent === root) {
  34207. if (typeof i.raws.before !== 'undefined') {
  34208. let parts = i.raws.before.split('\n');
  34209. value = parts[parts.length - 1];
  34210. value = value.replace(/\S/g, '');
  34211. return false
  34212. }
  34213. }
  34214. });
  34215. return value
  34216. }
  34217. rawBeforeComment(root, node) {
  34218. let value;
  34219. root.walkComments(i => {
  34220. if (typeof i.raws.before !== 'undefined') {
  34221. value = i.raws.before;
  34222. if (value.includes('\n')) {
  34223. value = value.replace(/[^\n]+$/, '');
  34224. }
  34225. return false
  34226. }
  34227. });
  34228. if (typeof value === 'undefined') {
  34229. value = this.raw(node, null, 'beforeDecl');
  34230. } else if (value) {
  34231. value = value.replace(/\S/g, '');
  34232. }
  34233. return value
  34234. }
  34235. rawBeforeDecl(root, node) {
  34236. let value;
  34237. root.walkDecls(i => {
  34238. if (typeof i.raws.before !== 'undefined') {
  34239. value = i.raws.before;
  34240. if (value.includes('\n')) {
  34241. value = value.replace(/[^\n]+$/, '');
  34242. }
  34243. return false
  34244. }
  34245. });
  34246. if (typeof value === 'undefined') {
  34247. value = this.raw(node, null, 'beforeRule');
  34248. } else if (value) {
  34249. value = value.replace(/\S/g, '');
  34250. }
  34251. return value
  34252. }
  34253. rawBeforeRule(root) {
  34254. let value;
  34255. root.walk(i => {
  34256. if (i.nodes && (i.parent !== root || root.first !== i)) {
  34257. if (typeof i.raws.before !== 'undefined') {
  34258. value = i.raws.before;
  34259. if (value.includes('\n')) {
  34260. value = value.replace(/[^\n]+$/, '');
  34261. }
  34262. return false
  34263. }
  34264. }
  34265. });
  34266. if (value) value = value.replace(/\S/g, '');
  34267. return value
  34268. }
  34269. rawBeforeClose(root) {
  34270. let value;
  34271. root.walk(i => {
  34272. if (i.nodes && i.nodes.length > 0) {
  34273. if (typeof i.raws.after !== 'undefined') {
  34274. value = i.raws.after;
  34275. if (value.includes('\n')) {
  34276. value = value.replace(/[^\n]+$/, '');
  34277. }
  34278. return false
  34279. }
  34280. }
  34281. });
  34282. if (value) value = value.replace(/\S/g, '');
  34283. return value
  34284. }
  34285. rawBeforeOpen(root) {
  34286. let value;
  34287. root.walk(i => {
  34288. if (i.type !== 'decl') {
  34289. value = i.raws.between;
  34290. if (typeof value !== 'undefined') return false
  34291. }
  34292. });
  34293. return value
  34294. }
  34295. rawColon(root) {
  34296. let value;
  34297. root.walkDecls(i => {
  34298. if (typeof i.raws.between !== 'undefined') {
  34299. value = i.raws.between.replace(/[^\s:]/g, '');
  34300. return false
  34301. }
  34302. });
  34303. return value
  34304. }
  34305. beforeAfter(node, detect) {
  34306. let value;
  34307. if (node.type === 'decl') {
  34308. value = this.raw(node, null, 'beforeDecl');
  34309. } else if (node.type === 'comment') {
  34310. value = this.raw(node, null, 'beforeComment');
  34311. } else if (detect === 'before') {
  34312. value = this.raw(node, null, 'beforeRule');
  34313. } else {
  34314. value = this.raw(node, null, 'beforeClose');
  34315. }
  34316. let buf = node.parent;
  34317. let depth = 0;
  34318. while (buf && buf.type !== 'root') {
  34319. depth += 1;
  34320. buf = buf.parent;
  34321. }
  34322. if (value.includes('\n')) {
  34323. let indent = this.raw(node, null, 'indent');
  34324. if (indent.length) {
  34325. for (let step = 0; step < depth; step++) value += indent;
  34326. }
  34327. }
  34328. return value
  34329. }
  34330. rawValue(node, prop) {
  34331. let value = node[prop];
  34332. let raw = node.raws[prop];
  34333. if (raw && raw.value === value) {
  34334. return raw.raw
  34335. }
  34336. return value
  34337. }
  34338. };
  34339. var stringifier = Stringifier$2;
  34340. Stringifier$2.default = Stringifier$2;
  34341. let Stringifier$1 = stringifier;
  34342. function stringify$4(node, builder) {
  34343. let str = new Stringifier$1(builder);
  34344. str.stringify(node);
  34345. }
  34346. var stringify_1 = stringify$4;
  34347. stringify$4.default = stringify$4;
  34348. let { isClean: isClean$2, my: my$2 } = symbols;
  34349. let CssSyntaxError$2 = cssSyntaxError;
  34350. let Stringifier = stringifier;
  34351. let stringify$3 = stringify_1;
  34352. function cloneNode(obj, parent) {
  34353. let cloned = new obj.constructor();
  34354. for (let i in obj) {
  34355. if (!Object.prototype.hasOwnProperty.call(obj, i)) {
  34356. /* c8 ignore next 2 */
  34357. continue
  34358. }
  34359. if (i === 'proxyCache') continue
  34360. let value = obj[i];
  34361. let type = typeof value;
  34362. if (i === 'parent' && type === 'object') {
  34363. if (parent) cloned[i] = parent;
  34364. } else if (i === 'source') {
  34365. cloned[i] = value;
  34366. } else if (Array.isArray(value)) {
  34367. cloned[i] = value.map(j => cloneNode(j, cloned));
  34368. } else {
  34369. if (type === 'object' && value !== null) value = cloneNode(value);
  34370. cloned[i] = value;
  34371. }
  34372. }
  34373. return cloned
  34374. }
  34375. let Node$4 = class Node {
  34376. constructor(defaults = {}) {
  34377. this.raws = {};
  34378. this[isClean$2] = false;
  34379. this[my$2] = true;
  34380. for (let name in defaults) {
  34381. if (name === 'nodes') {
  34382. this.nodes = [];
  34383. for (let node of defaults[name]) {
  34384. if (typeof node.clone === 'function') {
  34385. this.append(node.clone());
  34386. } else {
  34387. this.append(node);
  34388. }
  34389. }
  34390. } else {
  34391. this[name] = defaults[name];
  34392. }
  34393. }
  34394. }
  34395. error(message, opts = {}) {
  34396. if (this.source) {
  34397. let { start, end } = this.rangeBy(opts);
  34398. return this.source.input.error(
  34399. message,
  34400. { line: start.line, column: start.column },
  34401. { line: end.line, column: end.column },
  34402. opts
  34403. )
  34404. }
  34405. return new CssSyntaxError$2(message)
  34406. }
  34407. warn(result, text, opts) {
  34408. let data = { node: this };
  34409. for (let i in opts) data[i] = opts[i];
  34410. return result.warn(text, data)
  34411. }
  34412. remove() {
  34413. if (this.parent) {
  34414. this.parent.removeChild(this);
  34415. }
  34416. this.parent = undefined;
  34417. return this
  34418. }
  34419. toString(stringifier = stringify$3) {
  34420. if (stringifier.stringify) stringifier = stringifier.stringify;
  34421. let result = '';
  34422. stringifier(this, i => {
  34423. result += i;
  34424. });
  34425. return result
  34426. }
  34427. assign(overrides = {}) {
  34428. for (let name in overrides) {
  34429. this[name] = overrides[name];
  34430. }
  34431. return this
  34432. }
  34433. clone(overrides = {}) {
  34434. let cloned = cloneNode(this);
  34435. for (let name in overrides) {
  34436. cloned[name] = overrides[name];
  34437. }
  34438. return cloned
  34439. }
  34440. cloneBefore(overrides = {}) {
  34441. let cloned = this.clone(overrides);
  34442. this.parent.insertBefore(this, cloned);
  34443. return cloned
  34444. }
  34445. cloneAfter(overrides = {}) {
  34446. let cloned = this.clone(overrides);
  34447. this.parent.insertAfter(this, cloned);
  34448. return cloned
  34449. }
  34450. replaceWith(...nodes) {
  34451. if (this.parent) {
  34452. let bookmark = this;
  34453. let foundSelf = false;
  34454. for (let node of nodes) {
  34455. if (node === this) {
  34456. foundSelf = true;
  34457. } else if (foundSelf) {
  34458. this.parent.insertAfter(bookmark, node);
  34459. bookmark = node;
  34460. } else {
  34461. this.parent.insertBefore(bookmark, node);
  34462. }
  34463. }
  34464. if (!foundSelf) {
  34465. this.remove();
  34466. }
  34467. }
  34468. return this
  34469. }
  34470. next() {
  34471. if (!this.parent) return undefined
  34472. let index = this.parent.index(this);
  34473. return this.parent.nodes[index + 1]
  34474. }
  34475. prev() {
  34476. if (!this.parent) return undefined
  34477. let index = this.parent.index(this);
  34478. return this.parent.nodes[index - 1]
  34479. }
  34480. before(add) {
  34481. this.parent.insertBefore(this, add);
  34482. return this
  34483. }
  34484. after(add) {
  34485. this.parent.insertAfter(this, add);
  34486. return this
  34487. }
  34488. root() {
  34489. let result = this;
  34490. while (result.parent && result.parent.type !== 'document') {
  34491. result = result.parent;
  34492. }
  34493. return result
  34494. }
  34495. raw(prop, defaultType) {
  34496. let str = new Stringifier();
  34497. return str.raw(this, prop, defaultType)
  34498. }
  34499. cleanRaws(keepBetween) {
  34500. delete this.raws.before;
  34501. delete this.raws.after;
  34502. if (!keepBetween) delete this.raws.between;
  34503. }
  34504. toJSON(_, inputs) {
  34505. let fixed = {};
  34506. let emitInputs = inputs == null;
  34507. inputs = inputs || new Map();
  34508. let inputsNextIndex = 0;
  34509. for (let name in this) {
  34510. if (!Object.prototype.hasOwnProperty.call(this, name)) {
  34511. /* c8 ignore next 2 */
  34512. continue
  34513. }
  34514. if (name === 'parent' || name === 'proxyCache') continue
  34515. let value = this[name];
  34516. if (Array.isArray(value)) {
  34517. fixed[name] = value.map(i => {
  34518. if (typeof i === 'object' && i.toJSON) {
  34519. return i.toJSON(null, inputs)
  34520. } else {
  34521. return i
  34522. }
  34523. });
  34524. } else if (typeof value === 'object' && value.toJSON) {
  34525. fixed[name] = value.toJSON(null, inputs);
  34526. } else if (name === 'source') {
  34527. let inputId = inputs.get(value.input);
  34528. if (inputId == null) {
  34529. inputId = inputsNextIndex;
  34530. inputs.set(value.input, inputsNextIndex);
  34531. inputsNextIndex++;
  34532. }
  34533. fixed[name] = {
  34534. inputId,
  34535. start: value.start,
  34536. end: value.end
  34537. };
  34538. } else {
  34539. fixed[name] = value;
  34540. }
  34541. }
  34542. if (emitInputs) {
  34543. fixed.inputs = [...inputs.keys()].map(input => input.toJSON());
  34544. }
  34545. return fixed
  34546. }
  34547. positionInside(index) {
  34548. let string = this.toString();
  34549. let column = this.source.start.column;
  34550. let line = this.source.start.line;
  34551. for (let i = 0; i < index; i++) {
  34552. if (string[i] === '\n') {
  34553. column = 1;
  34554. line += 1;
  34555. } else {
  34556. column += 1;
  34557. }
  34558. }
  34559. return { line, column }
  34560. }
  34561. positionBy(opts) {
  34562. let pos = this.source.start;
  34563. if (opts.index) {
  34564. pos = this.positionInside(opts.index);
  34565. } else if (opts.word) {
  34566. let index = this.toString().indexOf(opts.word);
  34567. if (index !== -1) pos = this.positionInside(index);
  34568. }
  34569. return pos
  34570. }
  34571. rangeBy(opts) {
  34572. let start = {
  34573. line: this.source.start.line,
  34574. column: this.source.start.column
  34575. };
  34576. let end = this.source.end
  34577. ? {
  34578. line: this.source.end.line,
  34579. column: this.source.end.column + 1
  34580. }
  34581. : {
  34582. line: start.line,
  34583. column: start.column + 1
  34584. };
  34585. if (opts.word) {
  34586. let index = this.toString().indexOf(opts.word);
  34587. if (index !== -1) {
  34588. start = this.positionInside(index);
  34589. end = this.positionInside(index + opts.word.length);
  34590. }
  34591. } else {
  34592. if (opts.start) {
  34593. start = {
  34594. line: opts.start.line,
  34595. column: opts.start.column
  34596. };
  34597. } else if (opts.index) {
  34598. start = this.positionInside(opts.index);
  34599. }
  34600. if (opts.end) {
  34601. end = {
  34602. line: opts.end.line,
  34603. column: opts.end.column
  34604. };
  34605. } else if (opts.endIndex) {
  34606. end = this.positionInside(opts.endIndex);
  34607. } else if (opts.index) {
  34608. end = this.positionInside(opts.index + 1);
  34609. }
  34610. }
  34611. if (
  34612. end.line < start.line ||
  34613. (end.line === start.line && end.column <= start.column)
  34614. ) {
  34615. end = { line: start.line, column: start.column + 1 };
  34616. }
  34617. return { start, end }
  34618. }
  34619. getProxyProcessor() {
  34620. return {
  34621. set(node, prop, value) {
  34622. if (node[prop] === value) return true
  34623. node[prop] = value;
  34624. if (
  34625. prop === 'prop' ||
  34626. prop === 'value' ||
  34627. prop === 'name' ||
  34628. prop === 'params' ||
  34629. prop === 'important' ||
  34630. /* c8 ignore next */
  34631. prop === 'text'
  34632. ) {
  34633. node.markDirty();
  34634. }
  34635. return true
  34636. },
  34637. get(node, prop) {
  34638. if (prop === 'proxyOf') {
  34639. return node
  34640. } else if (prop === 'root') {
  34641. return () => node.root().toProxy()
  34642. } else {
  34643. return node[prop]
  34644. }
  34645. }
  34646. }
  34647. }
  34648. toProxy() {
  34649. if (!this.proxyCache) {
  34650. this.proxyCache = new Proxy(this, this.getProxyProcessor());
  34651. }
  34652. return this.proxyCache
  34653. }
  34654. addToError(error) {
  34655. error.postcssNode = this;
  34656. if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
  34657. let s = this.source;
  34658. error.stack = error.stack.replace(
  34659. /\n\s{4}at /,
  34660. `$&${s.input.from}:${s.start.line}:${s.start.column}$&`
  34661. );
  34662. }
  34663. return error
  34664. }
  34665. markDirty() {
  34666. if (this[isClean$2]) {
  34667. this[isClean$2] = false;
  34668. let next = this;
  34669. while ((next = next.parent)) {
  34670. next[isClean$2] = false;
  34671. }
  34672. }
  34673. }
  34674. get proxyOf() {
  34675. return this
  34676. }
  34677. };
  34678. var node$2 = Node$4;
  34679. Node$4.default = Node$4;
  34680. let Node$3 = node$2;
  34681. let Declaration$4 = class Declaration extends Node$3 {
  34682. constructor(defaults) {
  34683. if (
  34684. defaults &&
  34685. typeof defaults.value !== 'undefined' &&
  34686. typeof defaults.value !== 'string'
  34687. ) {
  34688. defaults = { ...defaults, value: String(defaults.value) };
  34689. }
  34690. super(defaults);
  34691. this.type = 'decl';
  34692. }
  34693. get variable() {
  34694. return this.prop.startsWith('--') || this.prop[0] === '$'
  34695. }
  34696. };
  34697. var declaration = Declaration$4;
  34698. Declaration$4.default = Declaration$4;
  34699. var sourceMap$1 = {};
  34700. var sourceMapGenerator = {};
  34701. var base64Vlq = {};
  34702. var base64$1 = {};
  34703. /* -*- Mode: js; js-indent-level: 2; -*- */
  34704. /*
  34705. * Copyright 2011 Mozilla Foundation and contributors
  34706. * Licensed under the New BSD license. See LICENSE or:
  34707. * http://opensource.org/licenses/BSD-3-Clause
  34708. */
  34709. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  34710. /**
  34711. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  34712. */
  34713. base64$1.encode = function (number) {
  34714. if (0 <= number && number < intToCharMap.length) {
  34715. return intToCharMap[number];
  34716. }
  34717. throw new TypeError("Must be between 0 and 63: " + number);
  34718. };
  34719. /**
  34720. * Decode a single base 64 character code digit to an integer. Returns -1 on
  34721. * failure.
  34722. */
  34723. base64$1.decode = function (charCode) {
  34724. var bigA = 65; // 'A'
  34725. var bigZ = 90; // 'Z'
  34726. var littleA = 97; // 'a'
  34727. var littleZ = 122; // 'z'
  34728. var zero = 48; // '0'
  34729. var nine = 57; // '9'
  34730. var plus = 43; // '+'
  34731. var slash = 47; // '/'
  34732. var littleOffset = 26;
  34733. var numberOffset = 52;
  34734. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  34735. if (bigA <= charCode && charCode <= bigZ) {
  34736. return (charCode - bigA);
  34737. }
  34738. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  34739. if (littleA <= charCode && charCode <= littleZ) {
  34740. return (charCode - littleA + littleOffset);
  34741. }
  34742. // 52 - 61: 0123456789
  34743. if (zero <= charCode && charCode <= nine) {
  34744. return (charCode - zero + numberOffset);
  34745. }
  34746. // 62: +
  34747. if (charCode == plus) {
  34748. return 62;
  34749. }
  34750. // 63: /
  34751. if (charCode == slash) {
  34752. return 63;
  34753. }
  34754. // Invalid base64 digit.
  34755. return -1;
  34756. };
  34757. /* -*- Mode: js; js-indent-level: 2; -*- */
  34758. /*
  34759. * Copyright 2011 Mozilla Foundation and contributors
  34760. * Licensed under the New BSD license. See LICENSE or:
  34761. * http://opensource.org/licenses/BSD-3-Clause
  34762. *
  34763. * Based on the Base 64 VLQ implementation in Closure Compiler:
  34764. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  34765. *
  34766. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  34767. * Redistribution and use in source and binary forms, with or without
  34768. * modification, are permitted provided that the following conditions are
  34769. * met:
  34770. *
  34771. * * Redistributions of source code must retain the above copyright
  34772. * notice, this list of conditions and the following disclaimer.
  34773. * * Redistributions in binary form must reproduce the above
  34774. * copyright notice, this list of conditions and the following
  34775. * disclaimer in the documentation and/or other materials provided
  34776. * with the distribution.
  34777. * * Neither the name of Google Inc. nor the names of its
  34778. * contributors may be used to endorse or promote products derived
  34779. * from this software without specific prior written permission.
  34780. *
  34781. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  34782. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  34783. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  34784. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  34785. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  34786. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  34787. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  34788. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  34789. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  34790. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  34791. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  34792. */
  34793. var base64 = base64$1;
  34794. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  34795. // length quantities we use in the source map spec, the first bit is the sign,
  34796. // the next four bits are the actual value, and the 6th bit is the
  34797. // continuation bit. The continuation bit tells us whether there are more
  34798. // digits in this value following this digit.
  34799. //
  34800. // Continuation
  34801. // | Sign
  34802. // | |
  34803. // V V
  34804. // 101011
  34805. var VLQ_BASE_SHIFT = 5;
  34806. // binary: 100000
  34807. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  34808. // binary: 011111
  34809. var VLQ_BASE_MASK = VLQ_BASE - 1;
  34810. // binary: 100000
  34811. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  34812. /**
  34813. * Converts from a two-complement value to a value where the sign bit is
  34814. * placed in the least significant bit. For example, as decimals:
  34815. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  34816. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  34817. */
  34818. function toVLQSigned(aValue) {
  34819. return aValue < 0
  34820. ? ((-aValue) << 1) + 1
  34821. : (aValue << 1) + 0;
  34822. }
  34823. /**
  34824. * Converts to a two-complement value from a value where the sign bit is
  34825. * placed in the least significant bit. For example, as decimals:
  34826. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  34827. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  34828. */
  34829. function fromVLQSigned(aValue) {
  34830. var isNegative = (aValue & 1) === 1;
  34831. var shifted = aValue >> 1;
  34832. return isNegative
  34833. ? -shifted
  34834. : shifted;
  34835. }
  34836. /**
  34837. * Returns the base 64 VLQ encoded value.
  34838. */
  34839. base64Vlq.encode = function base64VLQ_encode(aValue) {
  34840. var encoded = "";
  34841. var digit;
  34842. var vlq = toVLQSigned(aValue);
  34843. do {
  34844. digit = vlq & VLQ_BASE_MASK;
  34845. vlq >>>= VLQ_BASE_SHIFT;
  34846. if (vlq > 0) {
  34847. // There are still more digits in this value, so we must make sure the
  34848. // continuation bit is marked.
  34849. digit |= VLQ_CONTINUATION_BIT;
  34850. }
  34851. encoded += base64.encode(digit);
  34852. } while (vlq > 0);
  34853. return encoded;
  34854. };
  34855. /**
  34856. * Decodes the next base 64 VLQ value from the given string and returns the
  34857. * value and the rest of the string via the out parameter.
  34858. */
  34859. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  34860. var strLen = aStr.length;
  34861. var result = 0;
  34862. var shift = 0;
  34863. var continuation, digit;
  34864. do {
  34865. if (aIndex >= strLen) {
  34866. throw new Error("Expected more digits in base 64 VLQ value.");
  34867. }
  34868. digit = base64.decode(aStr.charCodeAt(aIndex++));
  34869. if (digit === -1) {
  34870. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  34871. }
  34872. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  34873. digit &= VLQ_BASE_MASK;
  34874. result = result + (digit << shift);
  34875. shift += VLQ_BASE_SHIFT;
  34876. } while (continuation);
  34877. aOutParam.value = fromVLQSigned(result);
  34878. aOutParam.rest = aIndex;
  34879. };
  34880. var util$6 = {};
  34881. /* -*- Mode: js; js-indent-level: 2; -*- */
  34882. (function (exports) {
  34883. /*
  34884. * Copyright 2011 Mozilla Foundation and contributors
  34885. * Licensed under the New BSD license. See LICENSE or:
  34886. * http://opensource.org/licenses/BSD-3-Clause
  34887. */
  34888. /**
  34889. * This is a helper function for getting values from parameter/options
  34890. * objects.
  34891. *
  34892. * @param args The object we are extracting values from
  34893. * @param name The name of the property we are getting.
  34894. * @param defaultValue An optional value to return if the property is missing
  34895. * from the object. If this is not specified and the property is missing, an
  34896. * error will be thrown.
  34897. */
  34898. function getArg(aArgs, aName, aDefaultValue) {
  34899. if (aName in aArgs) {
  34900. return aArgs[aName];
  34901. } else if (arguments.length === 3) {
  34902. return aDefaultValue;
  34903. } else {
  34904. throw new Error('"' + aName + '" is a required argument.');
  34905. }
  34906. }
  34907. exports.getArg = getArg;
  34908. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  34909. var dataUrlRegexp = /^data:.+\,.+$/;
  34910. function urlParse(aUrl) {
  34911. var match = aUrl.match(urlRegexp);
  34912. if (!match) {
  34913. return null;
  34914. }
  34915. return {
  34916. scheme: match[1],
  34917. auth: match[2],
  34918. host: match[3],
  34919. port: match[4],
  34920. path: match[5]
  34921. };
  34922. }
  34923. exports.urlParse = urlParse;
  34924. function urlGenerate(aParsedUrl) {
  34925. var url = '';
  34926. if (aParsedUrl.scheme) {
  34927. url += aParsedUrl.scheme + ':';
  34928. }
  34929. url += '//';
  34930. if (aParsedUrl.auth) {
  34931. url += aParsedUrl.auth + '@';
  34932. }
  34933. if (aParsedUrl.host) {
  34934. url += aParsedUrl.host;
  34935. }
  34936. if (aParsedUrl.port) {
  34937. url += ":" + aParsedUrl.port;
  34938. }
  34939. if (aParsedUrl.path) {
  34940. url += aParsedUrl.path;
  34941. }
  34942. return url;
  34943. }
  34944. exports.urlGenerate = urlGenerate;
  34945. var MAX_CACHED_INPUTS = 32;
  34946. /**
  34947. * Takes some function `f(input) -> result` and returns a memoized version of
  34948. * `f`.
  34949. *
  34950. * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
  34951. * memoization is a dumb-simple, linear least-recently-used cache.
  34952. */
  34953. function lruMemoize(f) {
  34954. var cache = [];
  34955. return function(input) {
  34956. for (var i = 0; i < cache.length; i++) {
  34957. if (cache[i].input === input) {
  34958. var temp = cache[0];
  34959. cache[0] = cache[i];
  34960. cache[i] = temp;
  34961. return cache[0].result;
  34962. }
  34963. }
  34964. var result = f(input);
  34965. cache.unshift({
  34966. input,
  34967. result,
  34968. });
  34969. if (cache.length > MAX_CACHED_INPUTS) {
  34970. cache.pop();
  34971. }
  34972. return result;
  34973. };
  34974. }
  34975. /**
  34976. * Normalizes a path, or the path portion of a URL:
  34977. *
  34978. * - Replaces consecutive slashes with one slash.
  34979. * - Removes unnecessary '.' parts.
  34980. * - Removes unnecessary '<dir>/..' parts.
  34981. *
  34982. * Based on code in the Node.js 'path' core module.
  34983. *
  34984. * @param aPath The path or url to normalize.
  34985. */
  34986. var normalize = lruMemoize(function normalize(aPath) {
  34987. var path = aPath;
  34988. var url = urlParse(aPath);
  34989. if (url) {
  34990. if (!url.path) {
  34991. return aPath;
  34992. }
  34993. path = url.path;
  34994. }
  34995. var isAbsolute = exports.isAbsolute(path);
  34996. // Split the path into parts between `/` characters. This is much faster than
  34997. // using `.split(/\/+/g)`.
  34998. var parts = [];
  34999. var start = 0;
  35000. var i = 0;
  35001. while (true) {
  35002. start = i;
  35003. i = path.indexOf("/", start);
  35004. if (i === -1) {
  35005. parts.push(path.slice(start));
  35006. break;
  35007. } else {
  35008. parts.push(path.slice(start, i));
  35009. while (i < path.length && path[i] === "/") {
  35010. i++;
  35011. }
  35012. }
  35013. }
  35014. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  35015. part = parts[i];
  35016. if (part === '.') {
  35017. parts.splice(i, 1);
  35018. } else if (part === '..') {
  35019. up++;
  35020. } else if (up > 0) {
  35021. if (part === '') {
  35022. // The first part is blank if the path is absolute. Trying to go
  35023. // above the root is a no-op. Therefore we can remove all '..' parts
  35024. // directly after the root.
  35025. parts.splice(i + 1, up);
  35026. up = 0;
  35027. } else {
  35028. parts.splice(i, 2);
  35029. up--;
  35030. }
  35031. }
  35032. }
  35033. path = parts.join('/');
  35034. if (path === '') {
  35035. path = isAbsolute ? '/' : '.';
  35036. }
  35037. if (url) {
  35038. url.path = path;
  35039. return urlGenerate(url);
  35040. }
  35041. return path;
  35042. });
  35043. exports.normalize = normalize;
  35044. /**
  35045. * Joins two paths/URLs.
  35046. *
  35047. * @param aRoot The root path or URL.
  35048. * @param aPath The path or URL to be joined with the root.
  35049. *
  35050. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  35051. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  35052. * first.
  35053. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  35054. * is updated with the result and aRoot is returned. Otherwise the result
  35055. * is returned.
  35056. * - If aPath is absolute, the result is aPath.
  35057. * - Otherwise the two paths are joined with a slash.
  35058. * - Joining for example 'http://' and 'www.example.com' is also supported.
  35059. */
  35060. function join(aRoot, aPath) {
  35061. if (aRoot === "") {
  35062. aRoot = ".";
  35063. }
  35064. if (aPath === "") {
  35065. aPath = ".";
  35066. }
  35067. var aPathUrl = urlParse(aPath);
  35068. var aRootUrl = urlParse(aRoot);
  35069. if (aRootUrl) {
  35070. aRoot = aRootUrl.path || '/';
  35071. }
  35072. // `join(foo, '//www.example.org')`
  35073. if (aPathUrl && !aPathUrl.scheme) {
  35074. if (aRootUrl) {
  35075. aPathUrl.scheme = aRootUrl.scheme;
  35076. }
  35077. return urlGenerate(aPathUrl);
  35078. }
  35079. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  35080. return aPath;
  35081. }
  35082. // `join('http://', 'www.example.com')`
  35083. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  35084. aRootUrl.host = aPath;
  35085. return urlGenerate(aRootUrl);
  35086. }
  35087. var joined = aPath.charAt(0) === '/'
  35088. ? aPath
  35089. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  35090. if (aRootUrl) {
  35091. aRootUrl.path = joined;
  35092. return urlGenerate(aRootUrl);
  35093. }
  35094. return joined;
  35095. }
  35096. exports.join = join;
  35097. exports.isAbsolute = function (aPath) {
  35098. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  35099. };
  35100. /**
  35101. * Make a path relative to a URL or another path.
  35102. *
  35103. * @param aRoot The root path or URL.
  35104. * @param aPath The path or URL to be made relative to aRoot.
  35105. */
  35106. function relative(aRoot, aPath) {
  35107. if (aRoot === "") {
  35108. aRoot = ".";
  35109. }
  35110. aRoot = aRoot.replace(/\/$/, '');
  35111. // It is possible for the path to be above the root. In this case, simply
  35112. // checking whether the root is a prefix of the path won't work. Instead, we
  35113. // need to remove components from the root one by one, until either we find
  35114. // a prefix that fits, or we run out of components to remove.
  35115. var level = 0;
  35116. while (aPath.indexOf(aRoot + '/') !== 0) {
  35117. var index = aRoot.lastIndexOf("/");
  35118. if (index < 0) {
  35119. return aPath;
  35120. }
  35121. // If the only part of the root that is left is the scheme (i.e. http://,
  35122. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  35123. // have exhausted all components, so the path is not relative to the root.
  35124. aRoot = aRoot.slice(0, index);
  35125. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  35126. return aPath;
  35127. }
  35128. ++level;
  35129. }
  35130. // Make sure we add a "../" for each component we removed from the root.
  35131. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  35132. }
  35133. exports.relative = relative;
  35134. var supportsNullProto = (function () {
  35135. var obj = Object.create(null);
  35136. return !('__proto__' in obj);
  35137. }());
  35138. function identity (s) {
  35139. return s;
  35140. }
  35141. /**
  35142. * Because behavior goes wacky when you set `__proto__` on objects, we
  35143. * have to prefix all the strings in our set with an arbitrary character.
  35144. *
  35145. * See https://github.com/mozilla/source-map/pull/31 and
  35146. * https://github.com/mozilla/source-map/issues/30
  35147. *
  35148. * @param String aStr
  35149. */
  35150. function toSetString(aStr) {
  35151. if (isProtoString(aStr)) {
  35152. return '$' + aStr;
  35153. }
  35154. return aStr;
  35155. }
  35156. exports.toSetString = supportsNullProto ? identity : toSetString;
  35157. function fromSetString(aStr) {
  35158. if (isProtoString(aStr)) {
  35159. return aStr.slice(1);
  35160. }
  35161. return aStr;
  35162. }
  35163. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  35164. function isProtoString(s) {
  35165. if (!s) {
  35166. return false;
  35167. }
  35168. var length = s.length;
  35169. if (length < 9 /* "__proto__".length */) {
  35170. return false;
  35171. }
  35172. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  35173. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  35174. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  35175. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  35176. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  35177. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  35178. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  35179. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  35180. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  35181. return false;
  35182. }
  35183. for (var i = length - 10; i >= 0; i--) {
  35184. if (s.charCodeAt(i) !== 36 /* '$' */) {
  35185. return false;
  35186. }
  35187. }
  35188. return true;
  35189. }
  35190. /**
  35191. * Comparator between two mappings where the original positions are compared.
  35192. *
  35193. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  35194. * mappings with the same original source/line/column, but different generated
  35195. * line and column the same. Useful when searching for a mapping with a
  35196. * stubbed out mapping.
  35197. */
  35198. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  35199. var cmp = strcmp(mappingA.source, mappingB.source);
  35200. if (cmp !== 0) {
  35201. return cmp;
  35202. }
  35203. cmp = mappingA.originalLine - mappingB.originalLine;
  35204. if (cmp !== 0) {
  35205. return cmp;
  35206. }
  35207. cmp = mappingA.originalColumn - mappingB.originalColumn;
  35208. if (cmp !== 0 || onlyCompareOriginal) {
  35209. return cmp;
  35210. }
  35211. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  35212. if (cmp !== 0) {
  35213. return cmp;
  35214. }
  35215. cmp = mappingA.generatedLine - mappingB.generatedLine;
  35216. if (cmp !== 0) {
  35217. return cmp;
  35218. }
  35219. return strcmp(mappingA.name, mappingB.name);
  35220. }
  35221. exports.compareByOriginalPositions = compareByOriginalPositions;
  35222. function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) {
  35223. var cmp;
  35224. cmp = mappingA.originalLine - mappingB.originalLine;
  35225. if (cmp !== 0) {
  35226. return cmp;
  35227. }
  35228. cmp = mappingA.originalColumn - mappingB.originalColumn;
  35229. if (cmp !== 0 || onlyCompareOriginal) {
  35230. return cmp;
  35231. }
  35232. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  35233. if (cmp !== 0) {
  35234. return cmp;
  35235. }
  35236. cmp = mappingA.generatedLine - mappingB.generatedLine;
  35237. if (cmp !== 0) {
  35238. return cmp;
  35239. }
  35240. return strcmp(mappingA.name, mappingB.name);
  35241. }
  35242. exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource;
  35243. /**
  35244. * Comparator between two mappings with deflated source and name indices where
  35245. * the generated positions are compared.
  35246. *
  35247. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  35248. * mappings with the same generated line and column, but different
  35249. * source/name/original line and column the same. Useful when searching for a
  35250. * mapping with a stubbed out mapping.
  35251. */
  35252. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  35253. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  35254. if (cmp !== 0) {
  35255. return cmp;
  35256. }
  35257. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  35258. if (cmp !== 0 || onlyCompareGenerated) {
  35259. return cmp;
  35260. }
  35261. cmp = strcmp(mappingA.source, mappingB.source);
  35262. if (cmp !== 0) {
  35263. return cmp;
  35264. }
  35265. cmp = mappingA.originalLine - mappingB.originalLine;
  35266. if (cmp !== 0) {
  35267. return cmp;
  35268. }
  35269. cmp = mappingA.originalColumn - mappingB.originalColumn;
  35270. if (cmp !== 0) {
  35271. return cmp;
  35272. }
  35273. return strcmp(mappingA.name, mappingB.name);
  35274. }
  35275. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  35276. function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) {
  35277. var cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  35278. if (cmp !== 0 || onlyCompareGenerated) {
  35279. return cmp;
  35280. }
  35281. cmp = strcmp(mappingA.source, mappingB.source);
  35282. if (cmp !== 0) {
  35283. return cmp;
  35284. }
  35285. cmp = mappingA.originalLine - mappingB.originalLine;
  35286. if (cmp !== 0) {
  35287. return cmp;
  35288. }
  35289. cmp = mappingA.originalColumn - mappingB.originalColumn;
  35290. if (cmp !== 0) {
  35291. return cmp;
  35292. }
  35293. return strcmp(mappingA.name, mappingB.name);
  35294. }
  35295. exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine;
  35296. function strcmp(aStr1, aStr2) {
  35297. if (aStr1 === aStr2) {
  35298. return 0;
  35299. }
  35300. if (aStr1 === null) {
  35301. return 1; // aStr2 !== null
  35302. }
  35303. if (aStr2 === null) {
  35304. return -1; // aStr1 !== null
  35305. }
  35306. if (aStr1 > aStr2) {
  35307. return 1;
  35308. }
  35309. return -1;
  35310. }
  35311. /**
  35312. * Comparator between two mappings with inflated source and name strings where
  35313. * the generated positions are compared.
  35314. */
  35315. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  35316. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  35317. if (cmp !== 0) {
  35318. return cmp;
  35319. }
  35320. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  35321. if (cmp !== 0) {
  35322. return cmp;
  35323. }
  35324. cmp = strcmp(mappingA.source, mappingB.source);
  35325. if (cmp !== 0) {
  35326. return cmp;
  35327. }
  35328. cmp = mappingA.originalLine - mappingB.originalLine;
  35329. if (cmp !== 0) {
  35330. return cmp;
  35331. }
  35332. cmp = mappingA.originalColumn - mappingB.originalColumn;
  35333. if (cmp !== 0) {
  35334. return cmp;
  35335. }
  35336. return strcmp(mappingA.name, mappingB.name);
  35337. }
  35338. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  35339. /**
  35340. * Strip any JSON XSSI avoidance prefix from the string (as documented
  35341. * in the source maps specification), and then parse the string as
  35342. * JSON.
  35343. */
  35344. function parseSourceMapInput(str) {
  35345. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  35346. }
  35347. exports.parseSourceMapInput = parseSourceMapInput;
  35348. /**
  35349. * Compute the URL of a source given the the source root, the source's
  35350. * URL, and the source map's URL.
  35351. */
  35352. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  35353. sourceURL = sourceURL || '';
  35354. if (sourceRoot) {
  35355. // This follows what Chrome does.
  35356. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  35357. sourceRoot += '/';
  35358. }
  35359. // The spec says:
  35360. // Line 4: An optional source root, useful for relocating source
  35361. // files on a server or removing repeated values in the
  35362. // “sources” entry. This value is prepended to the individual
  35363. // entries in the “source” field.
  35364. sourceURL = sourceRoot + sourceURL;
  35365. }
  35366. // Historically, SourceMapConsumer did not take the sourceMapURL as
  35367. // a parameter. This mode is still somewhat supported, which is why
  35368. // this code block is conditional. However, it's preferable to pass
  35369. // the source map URL to SourceMapConsumer, so that this function
  35370. // can implement the source URL resolution algorithm as outlined in
  35371. // the spec. This block is basically the equivalent of:
  35372. // new URL(sourceURL, sourceMapURL).toString()
  35373. // ... except it avoids using URL, which wasn't available in the
  35374. // older releases of node still supported by this library.
  35375. //
  35376. // The spec says:
  35377. // If the sources are not absolute URLs after prepending of the
  35378. // “sourceRoot”, the sources are resolved relative to the
  35379. // SourceMap (like resolving script src in a html document).
  35380. if (sourceMapURL) {
  35381. var parsed = urlParse(sourceMapURL);
  35382. if (!parsed) {
  35383. throw new Error("sourceMapURL could not be parsed");
  35384. }
  35385. if (parsed.path) {
  35386. // Strip the last path component, but keep the "/".
  35387. var index = parsed.path.lastIndexOf('/');
  35388. if (index >= 0) {
  35389. parsed.path = parsed.path.substring(0, index + 1);
  35390. }
  35391. }
  35392. sourceURL = join(urlGenerate(parsed), sourceURL);
  35393. }
  35394. return normalize(sourceURL);
  35395. }
  35396. exports.computeSourceURL = computeSourceURL;
  35397. } (util$6));
  35398. var arraySet = {};
  35399. /* -*- Mode: js; js-indent-level: 2; -*- */
  35400. /*
  35401. * Copyright 2011 Mozilla Foundation and contributors
  35402. * Licensed under the New BSD license. See LICENSE or:
  35403. * http://opensource.org/licenses/BSD-3-Clause
  35404. */
  35405. var util$5 = util$6;
  35406. var has = Object.prototype.hasOwnProperty;
  35407. var hasNativeMap = typeof Map !== "undefined";
  35408. /**
  35409. * A data structure which is a combination of an array and a set. Adding a new
  35410. * member is O(1), testing for membership is O(1), and finding the index of an
  35411. * element is O(1). Removing elements from the set is not supported. Only
  35412. * strings are supported for membership.
  35413. */
  35414. function ArraySet$2() {
  35415. this._array = [];
  35416. this._set = hasNativeMap ? new Map() : Object.create(null);
  35417. }
  35418. /**
  35419. * Static method for creating ArraySet instances from an existing array.
  35420. */
  35421. ArraySet$2.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  35422. var set = new ArraySet$2();
  35423. for (var i = 0, len = aArray.length; i < len; i++) {
  35424. set.add(aArray[i], aAllowDuplicates);
  35425. }
  35426. return set;
  35427. };
  35428. /**
  35429. * Return how many unique items are in this ArraySet. If duplicates have been
  35430. * added, than those do not count towards the size.
  35431. *
  35432. * @returns Number
  35433. */
  35434. ArraySet$2.prototype.size = function ArraySet_size() {
  35435. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  35436. };
  35437. /**
  35438. * Add the given string to this set.
  35439. *
  35440. * @param String aStr
  35441. */
  35442. ArraySet$2.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  35443. var sStr = hasNativeMap ? aStr : util$5.toSetString(aStr);
  35444. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  35445. var idx = this._array.length;
  35446. if (!isDuplicate || aAllowDuplicates) {
  35447. this._array.push(aStr);
  35448. }
  35449. if (!isDuplicate) {
  35450. if (hasNativeMap) {
  35451. this._set.set(aStr, idx);
  35452. } else {
  35453. this._set[sStr] = idx;
  35454. }
  35455. }
  35456. };
  35457. /**
  35458. * Is the given string a member of this set?
  35459. *
  35460. * @param String aStr
  35461. */
  35462. ArraySet$2.prototype.has = function ArraySet_has(aStr) {
  35463. if (hasNativeMap) {
  35464. return this._set.has(aStr);
  35465. } else {
  35466. var sStr = util$5.toSetString(aStr);
  35467. return has.call(this._set, sStr);
  35468. }
  35469. };
  35470. /**
  35471. * What is the index of the given string in the array?
  35472. *
  35473. * @param String aStr
  35474. */
  35475. ArraySet$2.prototype.indexOf = function ArraySet_indexOf(aStr) {
  35476. if (hasNativeMap) {
  35477. var idx = this._set.get(aStr);
  35478. if (idx >= 0) {
  35479. return idx;
  35480. }
  35481. } else {
  35482. var sStr = util$5.toSetString(aStr);
  35483. if (has.call(this._set, sStr)) {
  35484. return this._set[sStr];
  35485. }
  35486. }
  35487. throw new Error('"' + aStr + '" is not in the set.');
  35488. };
  35489. /**
  35490. * What is the element at the given index?
  35491. *
  35492. * @param Number aIdx
  35493. */
  35494. ArraySet$2.prototype.at = function ArraySet_at(aIdx) {
  35495. if (aIdx >= 0 && aIdx < this._array.length) {
  35496. return this._array[aIdx];
  35497. }
  35498. throw new Error('No element indexed by ' + aIdx);
  35499. };
  35500. /**
  35501. * Returns the array representation of this set (which has the proper indices
  35502. * indicated by indexOf). Note that this is a copy of the internal array used
  35503. * for storing the members so that no one can mess with internal state.
  35504. */
  35505. ArraySet$2.prototype.toArray = function ArraySet_toArray() {
  35506. return this._array.slice();
  35507. };
  35508. arraySet.ArraySet = ArraySet$2;
  35509. var mappingList = {};
  35510. /* -*- Mode: js; js-indent-level: 2; -*- */
  35511. /*
  35512. * Copyright 2014 Mozilla Foundation and contributors
  35513. * Licensed under the New BSD license. See LICENSE or:
  35514. * http://opensource.org/licenses/BSD-3-Clause
  35515. */
  35516. var util$4 = util$6;
  35517. /**
  35518. * Determine whether mappingB is after mappingA with respect to generated
  35519. * position.
  35520. */
  35521. function generatedPositionAfter(mappingA, mappingB) {
  35522. // Optimized for most common case
  35523. var lineA = mappingA.generatedLine;
  35524. var lineB = mappingB.generatedLine;
  35525. var columnA = mappingA.generatedColumn;
  35526. var columnB = mappingB.generatedColumn;
  35527. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  35528. util$4.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  35529. }
  35530. /**
  35531. * A data structure to provide a sorted view of accumulated mappings in a
  35532. * performance conscious manner. It trades a neglibable overhead in general
  35533. * case for a large speedup in case of mappings being added in order.
  35534. */
  35535. function MappingList$1() {
  35536. this._array = [];
  35537. this._sorted = true;
  35538. // Serves as infimum
  35539. this._last = {generatedLine: -1, generatedColumn: 0};
  35540. }
  35541. /**
  35542. * Iterate through internal items. This method takes the same arguments that
  35543. * `Array.prototype.forEach` takes.
  35544. *
  35545. * NOTE: The order of the mappings is NOT guaranteed.
  35546. */
  35547. MappingList$1.prototype.unsortedForEach =
  35548. function MappingList_forEach(aCallback, aThisArg) {
  35549. this._array.forEach(aCallback, aThisArg);
  35550. };
  35551. /**
  35552. * Add the given source mapping.
  35553. *
  35554. * @param Object aMapping
  35555. */
  35556. MappingList$1.prototype.add = function MappingList_add(aMapping) {
  35557. if (generatedPositionAfter(this._last, aMapping)) {
  35558. this._last = aMapping;
  35559. this._array.push(aMapping);
  35560. } else {
  35561. this._sorted = false;
  35562. this._array.push(aMapping);
  35563. }
  35564. };
  35565. /**
  35566. * Returns the flat, sorted array of mappings. The mappings are sorted by
  35567. * generated position.
  35568. *
  35569. * WARNING: This method returns internal data without copying, for
  35570. * performance. The return value must NOT be mutated, and should be treated as
  35571. * an immutable borrow. If you want to take ownership, you must make your own
  35572. * copy.
  35573. */
  35574. MappingList$1.prototype.toArray = function MappingList_toArray() {
  35575. if (!this._sorted) {
  35576. this._array.sort(util$4.compareByGeneratedPositionsInflated);
  35577. this._sorted = true;
  35578. }
  35579. return this._array;
  35580. };
  35581. mappingList.MappingList = MappingList$1;
  35582. /* -*- Mode: js; js-indent-level: 2; -*- */
  35583. /*
  35584. * Copyright 2011 Mozilla Foundation and contributors
  35585. * Licensed under the New BSD license. See LICENSE or:
  35586. * http://opensource.org/licenses/BSD-3-Clause
  35587. */
  35588. var base64VLQ$1 = base64Vlq;
  35589. var util$3 = util$6;
  35590. var ArraySet$1 = arraySet.ArraySet;
  35591. var MappingList = mappingList.MappingList;
  35592. /**
  35593. * An instance of the SourceMapGenerator represents a source map which is
  35594. * being built incrementally. You may pass an object with the following
  35595. * properties:
  35596. *
  35597. * - file: The filename of the generated source.
  35598. * - sourceRoot: A root for all relative URLs in this source map.
  35599. */
  35600. function SourceMapGenerator$5(aArgs) {
  35601. if (!aArgs) {
  35602. aArgs = {};
  35603. }
  35604. this._file = util$3.getArg(aArgs, 'file', null);
  35605. this._sourceRoot = util$3.getArg(aArgs, 'sourceRoot', null);
  35606. this._skipValidation = util$3.getArg(aArgs, 'skipValidation', false);
  35607. this._sources = new ArraySet$1();
  35608. this._names = new ArraySet$1();
  35609. this._mappings = new MappingList();
  35610. this._sourcesContents = null;
  35611. }
  35612. SourceMapGenerator$5.prototype._version = 3;
  35613. /**
  35614. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  35615. *
  35616. * @param aSourceMapConsumer The SourceMap.
  35617. */
  35618. SourceMapGenerator$5.fromSourceMap =
  35619. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  35620. var sourceRoot = aSourceMapConsumer.sourceRoot;
  35621. var generator = new SourceMapGenerator$5({
  35622. file: aSourceMapConsumer.file,
  35623. sourceRoot: sourceRoot
  35624. });
  35625. aSourceMapConsumer.eachMapping(function (mapping) {
  35626. var newMapping = {
  35627. generated: {
  35628. line: mapping.generatedLine,
  35629. column: mapping.generatedColumn
  35630. }
  35631. };
  35632. if (mapping.source != null) {
  35633. newMapping.source = mapping.source;
  35634. if (sourceRoot != null) {
  35635. newMapping.source = util$3.relative(sourceRoot, newMapping.source);
  35636. }
  35637. newMapping.original = {
  35638. line: mapping.originalLine,
  35639. column: mapping.originalColumn
  35640. };
  35641. if (mapping.name != null) {
  35642. newMapping.name = mapping.name;
  35643. }
  35644. }
  35645. generator.addMapping(newMapping);
  35646. });
  35647. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  35648. var sourceRelative = sourceFile;
  35649. if (sourceRoot !== null) {
  35650. sourceRelative = util$3.relative(sourceRoot, sourceFile);
  35651. }
  35652. if (!generator._sources.has(sourceRelative)) {
  35653. generator._sources.add(sourceRelative);
  35654. }
  35655. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  35656. if (content != null) {
  35657. generator.setSourceContent(sourceFile, content);
  35658. }
  35659. });
  35660. return generator;
  35661. };
  35662. /**
  35663. * Add a single mapping from original source line and column to the generated
  35664. * source's line and column for this source map being created. The mapping
  35665. * object should have the following properties:
  35666. *
  35667. * - generated: An object with the generated line and column positions.
  35668. * - original: An object with the original line and column positions.
  35669. * - source: The original source file (relative to the sourceRoot).
  35670. * - name: An optional original token name for this mapping.
  35671. */
  35672. SourceMapGenerator$5.prototype.addMapping =
  35673. function SourceMapGenerator_addMapping(aArgs) {
  35674. var generated = util$3.getArg(aArgs, 'generated');
  35675. var original = util$3.getArg(aArgs, 'original', null);
  35676. var source = util$3.getArg(aArgs, 'source', null);
  35677. var name = util$3.getArg(aArgs, 'name', null);
  35678. if (!this._skipValidation) {
  35679. this._validateMapping(generated, original, source, name);
  35680. }
  35681. if (source != null) {
  35682. source = String(source);
  35683. if (!this._sources.has(source)) {
  35684. this._sources.add(source);
  35685. }
  35686. }
  35687. if (name != null) {
  35688. name = String(name);
  35689. if (!this._names.has(name)) {
  35690. this._names.add(name);
  35691. }
  35692. }
  35693. this._mappings.add({
  35694. generatedLine: generated.line,
  35695. generatedColumn: generated.column,
  35696. originalLine: original != null && original.line,
  35697. originalColumn: original != null && original.column,
  35698. source: source,
  35699. name: name
  35700. });
  35701. };
  35702. /**
  35703. * Set the source content for a source file.
  35704. */
  35705. SourceMapGenerator$5.prototype.setSourceContent =
  35706. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  35707. var source = aSourceFile;
  35708. if (this._sourceRoot != null) {
  35709. source = util$3.relative(this._sourceRoot, source);
  35710. }
  35711. if (aSourceContent != null) {
  35712. // Add the source content to the _sourcesContents map.
  35713. // Create a new _sourcesContents map if the property is null.
  35714. if (!this._sourcesContents) {
  35715. this._sourcesContents = Object.create(null);
  35716. }
  35717. this._sourcesContents[util$3.toSetString(source)] = aSourceContent;
  35718. } else if (this._sourcesContents) {
  35719. // Remove the source file from the _sourcesContents map.
  35720. // If the _sourcesContents map is empty, set the property to null.
  35721. delete this._sourcesContents[util$3.toSetString(source)];
  35722. if (Object.keys(this._sourcesContents).length === 0) {
  35723. this._sourcesContents = null;
  35724. }
  35725. }
  35726. };
  35727. /**
  35728. * Applies the mappings of a sub-source-map for a specific source file to the
  35729. * source map being generated. Each mapping to the supplied source file is
  35730. * rewritten using the supplied source map. Note: The resolution for the
  35731. * resulting mappings is the minimium of this map and the supplied map.
  35732. *
  35733. * @param aSourceMapConsumer The source map to be applied.
  35734. * @param aSourceFile Optional. The filename of the source file.
  35735. * If omitted, SourceMapConsumer's file property will be used.
  35736. * @param aSourceMapPath Optional. The dirname of the path to the source map
  35737. * to be applied. If relative, it is relative to the SourceMapConsumer.
  35738. * This parameter is needed when the two source maps aren't in the same
  35739. * directory, and the source map to be applied contains relative source
  35740. * paths. If so, those relative source paths need to be rewritten
  35741. * relative to the SourceMapGenerator.
  35742. */
  35743. SourceMapGenerator$5.prototype.applySourceMap =
  35744. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  35745. var sourceFile = aSourceFile;
  35746. // If aSourceFile is omitted, we will use the file property of the SourceMap
  35747. if (aSourceFile == null) {
  35748. if (aSourceMapConsumer.file == null) {
  35749. throw new Error(
  35750. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  35751. 'or the source map\'s "file" property. Both were omitted.'
  35752. );
  35753. }
  35754. sourceFile = aSourceMapConsumer.file;
  35755. }
  35756. var sourceRoot = this._sourceRoot;
  35757. // Make "sourceFile" relative if an absolute Url is passed.
  35758. if (sourceRoot != null) {
  35759. sourceFile = util$3.relative(sourceRoot, sourceFile);
  35760. }
  35761. // Applying the SourceMap can add and remove items from the sources and
  35762. // the names array.
  35763. var newSources = new ArraySet$1();
  35764. var newNames = new ArraySet$1();
  35765. // Find mappings for the "sourceFile"
  35766. this._mappings.unsortedForEach(function (mapping) {
  35767. if (mapping.source === sourceFile && mapping.originalLine != null) {
  35768. // Check if it can be mapped by the source map, then update the mapping.
  35769. var original = aSourceMapConsumer.originalPositionFor({
  35770. line: mapping.originalLine,
  35771. column: mapping.originalColumn
  35772. });
  35773. if (original.source != null) {
  35774. // Copy mapping
  35775. mapping.source = original.source;
  35776. if (aSourceMapPath != null) {
  35777. mapping.source = util$3.join(aSourceMapPath, mapping.source);
  35778. }
  35779. if (sourceRoot != null) {
  35780. mapping.source = util$3.relative(sourceRoot, mapping.source);
  35781. }
  35782. mapping.originalLine = original.line;
  35783. mapping.originalColumn = original.column;
  35784. if (original.name != null) {
  35785. mapping.name = original.name;
  35786. }
  35787. }
  35788. }
  35789. var source = mapping.source;
  35790. if (source != null && !newSources.has(source)) {
  35791. newSources.add(source);
  35792. }
  35793. var name = mapping.name;
  35794. if (name != null && !newNames.has(name)) {
  35795. newNames.add(name);
  35796. }
  35797. }, this);
  35798. this._sources = newSources;
  35799. this._names = newNames;
  35800. // Copy sourcesContents of applied map.
  35801. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  35802. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  35803. if (content != null) {
  35804. if (aSourceMapPath != null) {
  35805. sourceFile = util$3.join(aSourceMapPath, sourceFile);
  35806. }
  35807. if (sourceRoot != null) {
  35808. sourceFile = util$3.relative(sourceRoot, sourceFile);
  35809. }
  35810. this.setSourceContent(sourceFile, content);
  35811. }
  35812. }, this);
  35813. };
  35814. /**
  35815. * A mapping can have one of the three levels of data:
  35816. *
  35817. * 1. Just the generated position.
  35818. * 2. The Generated position, original position, and original source.
  35819. * 3. Generated and original position, original source, as well as a name
  35820. * token.
  35821. *
  35822. * To maintain consistency, we validate that any new mapping being added falls
  35823. * in to one of these categories.
  35824. */
  35825. SourceMapGenerator$5.prototype._validateMapping =
  35826. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  35827. aName) {
  35828. // When aOriginal is truthy but has empty values for .line and .column,
  35829. // it is most likely a programmer error. In this case we throw a very
  35830. // specific error message to try to guide them the right way.
  35831. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  35832. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  35833. throw new Error(
  35834. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  35835. 'the original mapping entirely and only map the generated position. If so, pass ' +
  35836. 'null for the original mapping instead of an object with empty or null values.'
  35837. );
  35838. }
  35839. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  35840. && aGenerated.line > 0 && aGenerated.column >= 0
  35841. && !aOriginal && !aSource && !aName) {
  35842. // Case 1.
  35843. return;
  35844. }
  35845. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  35846. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  35847. && aGenerated.line > 0 && aGenerated.column >= 0
  35848. && aOriginal.line > 0 && aOriginal.column >= 0
  35849. && aSource) {
  35850. // Cases 2 and 3.
  35851. return;
  35852. }
  35853. else {
  35854. throw new Error('Invalid mapping: ' + JSON.stringify({
  35855. generated: aGenerated,
  35856. source: aSource,
  35857. original: aOriginal,
  35858. name: aName
  35859. }));
  35860. }
  35861. };
  35862. /**
  35863. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  35864. * specified by the source map format.
  35865. */
  35866. SourceMapGenerator$5.prototype._serializeMappings =
  35867. function SourceMapGenerator_serializeMappings() {
  35868. var previousGeneratedColumn = 0;
  35869. var previousGeneratedLine = 1;
  35870. var previousOriginalColumn = 0;
  35871. var previousOriginalLine = 0;
  35872. var previousName = 0;
  35873. var previousSource = 0;
  35874. var result = '';
  35875. var next;
  35876. var mapping;
  35877. var nameIdx;
  35878. var sourceIdx;
  35879. var mappings = this._mappings.toArray();
  35880. for (var i = 0, len = mappings.length; i < len; i++) {
  35881. mapping = mappings[i];
  35882. next = '';
  35883. if (mapping.generatedLine !== previousGeneratedLine) {
  35884. previousGeneratedColumn = 0;
  35885. while (mapping.generatedLine !== previousGeneratedLine) {
  35886. next += ';';
  35887. previousGeneratedLine++;
  35888. }
  35889. }
  35890. else {
  35891. if (i > 0) {
  35892. if (!util$3.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  35893. continue;
  35894. }
  35895. next += ',';
  35896. }
  35897. }
  35898. next += base64VLQ$1.encode(mapping.generatedColumn
  35899. - previousGeneratedColumn);
  35900. previousGeneratedColumn = mapping.generatedColumn;
  35901. if (mapping.source != null) {
  35902. sourceIdx = this._sources.indexOf(mapping.source);
  35903. next += base64VLQ$1.encode(sourceIdx - previousSource);
  35904. previousSource = sourceIdx;
  35905. // lines are stored 0-based in SourceMap spec version 3
  35906. next += base64VLQ$1.encode(mapping.originalLine - 1
  35907. - previousOriginalLine);
  35908. previousOriginalLine = mapping.originalLine - 1;
  35909. next += base64VLQ$1.encode(mapping.originalColumn
  35910. - previousOriginalColumn);
  35911. previousOriginalColumn = mapping.originalColumn;
  35912. if (mapping.name != null) {
  35913. nameIdx = this._names.indexOf(mapping.name);
  35914. next += base64VLQ$1.encode(nameIdx - previousName);
  35915. previousName = nameIdx;
  35916. }
  35917. }
  35918. result += next;
  35919. }
  35920. return result;
  35921. };
  35922. SourceMapGenerator$5.prototype._generateSourcesContent =
  35923. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  35924. return aSources.map(function (source) {
  35925. if (!this._sourcesContents) {
  35926. return null;
  35927. }
  35928. if (aSourceRoot != null) {
  35929. source = util$3.relative(aSourceRoot, source);
  35930. }
  35931. var key = util$3.toSetString(source);
  35932. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  35933. ? this._sourcesContents[key]
  35934. : null;
  35935. }, this);
  35936. };
  35937. /**
  35938. * Externalize the source map.
  35939. */
  35940. SourceMapGenerator$5.prototype.toJSON =
  35941. function SourceMapGenerator_toJSON() {
  35942. var map = {
  35943. version: this._version,
  35944. sources: this._sources.toArray(),
  35945. names: this._names.toArray(),
  35946. mappings: this._serializeMappings()
  35947. };
  35948. if (this._file != null) {
  35949. map.file = this._file;
  35950. }
  35951. if (this._sourceRoot != null) {
  35952. map.sourceRoot = this._sourceRoot;
  35953. }
  35954. if (this._sourcesContents) {
  35955. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  35956. }
  35957. return map;
  35958. };
  35959. /**
  35960. * Render the source map being generated to a string.
  35961. */
  35962. SourceMapGenerator$5.prototype.toString =
  35963. function SourceMapGenerator_toString() {
  35964. return JSON.stringify(this.toJSON());
  35965. };
  35966. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator$5;
  35967. var sourceMapConsumer = {};
  35968. var binarySearch$1 = {};
  35969. /* -*- Mode: js; js-indent-level: 2; -*- */
  35970. (function (exports) {
  35971. /*
  35972. * Copyright 2011 Mozilla Foundation and contributors
  35973. * Licensed under the New BSD license. See LICENSE or:
  35974. * http://opensource.org/licenses/BSD-3-Clause
  35975. */
  35976. exports.GREATEST_LOWER_BOUND = 1;
  35977. exports.LEAST_UPPER_BOUND = 2;
  35978. /**
  35979. * Recursive implementation of binary search.
  35980. *
  35981. * @param aLow Indices here and lower do not contain the needle.
  35982. * @param aHigh Indices here and higher do not contain the needle.
  35983. * @param aNeedle The element being searched for.
  35984. * @param aHaystack The non-empty array being searched.
  35985. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  35986. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  35987. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  35988. * closest element that is smaller than or greater than the one we are
  35989. * searching for, respectively, if the exact element cannot be found.
  35990. */
  35991. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  35992. // This function terminates when one of the following is true:
  35993. //
  35994. // 1. We find the exact element we are looking for.
  35995. //
  35996. // 2. We did not find the exact element, but we can return the index of
  35997. // the next-closest element.
  35998. //
  35999. // 3. We did not find the exact element, and there is no next-closest
  36000. // element than the one we are searching for, so we return -1.
  36001. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  36002. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  36003. if (cmp === 0) {
  36004. // Found the element we are looking for.
  36005. return mid;
  36006. }
  36007. else if (cmp > 0) {
  36008. // Our needle is greater than aHaystack[mid].
  36009. if (aHigh - mid > 1) {
  36010. // The element is in the upper half.
  36011. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  36012. }
  36013. // The exact needle element was not found in this haystack. Determine if
  36014. // we are in termination case (3) or (2) and return the appropriate thing.
  36015. if (aBias == exports.LEAST_UPPER_BOUND) {
  36016. return aHigh < aHaystack.length ? aHigh : -1;
  36017. } else {
  36018. return mid;
  36019. }
  36020. }
  36021. else {
  36022. // Our needle is less than aHaystack[mid].
  36023. if (mid - aLow > 1) {
  36024. // The element is in the lower half.
  36025. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  36026. }
  36027. // we are in termination case (3) or (2) and return the appropriate thing.
  36028. if (aBias == exports.LEAST_UPPER_BOUND) {
  36029. return mid;
  36030. } else {
  36031. return aLow < 0 ? -1 : aLow;
  36032. }
  36033. }
  36034. }
  36035. /**
  36036. * This is an implementation of binary search which will always try and return
  36037. * the index of the closest element if there is no exact hit. This is because
  36038. * mappings between original and generated line/col pairs are single points,
  36039. * and there is an implicit region between each of them, so a miss just means
  36040. * that you aren't on the very start of a region.
  36041. *
  36042. * @param aNeedle The element you are looking for.
  36043. * @param aHaystack The array that is being searched.
  36044. * @param aCompare A function which takes the needle and an element in the
  36045. * array and returns -1, 0, or 1 depending on whether the needle is less
  36046. * than, equal to, or greater than the element, respectively.
  36047. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  36048. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  36049. * closest element that is smaller than or greater than the one we are
  36050. * searching for, respectively, if the exact element cannot be found.
  36051. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  36052. */
  36053. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  36054. if (aHaystack.length === 0) {
  36055. return -1;
  36056. }
  36057. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  36058. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  36059. if (index < 0) {
  36060. return -1;
  36061. }
  36062. // We have found either the exact element, or the next-closest element than
  36063. // the one we are searching for. However, there may be more than one such
  36064. // element. Make sure we always return the smallest of these.
  36065. while (index - 1 >= 0) {
  36066. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  36067. break;
  36068. }
  36069. --index;
  36070. }
  36071. return index;
  36072. };
  36073. } (binarySearch$1));
  36074. var quickSort$1 = {};
  36075. /* -*- Mode: js; js-indent-level: 2; -*- */
  36076. /*
  36077. * Copyright 2011 Mozilla Foundation and contributors
  36078. * Licensed under the New BSD license. See LICENSE or:
  36079. * http://opensource.org/licenses/BSD-3-Clause
  36080. */
  36081. // It turns out that some (most?) JavaScript engines don't self-host
  36082. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  36083. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  36084. // custom comparator function, calling back and forth between the VM's C++ and
  36085. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  36086. // worse generated code for the comparator function than would be optimal. In
  36087. // fact, when sorting with a comparator, these costs outweigh the benefits of
  36088. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  36089. // a ~3500ms mean speed-up in `bench/bench.html`.
  36090. function SortTemplate(comparator) {
  36091. /**
  36092. * Swap the elements indexed by `x` and `y` in the array `ary`.
  36093. *
  36094. * @param {Array} ary
  36095. * The array.
  36096. * @param {Number} x
  36097. * The index of the first item.
  36098. * @param {Number} y
  36099. * The index of the second item.
  36100. */
  36101. function swap(ary, x, y) {
  36102. var temp = ary[x];
  36103. ary[x] = ary[y];
  36104. ary[y] = temp;
  36105. }
  36106. /**
  36107. * Returns a random integer within the range `low .. high` inclusive.
  36108. *
  36109. * @param {Number} low
  36110. * The lower bound on the range.
  36111. * @param {Number} high
  36112. * The upper bound on the range.
  36113. */
  36114. function randomIntInRange(low, high) {
  36115. return Math.round(low + (Math.random() * (high - low)));
  36116. }
  36117. /**
  36118. * The Quick Sort algorithm.
  36119. *
  36120. * @param {Array} ary
  36121. * An array to sort.
  36122. * @param {function} comparator
  36123. * Function to use to compare two items.
  36124. * @param {Number} p
  36125. * Start index of the array
  36126. * @param {Number} r
  36127. * End index of the array
  36128. */
  36129. function doQuickSort(ary, comparator, p, r) {
  36130. // If our lower bound is less than our upper bound, we (1) partition the
  36131. // array into two pieces and (2) recurse on each half. If it is not, this is
  36132. // the empty array and our base case.
  36133. if (p < r) {
  36134. // (1) Partitioning.
  36135. //
  36136. // The partitioning chooses a pivot between `p` and `r` and moves all
  36137. // elements that are less than or equal to the pivot to the before it, and
  36138. // all the elements that are greater than it after it. The effect is that
  36139. // once partition is done, the pivot is in the exact place it will be when
  36140. // the array is put in sorted order, and it will not need to be moved
  36141. // again. This runs in O(n) time.
  36142. // Always choose a random pivot so that an input array which is reverse
  36143. // sorted does not cause O(n^2) running time.
  36144. var pivotIndex = randomIntInRange(p, r);
  36145. var i = p - 1;
  36146. swap(ary, pivotIndex, r);
  36147. var pivot = ary[r];
  36148. // Immediately after `j` is incremented in this loop, the following hold
  36149. // true:
  36150. //
  36151. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  36152. //
  36153. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  36154. for (var j = p; j < r; j++) {
  36155. if (comparator(ary[j], pivot, false) <= 0) {
  36156. i += 1;
  36157. swap(ary, i, j);
  36158. }
  36159. }
  36160. swap(ary, i + 1, j);
  36161. var q = i + 1;
  36162. // (2) Recurse on each half.
  36163. doQuickSort(ary, comparator, p, q - 1);
  36164. doQuickSort(ary, comparator, q + 1, r);
  36165. }
  36166. }
  36167. return doQuickSort;
  36168. }
  36169. function cloneSort(comparator) {
  36170. let template = SortTemplate.toString();
  36171. let templateFn = new Function(`return ${template}`)();
  36172. return templateFn(comparator);
  36173. }
  36174. /**
  36175. * Sort the given array in-place with the given comparator function.
  36176. *
  36177. * @param {Array} ary
  36178. * An array to sort.
  36179. * @param {function} comparator
  36180. * Function to use to compare two items.
  36181. */
  36182. let sortCache = new WeakMap();
  36183. quickSort$1.quickSort = function (ary, comparator, start = 0) {
  36184. let doQuickSort = sortCache.get(comparator);
  36185. if (doQuickSort === void 0) {
  36186. doQuickSort = cloneSort(comparator);
  36187. sortCache.set(comparator, doQuickSort);
  36188. }
  36189. doQuickSort(ary, comparator, start, ary.length - 1);
  36190. };
  36191. /* -*- Mode: js; js-indent-level: 2; -*- */
  36192. /*
  36193. * Copyright 2011 Mozilla Foundation and contributors
  36194. * Licensed under the New BSD license. See LICENSE or:
  36195. * http://opensource.org/licenses/BSD-3-Clause
  36196. */
  36197. var util$2 = util$6;
  36198. var binarySearch = binarySearch$1;
  36199. var ArraySet = arraySet.ArraySet;
  36200. var base64VLQ = base64Vlq;
  36201. var quickSort = quickSort$1.quickSort;
  36202. function SourceMapConsumer$4(aSourceMap, aSourceMapURL) {
  36203. var sourceMap = aSourceMap;
  36204. if (typeof aSourceMap === 'string') {
  36205. sourceMap = util$2.parseSourceMapInput(aSourceMap);
  36206. }
  36207. return sourceMap.sections != null
  36208. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  36209. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  36210. }
  36211. SourceMapConsumer$4.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  36212. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  36213. };
  36214. /**
  36215. * The version of the source mapping spec that we are consuming.
  36216. */
  36217. SourceMapConsumer$4.prototype._version = 3;
  36218. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  36219. // parsed mapping coordinates from the source map's "mappings" attribute. They
  36220. // are lazily instantiated, accessed via the `_generatedMappings` and
  36221. // `_originalMappings` getters respectively, and we only parse the mappings
  36222. // and create these arrays once queried for a source location. We jump through
  36223. // these hoops because there can be many thousands of mappings, and parsing
  36224. // them is expensive, so we only want to do it if we must.
  36225. //
  36226. // Each object in the arrays is of the form:
  36227. //
  36228. // {
  36229. // generatedLine: The line number in the generated code,
  36230. // generatedColumn: The column number in the generated code,
  36231. // source: The path to the original source file that generated this
  36232. // chunk of code,
  36233. // originalLine: The line number in the original source that
  36234. // corresponds to this chunk of generated code,
  36235. // originalColumn: The column number in the original source that
  36236. // corresponds to this chunk of generated code,
  36237. // name: The name of the original symbol which generated this chunk of
  36238. // code.
  36239. // }
  36240. //
  36241. // All properties except for `generatedLine` and `generatedColumn` can be
  36242. // `null`.
  36243. //
  36244. // `_generatedMappings` is ordered by the generated positions.
  36245. //
  36246. // `_originalMappings` is ordered by the original positions.
  36247. SourceMapConsumer$4.prototype.__generatedMappings = null;
  36248. Object.defineProperty(SourceMapConsumer$4.prototype, '_generatedMappings', {
  36249. configurable: true,
  36250. enumerable: true,
  36251. get: function () {
  36252. if (!this.__generatedMappings) {
  36253. this._parseMappings(this._mappings, this.sourceRoot);
  36254. }
  36255. return this.__generatedMappings;
  36256. }
  36257. });
  36258. SourceMapConsumer$4.prototype.__originalMappings = null;
  36259. Object.defineProperty(SourceMapConsumer$4.prototype, '_originalMappings', {
  36260. configurable: true,
  36261. enumerable: true,
  36262. get: function () {
  36263. if (!this.__originalMappings) {
  36264. this._parseMappings(this._mappings, this.sourceRoot);
  36265. }
  36266. return this.__originalMappings;
  36267. }
  36268. });
  36269. SourceMapConsumer$4.prototype._charIsMappingSeparator =
  36270. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  36271. var c = aStr.charAt(index);
  36272. return c === ";" || c === ",";
  36273. };
  36274. /**
  36275. * Parse the mappings in a string in to a data structure which we can easily
  36276. * query (the ordered arrays in the `this.__generatedMappings` and
  36277. * `this.__originalMappings` properties).
  36278. */
  36279. SourceMapConsumer$4.prototype._parseMappings =
  36280. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  36281. throw new Error("Subclasses must implement _parseMappings");
  36282. };
  36283. SourceMapConsumer$4.GENERATED_ORDER = 1;
  36284. SourceMapConsumer$4.ORIGINAL_ORDER = 2;
  36285. SourceMapConsumer$4.GREATEST_LOWER_BOUND = 1;
  36286. SourceMapConsumer$4.LEAST_UPPER_BOUND = 2;
  36287. /**
  36288. * Iterate over each mapping between an original source/line/column and a
  36289. * generated line/column in this source map.
  36290. *
  36291. * @param Function aCallback
  36292. * The function that is called with each mapping.
  36293. * @param Object aContext
  36294. * Optional. If specified, this object will be the value of `this` every
  36295. * time that `aCallback` is called.
  36296. * @param aOrder
  36297. * Either `SourceMapConsumer.GENERATED_ORDER` or
  36298. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  36299. * iterate over the mappings sorted by the generated file's line/column
  36300. * order or the original's source/line/column order, respectively. Defaults to
  36301. * `SourceMapConsumer.GENERATED_ORDER`.
  36302. */
  36303. SourceMapConsumer$4.prototype.eachMapping =
  36304. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  36305. var context = aContext || null;
  36306. var order = aOrder || SourceMapConsumer$4.GENERATED_ORDER;
  36307. var mappings;
  36308. switch (order) {
  36309. case SourceMapConsumer$4.GENERATED_ORDER:
  36310. mappings = this._generatedMappings;
  36311. break;
  36312. case SourceMapConsumer$4.ORIGINAL_ORDER:
  36313. mappings = this._originalMappings;
  36314. break;
  36315. default:
  36316. throw new Error("Unknown order of iteration.");
  36317. }
  36318. var sourceRoot = this.sourceRoot;
  36319. var boundCallback = aCallback.bind(context);
  36320. var names = this._names;
  36321. var sources = this._sources;
  36322. var sourceMapURL = this._sourceMapURL;
  36323. for (var i = 0, n = mappings.length; i < n; i++) {
  36324. var mapping = mappings[i];
  36325. var source = mapping.source === null ? null : sources.at(mapping.source);
  36326. source = util$2.computeSourceURL(sourceRoot, source, sourceMapURL);
  36327. boundCallback({
  36328. source: source,
  36329. generatedLine: mapping.generatedLine,
  36330. generatedColumn: mapping.generatedColumn,
  36331. originalLine: mapping.originalLine,
  36332. originalColumn: mapping.originalColumn,
  36333. name: mapping.name === null ? null : names.at(mapping.name)
  36334. });
  36335. }
  36336. };
  36337. /**
  36338. * Returns all generated line and column information for the original source,
  36339. * line, and column provided. If no column is provided, returns all mappings
  36340. * corresponding to a either the line we are searching for or the next
  36341. * closest line that has any mappings. Otherwise, returns all mappings
  36342. * corresponding to the given line and either the column we are searching for
  36343. * or the next closest column that has any offsets.
  36344. *
  36345. * The only argument is an object with the following properties:
  36346. *
  36347. * - source: The filename of the original source.
  36348. * - line: The line number in the original source. The line number is 1-based.
  36349. * - column: Optional. the column number in the original source.
  36350. * The column number is 0-based.
  36351. *
  36352. * and an array of objects is returned, each with the following properties:
  36353. *
  36354. * - line: The line number in the generated source, or null. The
  36355. * line number is 1-based.
  36356. * - column: The column number in the generated source, or null.
  36357. * The column number is 0-based.
  36358. */
  36359. SourceMapConsumer$4.prototype.allGeneratedPositionsFor =
  36360. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  36361. var line = util$2.getArg(aArgs, 'line');
  36362. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  36363. // returns the index of the closest mapping less than the needle. By
  36364. // setting needle.originalColumn to 0, we thus find the last mapping for
  36365. // the given line, provided such a mapping exists.
  36366. var needle = {
  36367. source: util$2.getArg(aArgs, 'source'),
  36368. originalLine: line,
  36369. originalColumn: util$2.getArg(aArgs, 'column', 0)
  36370. };
  36371. needle.source = this._findSourceIndex(needle.source);
  36372. if (needle.source < 0) {
  36373. return [];
  36374. }
  36375. var mappings = [];
  36376. var index = this._findMapping(needle,
  36377. this._originalMappings,
  36378. "originalLine",
  36379. "originalColumn",
  36380. util$2.compareByOriginalPositions,
  36381. binarySearch.LEAST_UPPER_BOUND);
  36382. if (index >= 0) {
  36383. var mapping = this._originalMappings[index];
  36384. if (aArgs.column === undefined) {
  36385. var originalLine = mapping.originalLine;
  36386. // Iterate until either we run out of mappings, or we run into
  36387. // a mapping for a different line than the one we found. Since
  36388. // mappings are sorted, this is guaranteed to find all mappings for
  36389. // the line we found.
  36390. while (mapping && mapping.originalLine === originalLine) {
  36391. mappings.push({
  36392. line: util$2.getArg(mapping, 'generatedLine', null),
  36393. column: util$2.getArg(mapping, 'generatedColumn', null),
  36394. lastColumn: util$2.getArg(mapping, 'lastGeneratedColumn', null)
  36395. });
  36396. mapping = this._originalMappings[++index];
  36397. }
  36398. } else {
  36399. var originalColumn = mapping.originalColumn;
  36400. // Iterate until either we run out of mappings, or we run into
  36401. // a mapping for a different line than the one we were searching for.
  36402. // Since mappings are sorted, this is guaranteed to find all mappings for
  36403. // the line we are searching for.
  36404. while (mapping &&
  36405. mapping.originalLine === line &&
  36406. mapping.originalColumn == originalColumn) {
  36407. mappings.push({
  36408. line: util$2.getArg(mapping, 'generatedLine', null),
  36409. column: util$2.getArg(mapping, 'generatedColumn', null),
  36410. lastColumn: util$2.getArg(mapping, 'lastGeneratedColumn', null)
  36411. });
  36412. mapping = this._originalMappings[++index];
  36413. }
  36414. }
  36415. }
  36416. return mappings;
  36417. };
  36418. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer$4;
  36419. /**
  36420. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  36421. * query for information about the original file positions by giving it a file
  36422. * position in the generated source.
  36423. *
  36424. * The first parameter is the raw source map (either as a JSON string, or
  36425. * already parsed to an object). According to the spec, source maps have the
  36426. * following attributes:
  36427. *
  36428. * - version: Which version of the source map spec this map is following.
  36429. * - sources: An array of URLs to the original source files.
  36430. * - names: An array of identifiers which can be referrenced by individual mappings.
  36431. * - sourceRoot: Optional. The URL root from which all sources are relative.
  36432. * - sourcesContent: Optional. An array of contents of the original source files.
  36433. * - mappings: A string of base64 VLQs which contain the actual mappings.
  36434. * - file: Optional. The generated file this source map is associated with.
  36435. *
  36436. * Here is an example source map, taken from the source map spec[0]:
  36437. *
  36438. * {
  36439. * version : 3,
  36440. * file: "out.js",
  36441. * sourceRoot : "",
  36442. * sources: ["foo.js", "bar.js"],
  36443. * names: ["src", "maps", "are", "fun"],
  36444. * mappings: "AA,AB;;ABCDE;"
  36445. * }
  36446. *
  36447. * The second parameter, if given, is a string whose value is the URL
  36448. * at which the source map was found. This URL is used to compute the
  36449. * sources array.
  36450. *
  36451. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  36452. */
  36453. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  36454. var sourceMap = aSourceMap;
  36455. if (typeof aSourceMap === 'string') {
  36456. sourceMap = util$2.parseSourceMapInput(aSourceMap);
  36457. }
  36458. var version = util$2.getArg(sourceMap, 'version');
  36459. var sources = util$2.getArg(sourceMap, 'sources');
  36460. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  36461. // requires the array) to play nice here.
  36462. var names = util$2.getArg(sourceMap, 'names', []);
  36463. var sourceRoot = util$2.getArg(sourceMap, 'sourceRoot', null);
  36464. var sourcesContent = util$2.getArg(sourceMap, 'sourcesContent', null);
  36465. var mappings = util$2.getArg(sourceMap, 'mappings');
  36466. var file = util$2.getArg(sourceMap, 'file', null);
  36467. // Once again, Sass deviates from the spec and supplies the version as a
  36468. // string rather than a number, so we use loose equality checking here.
  36469. if (version != this._version) {
  36470. throw new Error('Unsupported version: ' + version);
  36471. }
  36472. if (sourceRoot) {
  36473. sourceRoot = util$2.normalize(sourceRoot);
  36474. }
  36475. sources = sources
  36476. .map(String)
  36477. // Some source maps produce relative source paths like "./foo.js" instead of
  36478. // "foo.js". Normalize these first so that future comparisons will succeed.
  36479. // See bugzil.la/1090768.
  36480. .map(util$2.normalize)
  36481. // Always ensure that absolute sources are internally stored relative to
  36482. // the source root, if the source root is absolute. Not doing this would
  36483. // be particularly problematic when the source root is a prefix of the
  36484. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  36485. .map(function (source) {
  36486. return sourceRoot && util$2.isAbsolute(sourceRoot) && util$2.isAbsolute(source)
  36487. ? util$2.relative(sourceRoot, source)
  36488. : source;
  36489. });
  36490. // Pass `true` below to allow duplicate names and sources. While source maps
  36491. // are intended to be compressed and deduplicated, the TypeScript compiler
  36492. // sometimes generates source maps with duplicates in them. See Github issue
  36493. // #72 and bugzil.la/889492.
  36494. this._names = ArraySet.fromArray(names.map(String), true);
  36495. this._sources = ArraySet.fromArray(sources, true);
  36496. this._absoluteSources = this._sources.toArray().map(function (s) {
  36497. return util$2.computeSourceURL(sourceRoot, s, aSourceMapURL);
  36498. });
  36499. this.sourceRoot = sourceRoot;
  36500. this.sourcesContent = sourcesContent;
  36501. this._mappings = mappings;
  36502. this._sourceMapURL = aSourceMapURL;
  36503. this.file = file;
  36504. }
  36505. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer$4.prototype);
  36506. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$4;
  36507. /**
  36508. * Utility function to find the index of a source. Returns -1 if not
  36509. * found.
  36510. */
  36511. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  36512. var relativeSource = aSource;
  36513. if (this.sourceRoot != null) {
  36514. relativeSource = util$2.relative(this.sourceRoot, relativeSource);
  36515. }
  36516. if (this._sources.has(relativeSource)) {
  36517. return this._sources.indexOf(relativeSource);
  36518. }
  36519. // Maybe aSource is an absolute URL as returned by |sources|. In
  36520. // this case we can't simply undo the transform.
  36521. var i;
  36522. for (i = 0; i < this._absoluteSources.length; ++i) {
  36523. if (this._absoluteSources[i] == aSource) {
  36524. return i;
  36525. }
  36526. }
  36527. return -1;
  36528. };
  36529. /**
  36530. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  36531. *
  36532. * @param SourceMapGenerator aSourceMap
  36533. * The source map that will be consumed.
  36534. * @param String aSourceMapURL
  36535. * The URL at which the source map can be found (optional)
  36536. * @returns BasicSourceMapConsumer
  36537. */
  36538. BasicSourceMapConsumer.fromSourceMap =
  36539. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  36540. var smc = Object.create(BasicSourceMapConsumer.prototype);
  36541. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  36542. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  36543. smc.sourceRoot = aSourceMap._sourceRoot;
  36544. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  36545. smc.sourceRoot);
  36546. smc.file = aSourceMap._file;
  36547. smc._sourceMapURL = aSourceMapURL;
  36548. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  36549. return util$2.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  36550. });
  36551. // Because we are modifying the entries (by converting string sources and
  36552. // names to indices into the sources and names ArraySets), we have to make
  36553. // a copy of the entry or else bad things happen. Shared mutable state
  36554. // strikes again! See github issue #191.
  36555. var generatedMappings = aSourceMap._mappings.toArray().slice();
  36556. var destGeneratedMappings = smc.__generatedMappings = [];
  36557. var destOriginalMappings = smc.__originalMappings = [];
  36558. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  36559. var srcMapping = generatedMappings[i];
  36560. var destMapping = new Mapping;
  36561. destMapping.generatedLine = srcMapping.generatedLine;
  36562. destMapping.generatedColumn = srcMapping.generatedColumn;
  36563. if (srcMapping.source) {
  36564. destMapping.source = sources.indexOf(srcMapping.source);
  36565. destMapping.originalLine = srcMapping.originalLine;
  36566. destMapping.originalColumn = srcMapping.originalColumn;
  36567. if (srcMapping.name) {
  36568. destMapping.name = names.indexOf(srcMapping.name);
  36569. }
  36570. destOriginalMappings.push(destMapping);
  36571. }
  36572. destGeneratedMappings.push(destMapping);
  36573. }
  36574. quickSort(smc.__originalMappings, util$2.compareByOriginalPositions);
  36575. return smc;
  36576. };
  36577. /**
  36578. * The version of the source mapping spec that we are consuming.
  36579. */
  36580. BasicSourceMapConsumer.prototype._version = 3;
  36581. /**
  36582. * The list of original sources.
  36583. */
  36584. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  36585. get: function () {
  36586. return this._absoluteSources.slice();
  36587. }
  36588. });
  36589. /**
  36590. * Provide the JIT with a nice shape / hidden class.
  36591. */
  36592. function Mapping() {
  36593. this.generatedLine = 0;
  36594. this.generatedColumn = 0;
  36595. this.source = null;
  36596. this.originalLine = null;
  36597. this.originalColumn = null;
  36598. this.name = null;
  36599. }
  36600. /**
  36601. * Parse the mappings in a string in to a data structure which we can easily
  36602. * query (the ordered arrays in the `this.__generatedMappings` and
  36603. * `this.__originalMappings` properties).
  36604. */
  36605. const compareGenerated = util$2.compareByGeneratedPositionsDeflatedNoLine;
  36606. function sortGenerated(array, start) {
  36607. let l = array.length;
  36608. let n = array.length - start;
  36609. if (n <= 1) {
  36610. return;
  36611. } else if (n == 2) {
  36612. let a = array[start];
  36613. let b = array[start + 1];
  36614. if (compareGenerated(a, b) > 0) {
  36615. array[start] = b;
  36616. array[start + 1] = a;
  36617. }
  36618. } else if (n < 20) {
  36619. for (let i = start; i < l; i++) {
  36620. for (let j = i; j > start; j--) {
  36621. let a = array[j - 1];
  36622. let b = array[j];
  36623. if (compareGenerated(a, b) <= 0) {
  36624. break;
  36625. }
  36626. array[j - 1] = b;
  36627. array[j] = a;
  36628. }
  36629. }
  36630. } else {
  36631. quickSort(array, compareGenerated, start);
  36632. }
  36633. }
  36634. BasicSourceMapConsumer.prototype._parseMappings =
  36635. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  36636. var generatedLine = 1;
  36637. var previousGeneratedColumn = 0;
  36638. var previousOriginalLine = 0;
  36639. var previousOriginalColumn = 0;
  36640. var previousSource = 0;
  36641. var previousName = 0;
  36642. var length = aStr.length;
  36643. var index = 0;
  36644. var temp = {};
  36645. var originalMappings = [];
  36646. var generatedMappings = [];
  36647. var mapping, segment, end, value;
  36648. let subarrayStart = 0;
  36649. while (index < length) {
  36650. if (aStr.charAt(index) === ';') {
  36651. generatedLine++;
  36652. index++;
  36653. previousGeneratedColumn = 0;
  36654. sortGenerated(generatedMappings, subarrayStart);
  36655. subarrayStart = generatedMappings.length;
  36656. }
  36657. else if (aStr.charAt(index) === ',') {
  36658. index++;
  36659. }
  36660. else {
  36661. mapping = new Mapping();
  36662. mapping.generatedLine = generatedLine;
  36663. for (end = index; end < length; end++) {
  36664. if (this._charIsMappingSeparator(aStr, end)) {
  36665. break;
  36666. }
  36667. }
  36668. aStr.slice(index, end);
  36669. segment = [];
  36670. while (index < end) {
  36671. base64VLQ.decode(aStr, index, temp);
  36672. value = temp.value;
  36673. index = temp.rest;
  36674. segment.push(value);
  36675. }
  36676. if (segment.length === 2) {
  36677. throw new Error('Found a source, but no line and column');
  36678. }
  36679. if (segment.length === 3) {
  36680. throw new Error('Found a source and line, but no column');
  36681. }
  36682. // Generated column.
  36683. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  36684. previousGeneratedColumn = mapping.generatedColumn;
  36685. if (segment.length > 1) {
  36686. // Original source.
  36687. mapping.source = previousSource + segment[1];
  36688. previousSource += segment[1];
  36689. // Original line.
  36690. mapping.originalLine = previousOriginalLine + segment[2];
  36691. previousOriginalLine = mapping.originalLine;
  36692. // Lines are stored 0-based
  36693. mapping.originalLine += 1;
  36694. // Original column.
  36695. mapping.originalColumn = previousOriginalColumn + segment[3];
  36696. previousOriginalColumn = mapping.originalColumn;
  36697. if (segment.length > 4) {
  36698. // Original name.
  36699. mapping.name = previousName + segment[4];
  36700. previousName += segment[4];
  36701. }
  36702. }
  36703. generatedMappings.push(mapping);
  36704. if (typeof mapping.originalLine === 'number') {
  36705. let currentSource = mapping.source;
  36706. while (originalMappings.length <= currentSource) {
  36707. originalMappings.push(null);
  36708. }
  36709. if (originalMappings[currentSource] === null) {
  36710. originalMappings[currentSource] = [];
  36711. }
  36712. originalMappings[currentSource].push(mapping);
  36713. }
  36714. }
  36715. }
  36716. sortGenerated(generatedMappings, subarrayStart);
  36717. this.__generatedMappings = generatedMappings;
  36718. for (var i = 0; i < originalMappings.length; i++) {
  36719. if (originalMappings[i] != null) {
  36720. quickSort(originalMappings[i], util$2.compareByOriginalPositionsNoSource);
  36721. }
  36722. }
  36723. this.__originalMappings = [].concat(...originalMappings);
  36724. };
  36725. /**
  36726. * Find the mapping that best matches the hypothetical "needle" mapping that
  36727. * we are searching for in the given "haystack" of mappings.
  36728. */
  36729. BasicSourceMapConsumer.prototype._findMapping =
  36730. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  36731. aColumnName, aComparator, aBias) {
  36732. // To return the position we are searching for, we must first find the
  36733. // mapping for the given position and then return the opposite position it
  36734. // points to. Because the mappings are sorted, we can use binary search to
  36735. // find the best mapping.
  36736. if (aNeedle[aLineName] <= 0) {
  36737. throw new TypeError('Line must be greater than or equal to 1, got '
  36738. + aNeedle[aLineName]);
  36739. }
  36740. if (aNeedle[aColumnName] < 0) {
  36741. throw new TypeError('Column must be greater than or equal to 0, got '
  36742. + aNeedle[aColumnName]);
  36743. }
  36744. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  36745. };
  36746. /**
  36747. * Compute the last column for each generated mapping. The last column is
  36748. * inclusive.
  36749. */
  36750. BasicSourceMapConsumer.prototype.computeColumnSpans =
  36751. function SourceMapConsumer_computeColumnSpans() {
  36752. for (var index = 0; index < this._generatedMappings.length; ++index) {
  36753. var mapping = this._generatedMappings[index];
  36754. // Mappings do not contain a field for the last generated columnt. We
  36755. // can come up with an optimistic estimate, however, by assuming that
  36756. // mappings are contiguous (i.e. given two consecutive mappings, the
  36757. // first mapping ends where the second one starts).
  36758. if (index + 1 < this._generatedMappings.length) {
  36759. var nextMapping = this._generatedMappings[index + 1];
  36760. if (mapping.generatedLine === nextMapping.generatedLine) {
  36761. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  36762. continue;
  36763. }
  36764. }
  36765. // The last mapping for each line spans the entire line.
  36766. mapping.lastGeneratedColumn = Infinity;
  36767. }
  36768. };
  36769. /**
  36770. * Returns the original source, line, and column information for the generated
  36771. * source's line and column positions provided. The only argument is an object
  36772. * with the following properties:
  36773. *
  36774. * - line: The line number in the generated source. The line number
  36775. * is 1-based.
  36776. * - column: The column number in the generated source. The column
  36777. * number is 0-based.
  36778. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  36779. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  36780. * closest element that is smaller than or greater than the one we are
  36781. * searching for, respectively, if the exact element cannot be found.
  36782. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  36783. *
  36784. * and an object is returned with the following properties:
  36785. *
  36786. * - source: The original source file, or null.
  36787. * - line: The line number in the original source, or null. The
  36788. * line number is 1-based.
  36789. * - column: The column number in the original source, or null. The
  36790. * column number is 0-based.
  36791. * - name: The original identifier, or null.
  36792. */
  36793. BasicSourceMapConsumer.prototype.originalPositionFor =
  36794. function SourceMapConsumer_originalPositionFor(aArgs) {
  36795. var needle = {
  36796. generatedLine: util$2.getArg(aArgs, 'line'),
  36797. generatedColumn: util$2.getArg(aArgs, 'column')
  36798. };
  36799. var index = this._findMapping(
  36800. needle,
  36801. this._generatedMappings,
  36802. "generatedLine",
  36803. "generatedColumn",
  36804. util$2.compareByGeneratedPositionsDeflated,
  36805. util$2.getArg(aArgs, 'bias', SourceMapConsumer$4.GREATEST_LOWER_BOUND)
  36806. );
  36807. if (index >= 0) {
  36808. var mapping = this._generatedMappings[index];
  36809. if (mapping.generatedLine === needle.generatedLine) {
  36810. var source = util$2.getArg(mapping, 'source', null);
  36811. if (source !== null) {
  36812. source = this._sources.at(source);
  36813. source = util$2.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  36814. }
  36815. var name = util$2.getArg(mapping, 'name', null);
  36816. if (name !== null) {
  36817. name = this._names.at(name);
  36818. }
  36819. return {
  36820. source: source,
  36821. line: util$2.getArg(mapping, 'originalLine', null),
  36822. column: util$2.getArg(mapping, 'originalColumn', null),
  36823. name: name
  36824. };
  36825. }
  36826. }
  36827. return {
  36828. source: null,
  36829. line: null,
  36830. column: null,
  36831. name: null
  36832. };
  36833. };
  36834. /**
  36835. * Return true if we have the source content for every source in the source
  36836. * map, false otherwise.
  36837. */
  36838. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  36839. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  36840. if (!this.sourcesContent) {
  36841. return false;
  36842. }
  36843. return this.sourcesContent.length >= this._sources.size() &&
  36844. !this.sourcesContent.some(function (sc) { return sc == null; });
  36845. };
  36846. /**
  36847. * Returns the original source content. The only argument is the url of the
  36848. * original source file. Returns null if no original source content is
  36849. * available.
  36850. */
  36851. BasicSourceMapConsumer.prototype.sourceContentFor =
  36852. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  36853. if (!this.sourcesContent) {
  36854. return null;
  36855. }
  36856. var index = this._findSourceIndex(aSource);
  36857. if (index >= 0) {
  36858. return this.sourcesContent[index];
  36859. }
  36860. var relativeSource = aSource;
  36861. if (this.sourceRoot != null) {
  36862. relativeSource = util$2.relative(this.sourceRoot, relativeSource);
  36863. }
  36864. var url;
  36865. if (this.sourceRoot != null
  36866. && (url = util$2.urlParse(this.sourceRoot))) {
  36867. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  36868. // many users. We can help them out when they expect file:// URIs to
  36869. // behave like it would if they were running a local HTTP server. See
  36870. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  36871. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  36872. if (url.scheme == "file"
  36873. && this._sources.has(fileUriAbsPath)) {
  36874. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  36875. }
  36876. if ((!url.path || url.path == "/")
  36877. && this._sources.has("/" + relativeSource)) {
  36878. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  36879. }
  36880. }
  36881. // This function is used recursively from
  36882. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  36883. // don't want to throw if we can't find the source - we just want to
  36884. // return null, so we provide a flag to exit gracefully.
  36885. if (nullOnMissing) {
  36886. return null;
  36887. }
  36888. else {
  36889. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  36890. }
  36891. };
  36892. /**
  36893. * Returns the generated line and column information for the original source,
  36894. * line, and column positions provided. The only argument is an object with
  36895. * the following properties:
  36896. *
  36897. * - source: The filename of the original source.
  36898. * - line: The line number in the original source. The line number
  36899. * is 1-based.
  36900. * - column: The column number in the original source. The column
  36901. * number is 0-based.
  36902. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  36903. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  36904. * closest element that is smaller than or greater than the one we are
  36905. * searching for, respectively, if the exact element cannot be found.
  36906. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  36907. *
  36908. * and an object is returned with the following properties:
  36909. *
  36910. * - line: The line number in the generated source, or null. The
  36911. * line number is 1-based.
  36912. * - column: The column number in the generated source, or null.
  36913. * The column number is 0-based.
  36914. */
  36915. BasicSourceMapConsumer.prototype.generatedPositionFor =
  36916. function SourceMapConsumer_generatedPositionFor(aArgs) {
  36917. var source = util$2.getArg(aArgs, 'source');
  36918. source = this._findSourceIndex(source);
  36919. if (source < 0) {
  36920. return {
  36921. line: null,
  36922. column: null,
  36923. lastColumn: null
  36924. };
  36925. }
  36926. var needle = {
  36927. source: source,
  36928. originalLine: util$2.getArg(aArgs, 'line'),
  36929. originalColumn: util$2.getArg(aArgs, 'column')
  36930. };
  36931. var index = this._findMapping(
  36932. needle,
  36933. this._originalMappings,
  36934. "originalLine",
  36935. "originalColumn",
  36936. util$2.compareByOriginalPositions,
  36937. util$2.getArg(aArgs, 'bias', SourceMapConsumer$4.GREATEST_LOWER_BOUND)
  36938. );
  36939. if (index >= 0) {
  36940. var mapping = this._originalMappings[index];
  36941. if (mapping.source === needle.source) {
  36942. return {
  36943. line: util$2.getArg(mapping, 'generatedLine', null),
  36944. column: util$2.getArg(mapping, 'generatedColumn', null),
  36945. lastColumn: util$2.getArg(mapping, 'lastGeneratedColumn', null)
  36946. };
  36947. }
  36948. }
  36949. return {
  36950. line: null,
  36951. column: null,
  36952. lastColumn: null
  36953. };
  36954. };
  36955. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  36956. /**
  36957. * An IndexedSourceMapConsumer instance represents a parsed source map which
  36958. * we can query for information. It differs from BasicSourceMapConsumer in
  36959. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  36960. * input.
  36961. *
  36962. * The first parameter is a raw source map (either as a JSON string, or already
  36963. * parsed to an object). According to the spec for indexed source maps, they
  36964. * have the following attributes:
  36965. *
  36966. * - version: Which version of the source map spec this map is following.
  36967. * - file: Optional. The generated file this source map is associated with.
  36968. * - sections: A list of section definitions.
  36969. *
  36970. * Each value under the "sections" field has two fields:
  36971. * - offset: The offset into the original specified at which this section
  36972. * begins to apply, defined as an object with a "line" and "column"
  36973. * field.
  36974. * - map: A source map definition. This source map could also be indexed,
  36975. * but doesn't have to be.
  36976. *
  36977. * Instead of the "map" field, it's also possible to have a "url" field
  36978. * specifying a URL to retrieve a source map from, but that's currently
  36979. * unsupported.
  36980. *
  36981. * Here's an example source map, taken from the source map spec[0], but
  36982. * modified to omit a section which uses the "url" field.
  36983. *
  36984. * {
  36985. * version : 3,
  36986. * file: "app.js",
  36987. * sections: [{
  36988. * offset: {line:100, column:10},
  36989. * map: {
  36990. * version : 3,
  36991. * file: "section.js",
  36992. * sources: ["foo.js", "bar.js"],
  36993. * names: ["src", "maps", "are", "fun"],
  36994. * mappings: "AAAA,E;;ABCDE;"
  36995. * }
  36996. * }],
  36997. * }
  36998. *
  36999. * The second parameter, if given, is a string whose value is the URL
  37000. * at which the source map was found. This URL is used to compute the
  37001. * sources array.
  37002. *
  37003. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  37004. */
  37005. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  37006. var sourceMap = aSourceMap;
  37007. if (typeof aSourceMap === 'string') {
  37008. sourceMap = util$2.parseSourceMapInput(aSourceMap);
  37009. }
  37010. var version = util$2.getArg(sourceMap, 'version');
  37011. var sections = util$2.getArg(sourceMap, 'sections');
  37012. if (version != this._version) {
  37013. throw new Error('Unsupported version: ' + version);
  37014. }
  37015. this._sources = new ArraySet();
  37016. this._names = new ArraySet();
  37017. var lastOffset = {
  37018. line: -1,
  37019. column: 0
  37020. };
  37021. this._sections = sections.map(function (s) {
  37022. if (s.url) {
  37023. // The url field will require support for asynchronicity.
  37024. // See https://github.com/mozilla/source-map/issues/16
  37025. throw new Error('Support for url field in sections not implemented.');
  37026. }
  37027. var offset = util$2.getArg(s, 'offset');
  37028. var offsetLine = util$2.getArg(offset, 'line');
  37029. var offsetColumn = util$2.getArg(offset, 'column');
  37030. if (offsetLine < lastOffset.line ||
  37031. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  37032. throw new Error('Section offsets must be ordered and non-overlapping.');
  37033. }
  37034. lastOffset = offset;
  37035. return {
  37036. generatedOffset: {
  37037. // The offset fields are 0-based, but we use 1-based indices when
  37038. // encoding/decoding from VLQ.
  37039. generatedLine: offsetLine + 1,
  37040. generatedColumn: offsetColumn + 1
  37041. },
  37042. consumer: new SourceMapConsumer$4(util$2.getArg(s, 'map'), aSourceMapURL)
  37043. }
  37044. });
  37045. }
  37046. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer$4.prototype);
  37047. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer$4;
  37048. /**
  37049. * The version of the source mapping spec that we are consuming.
  37050. */
  37051. IndexedSourceMapConsumer.prototype._version = 3;
  37052. /**
  37053. * The list of original sources.
  37054. */
  37055. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  37056. get: function () {
  37057. var sources = [];
  37058. for (var i = 0; i < this._sections.length; i++) {
  37059. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  37060. sources.push(this._sections[i].consumer.sources[j]);
  37061. }
  37062. }
  37063. return sources;
  37064. }
  37065. });
  37066. /**
  37067. * Returns the original source, line, and column information for the generated
  37068. * source's line and column positions provided. The only argument is an object
  37069. * with the following properties:
  37070. *
  37071. * - line: The line number in the generated source. The line number
  37072. * is 1-based.
  37073. * - column: The column number in the generated source. The column
  37074. * number is 0-based.
  37075. *
  37076. * and an object is returned with the following properties:
  37077. *
  37078. * - source: The original source file, or null.
  37079. * - line: The line number in the original source, or null. The
  37080. * line number is 1-based.
  37081. * - column: The column number in the original source, or null. The
  37082. * column number is 0-based.
  37083. * - name: The original identifier, or null.
  37084. */
  37085. IndexedSourceMapConsumer.prototype.originalPositionFor =
  37086. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  37087. var needle = {
  37088. generatedLine: util$2.getArg(aArgs, 'line'),
  37089. generatedColumn: util$2.getArg(aArgs, 'column')
  37090. };
  37091. // Find the section containing the generated position we're trying to map
  37092. // to an original position.
  37093. var sectionIndex = binarySearch.search(needle, this._sections,
  37094. function(needle, section) {
  37095. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  37096. if (cmp) {
  37097. return cmp;
  37098. }
  37099. return (needle.generatedColumn -
  37100. section.generatedOffset.generatedColumn);
  37101. });
  37102. var section = this._sections[sectionIndex];
  37103. if (!section) {
  37104. return {
  37105. source: null,
  37106. line: null,
  37107. column: null,
  37108. name: null
  37109. };
  37110. }
  37111. return section.consumer.originalPositionFor({
  37112. line: needle.generatedLine -
  37113. (section.generatedOffset.generatedLine - 1),
  37114. column: needle.generatedColumn -
  37115. (section.generatedOffset.generatedLine === needle.generatedLine
  37116. ? section.generatedOffset.generatedColumn - 1
  37117. : 0),
  37118. bias: aArgs.bias
  37119. });
  37120. };
  37121. /**
  37122. * Return true if we have the source content for every source in the source
  37123. * map, false otherwise.
  37124. */
  37125. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  37126. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  37127. return this._sections.every(function (s) {
  37128. return s.consumer.hasContentsOfAllSources();
  37129. });
  37130. };
  37131. /**
  37132. * Returns the original source content. The only argument is the url of the
  37133. * original source file. Returns null if no original source content is
  37134. * available.
  37135. */
  37136. IndexedSourceMapConsumer.prototype.sourceContentFor =
  37137. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  37138. for (var i = 0; i < this._sections.length; i++) {
  37139. var section = this._sections[i];
  37140. var content = section.consumer.sourceContentFor(aSource, true);
  37141. if (content) {
  37142. return content;
  37143. }
  37144. }
  37145. if (nullOnMissing) {
  37146. return null;
  37147. }
  37148. else {
  37149. throw new Error('"' + aSource + '" is not in the SourceMap.');
  37150. }
  37151. };
  37152. /**
  37153. * Returns the generated line and column information for the original source,
  37154. * line, and column positions provided. The only argument is an object with
  37155. * the following properties:
  37156. *
  37157. * - source: The filename of the original source.
  37158. * - line: The line number in the original source. The line number
  37159. * is 1-based.
  37160. * - column: The column number in the original source. The column
  37161. * number is 0-based.
  37162. *
  37163. * and an object is returned with the following properties:
  37164. *
  37165. * - line: The line number in the generated source, or null. The
  37166. * line number is 1-based.
  37167. * - column: The column number in the generated source, or null.
  37168. * The column number is 0-based.
  37169. */
  37170. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  37171. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  37172. for (var i = 0; i < this._sections.length; i++) {
  37173. var section = this._sections[i];
  37174. // Only consider this section if the requested source is in the list of
  37175. // sources of the consumer.
  37176. if (section.consumer._findSourceIndex(util$2.getArg(aArgs, 'source')) === -1) {
  37177. continue;
  37178. }
  37179. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  37180. if (generatedPosition) {
  37181. var ret = {
  37182. line: generatedPosition.line +
  37183. (section.generatedOffset.generatedLine - 1),
  37184. column: generatedPosition.column +
  37185. (section.generatedOffset.generatedLine === generatedPosition.line
  37186. ? section.generatedOffset.generatedColumn - 1
  37187. : 0)
  37188. };
  37189. return ret;
  37190. }
  37191. }
  37192. return {
  37193. line: null,
  37194. column: null
  37195. };
  37196. };
  37197. /**
  37198. * Parse the mappings in a string in to a data structure which we can easily
  37199. * query (the ordered arrays in the `this.__generatedMappings` and
  37200. * `this.__originalMappings` properties).
  37201. */
  37202. IndexedSourceMapConsumer.prototype._parseMappings =
  37203. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  37204. this.__generatedMappings = [];
  37205. this.__originalMappings = [];
  37206. for (var i = 0; i < this._sections.length; i++) {
  37207. var section = this._sections[i];
  37208. var sectionMappings = section.consumer._generatedMappings;
  37209. for (var j = 0; j < sectionMappings.length; j++) {
  37210. var mapping = sectionMappings[j];
  37211. var source = section.consumer._sources.at(mapping.source);
  37212. source = util$2.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  37213. this._sources.add(source);
  37214. source = this._sources.indexOf(source);
  37215. var name = null;
  37216. if (mapping.name) {
  37217. name = section.consumer._names.at(mapping.name);
  37218. this._names.add(name);
  37219. name = this._names.indexOf(name);
  37220. }
  37221. // The mappings coming from the consumer for the section have
  37222. // generated positions relative to the start of the section, so we
  37223. // need to offset them to be relative to the start of the concatenated
  37224. // generated file.
  37225. var adjustedMapping = {
  37226. source: source,
  37227. generatedLine: mapping.generatedLine +
  37228. (section.generatedOffset.generatedLine - 1),
  37229. generatedColumn: mapping.generatedColumn +
  37230. (section.generatedOffset.generatedLine === mapping.generatedLine
  37231. ? section.generatedOffset.generatedColumn - 1
  37232. : 0),
  37233. originalLine: mapping.originalLine,
  37234. originalColumn: mapping.originalColumn,
  37235. name: name
  37236. };
  37237. this.__generatedMappings.push(adjustedMapping);
  37238. if (typeof adjustedMapping.originalLine === 'number') {
  37239. this.__originalMappings.push(adjustedMapping);
  37240. }
  37241. }
  37242. }
  37243. quickSort(this.__generatedMappings, util$2.compareByGeneratedPositionsDeflated);
  37244. quickSort(this.__originalMappings, util$2.compareByOriginalPositions);
  37245. };
  37246. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  37247. var sourceNode = {};
  37248. /* -*- Mode: js; js-indent-level: 2; -*- */
  37249. /*
  37250. * Copyright 2011 Mozilla Foundation and contributors
  37251. * Licensed under the New BSD license. See LICENSE or:
  37252. * http://opensource.org/licenses/BSD-3-Clause
  37253. */
  37254. var SourceMapGenerator$4 = sourceMapGenerator.SourceMapGenerator;
  37255. var util$1 = util$6;
  37256. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  37257. // operating systems these days (capturing the result).
  37258. var REGEX_NEWLINE = /(\r?\n)/;
  37259. // Newline character code for charCodeAt() comparisons
  37260. var NEWLINE_CODE = 10;
  37261. // Private symbol for identifying `SourceNode`s when multiple versions of
  37262. // the source-map library are loaded. This MUST NOT CHANGE across
  37263. // versions!
  37264. var isSourceNode = "$$$isSourceNode$$$";
  37265. /**
  37266. * SourceNodes provide a way to abstract over interpolating/concatenating
  37267. * snippets of generated JavaScript source code while maintaining the line and
  37268. * column information associated with the original source code.
  37269. *
  37270. * @param aLine The original line number.
  37271. * @param aColumn The original column number.
  37272. * @param aSource The original source's filename.
  37273. * @param aChunks Optional. An array of strings which are snippets of
  37274. * generated JS, or other SourceNodes.
  37275. * @param aName The original identifier.
  37276. */
  37277. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  37278. this.children = [];
  37279. this.sourceContents = {};
  37280. this.line = aLine == null ? null : aLine;
  37281. this.column = aColumn == null ? null : aColumn;
  37282. this.source = aSource == null ? null : aSource;
  37283. this.name = aName == null ? null : aName;
  37284. this[isSourceNode] = true;
  37285. if (aChunks != null) this.add(aChunks);
  37286. }
  37287. /**
  37288. * Creates a SourceNode from generated code and a SourceMapConsumer.
  37289. *
  37290. * @param aGeneratedCode The generated code
  37291. * @param aSourceMapConsumer The SourceMap for the generated code
  37292. * @param aRelativePath Optional. The path that relative sources in the
  37293. * SourceMapConsumer should be relative to.
  37294. */
  37295. SourceNode.fromStringWithSourceMap =
  37296. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  37297. // The SourceNode we want to fill with the generated code
  37298. // and the SourceMap
  37299. var node = new SourceNode();
  37300. // All even indices of this array are one line of the generated code,
  37301. // while all odd indices are the newlines between two adjacent lines
  37302. // (since `REGEX_NEWLINE` captures its match).
  37303. // Processed fragments are accessed by calling `shiftNextLine`.
  37304. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  37305. var remainingLinesIndex = 0;
  37306. var shiftNextLine = function() {
  37307. var lineContents = getNextLine();
  37308. // The last line of a file might not have a newline.
  37309. var newLine = getNextLine() || "";
  37310. return lineContents + newLine;
  37311. function getNextLine() {
  37312. return remainingLinesIndex < remainingLines.length ?
  37313. remainingLines[remainingLinesIndex++] : undefined;
  37314. }
  37315. };
  37316. // We need to remember the position of "remainingLines"
  37317. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  37318. // The generate SourceNodes we need a code range.
  37319. // To extract it current and last mapping is used.
  37320. // Here we store the last mapping.
  37321. var lastMapping = null;
  37322. aSourceMapConsumer.eachMapping(function (mapping) {
  37323. if (lastMapping !== null) {
  37324. // We add the code from "lastMapping" to "mapping":
  37325. // First check if there is a new line in between.
  37326. if (lastGeneratedLine < mapping.generatedLine) {
  37327. // Associate first line with "lastMapping"
  37328. addMappingWithCode(lastMapping, shiftNextLine());
  37329. lastGeneratedLine++;
  37330. lastGeneratedColumn = 0;
  37331. // The remaining code is added without mapping
  37332. } else {
  37333. // There is no new line in between.
  37334. // Associate the code between "lastGeneratedColumn" and
  37335. // "mapping.generatedColumn" with "lastMapping"
  37336. var nextLine = remainingLines[remainingLinesIndex] || '';
  37337. var code = nextLine.substr(0, mapping.generatedColumn -
  37338. lastGeneratedColumn);
  37339. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  37340. lastGeneratedColumn);
  37341. lastGeneratedColumn = mapping.generatedColumn;
  37342. addMappingWithCode(lastMapping, code);
  37343. // No more remaining code, continue
  37344. lastMapping = mapping;
  37345. return;
  37346. }
  37347. }
  37348. // We add the generated code until the first mapping
  37349. // to the SourceNode without any mapping.
  37350. // Each line is added as separate string.
  37351. while (lastGeneratedLine < mapping.generatedLine) {
  37352. node.add(shiftNextLine());
  37353. lastGeneratedLine++;
  37354. }
  37355. if (lastGeneratedColumn < mapping.generatedColumn) {
  37356. var nextLine = remainingLines[remainingLinesIndex] || '';
  37357. node.add(nextLine.substr(0, mapping.generatedColumn));
  37358. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  37359. lastGeneratedColumn = mapping.generatedColumn;
  37360. }
  37361. lastMapping = mapping;
  37362. }, this);
  37363. // We have processed all mappings.
  37364. if (remainingLinesIndex < remainingLines.length) {
  37365. if (lastMapping) {
  37366. // Associate the remaining code in the current line with "lastMapping"
  37367. addMappingWithCode(lastMapping, shiftNextLine());
  37368. }
  37369. // and add the remaining lines without any mapping
  37370. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  37371. }
  37372. // Copy sourcesContent into SourceNode
  37373. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  37374. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  37375. if (content != null) {
  37376. if (aRelativePath != null) {
  37377. sourceFile = util$1.join(aRelativePath, sourceFile);
  37378. }
  37379. node.setSourceContent(sourceFile, content);
  37380. }
  37381. });
  37382. return node;
  37383. function addMappingWithCode(mapping, code) {
  37384. if (mapping === null || mapping.source === undefined) {
  37385. node.add(code);
  37386. } else {
  37387. var source = aRelativePath
  37388. ? util$1.join(aRelativePath, mapping.source)
  37389. : mapping.source;
  37390. node.add(new SourceNode(mapping.originalLine,
  37391. mapping.originalColumn,
  37392. source,
  37393. code,
  37394. mapping.name));
  37395. }
  37396. }
  37397. };
  37398. /**
  37399. * Add a chunk of generated JS to this source node.
  37400. *
  37401. * @param aChunk A string snippet of generated JS code, another instance of
  37402. * SourceNode, or an array where each member is one of those things.
  37403. */
  37404. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  37405. if (Array.isArray(aChunk)) {
  37406. aChunk.forEach(function (chunk) {
  37407. this.add(chunk);
  37408. }, this);
  37409. }
  37410. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  37411. if (aChunk) {
  37412. this.children.push(aChunk);
  37413. }
  37414. }
  37415. else {
  37416. throw new TypeError(
  37417. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  37418. );
  37419. }
  37420. return this;
  37421. };
  37422. /**
  37423. * Add a chunk of generated JS to the beginning of this source node.
  37424. *
  37425. * @param aChunk A string snippet of generated JS code, another instance of
  37426. * SourceNode, or an array where each member is one of those things.
  37427. */
  37428. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  37429. if (Array.isArray(aChunk)) {
  37430. for (var i = aChunk.length-1; i >= 0; i--) {
  37431. this.prepend(aChunk[i]);
  37432. }
  37433. }
  37434. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  37435. this.children.unshift(aChunk);
  37436. }
  37437. else {
  37438. throw new TypeError(
  37439. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  37440. );
  37441. }
  37442. return this;
  37443. };
  37444. /**
  37445. * Walk over the tree of JS snippets in this node and its children. The
  37446. * walking function is called once for each snippet of JS and is passed that
  37447. * snippet and the its original associated source's line/column location.
  37448. *
  37449. * @param aFn The traversal function.
  37450. */
  37451. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  37452. var chunk;
  37453. for (var i = 0, len = this.children.length; i < len; i++) {
  37454. chunk = this.children[i];
  37455. if (chunk[isSourceNode]) {
  37456. chunk.walk(aFn);
  37457. }
  37458. else {
  37459. if (chunk !== '') {
  37460. aFn(chunk, { source: this.source,
  37461. line: this.line,
  37462. column: this.column,
  37463. name: this.name });
  37464. }
  37465. }
  37466. }
  37467. };
  37468. /**
  37469. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  37470. * each of `this.children`.
  37471. *
  37472. * @param aSep The separator.
  37473. */
  37474. SourceNode.prototype.join = function SourceNode_join(aSep) {
  37475. var newChildren;
  37476. var i;
  37477. var len = this.children.length;
  37478. if (len > 0) {
  37479. newChildren = [];
  37480. for (i = 0; i < len-1; i++) {
  37481. newChildren.push(this.children[i]);
  37482. newChildren.push(aSep);
  37483. }
  37484. newChildren.push(this.children[i]);
  37485. this.children = newChildren;
  37486. }
  37487. return this;
  37488. };
  37489. /**
  37490. * Call String.prototype.replace on the very right-most source snippet. Useful
  37491. * for trimming whitespace from the end of a source node, etc.
  37492. *
  37493. * @param aPattern The pattern to replace.
  37494. * @param aReplacement The thing to replace the pattern with.
  37495. */
  37496. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  37497. var lastChild = this.children[this.children.length - 1];
  37498. if (lastChild[isSourceNode]) {
  37499. lastChild.replaceRight(aPattern, aReplacement);
  37500. }
  37501. else if (typeof lastChild === 'string') {
  37502. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  37503. }
  37504. else {
  37505. this.children.push(''.replace(aPattern, aReplacement));
  37506. }
  37507. return this;
  37508. };
  37509. /**
  37510. * Set the source content for a source file. This will be added to the SourceMapGenerator
  37511. * in the sourcesContent field.
  37512. *
  37513. * @param aSourceFile The filename of the source file
  37514. * @param aSourceContent The content of the source file
  37515. */
  37516. SourceNode.prototype.setSourceContent =
  37517. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  37518. this.sourceContents[util$1.toSetString(aSourceFile)] = aSourceContent;
  37519. };
  37520. /**
  37521. * Walk over the tree of SourceNodes. The walking function is called for each
  37522. * source file content and is passed the filename and source content.
  37523. *
  37524. * @param aFn The traversal function.
  37525. */
  37526. SourceNode.prototype.walkSourceContents =
  37527. function SourceNode_walkSourceContents(aFn) {
  37528. for (var i = 0, len = this.children.length; i < len; i++) {
  37529. if (this.children[i][isSourceNode]) {
  37530. this.children[i].walkSourceContents(aFn);
  37531. }
  37532. }
  37533. var sources = Object.keys(this.sourceContents);
  37534. for (var i = 0, len = sources.length; i < len; i++) {
  37535. aFn(util$1.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  37536. }
  37537. };
  37538. /**
  37539. * Return the string representation of this source node. Walks over the tree
  37540. * and concatenates all the various snippets together to one string.
  37541. */
  37542. SourceNode.prototype.toString = function SourceNode_toString() {
  37543. var str = "";
  37544. this.walk(function (chunk) {
  37545. str += chunk;
  37546. });
  37547. return str;
  37548. };
  37549. /**
  37550. * Returns the string representation of this source node along with a source
  37551. * map.
  37552. */
  37553. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  37554. var generated = {
  37555. code: "",
  37556. line: 1,
  37557. column: 0
  37558. };
  37559. var map = new SourceMapGenerator$4(aArgs);
  37560. var sourceMappingActive = false;
  37561. var lastOriginalSource = null;
  37562. var lastOriginalLine = null;
  37563. var lastOriginalColumn = null;
  37564. var lastOriginalName = null;
  37565. this.walk(function (chunk, original) {
  37566. generated.code += chunk;
  37567. if (original.source !== null
  37568. && original.line !== null
  37569. && original.column !== null) {
  37570. if(lastOriginalSource !== original.source
  37571. || lastOriginalLine !== original.line
  37572. || lastOriginalColumn !== original.column
  37573. || lastOriginalName !== original.name) {
  37574. map.addMapping({
  37575. source: original.source,
  37576. original: {
  37577. line: original.line,
  37578. column: original.column
  37579. },
  37580. generated: {
  37581. line: generated.line,
  37582. column: generated.column
  37583. },
  37584. name: original.name
  37585. });
  37586. }
  37587. lastOriginalSource = original.source;
  37588. lastOriginalLine = original.line;
  37589. lastOriginalColumn = original.column;
  37590. lastOriginalName = original.name;
  37591. sourceMappingActive = true;
  37592. } else if (sourceMappingActive) {
  37593. map.addMapping({
  37594. generated: {
  37595. line: generated.line,
  37596. column: generated.column
  37597. }
  37598. });
  37599. lastOriginalSource = null;
  37600. sourceMappingActive = false;
  37601. }
  37602. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  37603. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  37604. generated.line++;
  37605. generated.column = 0;
  37606. // Mappings end at eol
  37607. if (idx + 1 === length) {
  37608. lastOriginalSource = null;
  37609. sourceMappingActive = false;
  37610. } else if (sourceMappingActive) {
  37611. map.addMapping({
  37612. source: original.source,
  37613. original: {
  37614. line: original.line,
  37615. column: original.column
  37616. },
  37617. generated: {
  37618. line: generated.line,
  37619. column: generated.column
  37620. },
  37621. name: original.name
  37622. });
  37623. }
  37624. } else {
  37625. generated.column++;
  37626. }
  37627. }
  37628. });
  37629. this.walkSourceContents(function (sourceFile, sourceContent) {
  37630. map.setSourceContent(sourceFile, sourceContent);
  37631. });
  37632. return { code: generated.code, map: map };
  37633. };
  37634. sourceNode.SourceNode = SourceNode;
  37635. /*
  37636. * Copyright 2009-2011 Mozilla Foundation and contributors
  37637. * Licensed under the New BSD license. See LICENSE.txt or:
  37638. * http://opensource.org/licenses/BSD-3-Clause
  37639. */
  37640. sourceMap$1.SourceMapGenerator = sourceMapGenerator.SourceMapGenerator;
  37641. sourceMap$1.SourceMapConsumer = sourceMapConsumer.SourceMapConsumer;
  37642. sourceMap$1.SourceNode = sourceNode.SourceNode;
  37643. var require$$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_url$1);
  37644. let urlAlphabet =
  37645. 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
  37646. let customAlphabet = (alphabet, size) => {
  37647. return () => {
  37648. let id = '';
  37649. let i = size;
  37650. while (i--) {
  37651. id += alphabet[(Math.random() * alphabet.length) | 0];
  37652. }
  37653. return id
  37654. }
  37655. };
  37656. let nanoid$1 = (size = 21) => {
  37657. let id = '';
  37658. let i = size;
  37659. while (i--) {
  37660. id += urlAlphabet[(Math.random() * 64) | 0];
  37661. }
  37662. return id
  37663. };
  37664. var nonSecure = { nanoid: nanoid$1, customAlphabet };
  37665. let { SourceMapConsumer: SourceMapConsumer$3, SourceMapGenerator: SourceMapGenerator$3 } = sourceMap$1;
  37666. let { existsSync, readFileSync } = require$$0$2;
  37667. let { dirname: dirname$1, join } = require$$2$1;
  37668. function fromBase64(str) {
  37669. if (Buffer) {
  37670. return Buffer.from(str, 'base64').toString()
  37671. } else {
  37672. /* c8 ignore next 2 */
  37673. return window.atob(str)
  37674. }
  37675. }
  37676. let PreviousMap$2 = class PreviousMap {
  37677. constructor(css, opts) {
  37678. if (opts.map === false) return
  37679. this.loadAnnotation(css);
  37680. this.inline = this.startWith(this.annotation, 'data:');
  37681. let prev = opts.map ? opts.map.prev : undefined;
  37682. let text = this.loadMap(opts.from, prev);
  37683. if (!this.mapFile && opts.from) {
  37684. this.mapFile = opts.from;
  37685. }
  37686. if (this.mapFile) this.root = dirname$1(this.mapFile);
  37687. if (text) this.text = text;
  37688. }
  37689. consumer() {
  37690. if (!this.consumerCache) {
  37691. this.consumerCache = new SourceMapConsumer$3(this.text);
  37692. }
  37693. return this.consumerCache
  37694. }
  37695. withContent() {
  37696. return !!(
  37697. this.consumer().sourcesContent &&
  37698. this.consumer().sourcesContent.length > 0
  37699. )
  37700. }
  37701. startWith(string, start) {
  37702. if (!string) return false
  37703. return string.substr(0, start.length) === start
  37704. }
  37705. getAnnotationURL(sourceMapString) {
  37706. return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, '').trim()
  37707. }
  37708. loadAnnotation(css) {
  37709. let comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
  37710. if (!comments) return
  37711. // sourceMappingURLs from comments, strings, etc.
  37712. let start = css.lastIndexOf(comments.pop());
  37713. let end = css.indexOf('*/', start);
  37714. if (start > -1 && end > -1) {
  37715. // Locate the last sourceMappingURL to avoid pickin
  37716. this.annotation = this.getAnnotationURL(css.substring(start, end));
  37717. }
  37718. }
  37719. decodeInline(text) {
  37720. let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
  37721. let baseUri = /^data:application\/json;base64,/;
  37722. let charsetUri = /^data:application\/json;charset=utf-?8,/;
  37723. let uri = /^data:application\/json,/;
  37724. if (charsetUri.test(text) || uri.test(text)) {
  37725. return decodeURIComponent(text.substr(RegExp.lastMatch.length))
  37726. }
  37727. if (baseCharsetUri.test(text) || baseUri.test(text)) {
  37728. return fromBase64(text.substr(RegExp.lastMatch.length))
  37729. }
  37730. let encoding = text.match(/data:application\/json;([^,]+),/)[1];
  37731. throw new Error('Unsupported source map encoding ' + encoding)
  37732. }
  37733. loadFile(path) {
  37734. this.root = dirname$1(path);
  37735. if (existsSync(path)) {
  37736. this.mapFile = path;
  37737. return readFileSync(path, 'utf-8').toString().trim()
  37738. }
  37739. }
  37740. loadMap(file, prev) {
  37741. if (prev === false) return false
  37742. if (prev) {
  37743. if (typeof prev === 'string') {
  37744. return prev
  37745. } else if (typeof prev === 'function') {
  37746. let prevPath = prev(file);
  37747. if (prevPath) {
  37748. let map = this.loadFile(prevPath);
  37749. if (!map) {
  37750. throw new Error(
  37751. 'Unable to load previous source map: ' + prevPath.toString()
  37752. )
  37753. }
  37754. return map
  37755. }
  37756. } else if (prev instanceof SourceMapConsumer$3) {
  37757. return SourceMapGenerator$3.fromSourceMap(prev).toString()
  37758. } else if (prev instanceof SourceMapGenerator$3) {
  37759. return prev.toString()
  37760. } else if (this.isMap(prev)) {
  37761. return JSON.stringify(prev)
  37762. } else {
  37763. throw new Error(
  37764. 'Unsupported previous source map format: ' + prev.toString()
  37765. )
  37766. }
  37767. } else if (this.inline) {
  37768. return this.decodeInline(this.annotation)
  37769. } else if (this.annotation) {
  37770. let map = this.annotation;
  37771. if (file) map = join(dirname$1(file), map);
  37772. return this.loadFile(map)
  37773. }
  37774. }
  37775. isMap(map) {
  37776. if (typeof map !== 'object') return false
  37777. return (
  37778. typeof map.mappings === 'string' ||
  37779. typeof map._mappings === 'string' ||
  37780. Array.isArray(map.sections)
  37781. )
  37782. }
  37783. };
  37784. var previousMap = PreviousMap$2;
  37785. PreviousMap$2.default = PreviousMap$2;
  37786. let { SourceMapConsumer: SourceMapConsumer$2, SourceMapGenerator: SourceMapGenerator$2 } = sourceMap$1;
  37787. let { fileURLToPath, pathToFileURL: pathToFileURL$1 } = require$$2;
  37788. let { resolve: resolve$1, isAbsolute } = require$$2$1;
  37789. let { nanoid } = nonSecure;
  37790. let terminalHighlight = terminalHighlight_1;
  37791. let CssSyntaxError$1 = cssSyntaxError;
  37792. let PreviousMap$1 = previousMap;
  37793. let fromOffsetCache = Symbol('fromOffsetCache');
  37794. let sourceMapAvailable$1 = Boolean(SourceMapConsumer$2 && SourceMapGenerator$2);
  37795. let pathAvailable$1 = Boolean(resolve$1 && isAbsolute);
  37796. let Input$4 = class Input {
  37797. constructor(css, opts = {}) {
  37798. if (
  37799. css === null ||
  37800. typeof css === 'undefined' ||
  37801. (typeof css === 'object' && !css.toString)
  37802. ) {
  37803. throw new Error(`PostCSS received ${css} instead of CSS string`)
  37804. }
  37805. this.css = css.toString();
  37806. if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
  37807. this.hasBOM = true;
  37808. this.css = this.css.slice(1);
  37809. } else {
  37810. this.hasBOM = false;
  37811. }
  37812. if (opts.from) {
  37813. if (
  37814. !pathAvailable$1 ||
  37815. /^\w+:\/\//.test(opts.from) ||
  37816. isAbsolute(opts.from)
  37817. ) {
  37818. this.file = opts.from;
  37819. } else {
  37820. this.file = resolve$1(opts.from);
  37821. }
  37822. }
  37823. if (pathAvailable$1 && sourceMapAvailable$1) {
  37824. let map = new PreviousMap$1(this.css, opts);
  37825. if (map.text) {
  37826. this.map = map;
  37827. let file = map.consumer().file;
  37828. if (!this.file && file) this.file = this.mapResolve(file);
  37829. }
  37830. }
  37831. if (!this.file) {
  37832. this.id = '<input css ' + nanoid(6) + '>';
  37833. }
  37834. if (this.map) this.map.file = this.from;
  37835. }
  37836. fromOffset(offset) {
  37837. let lastLine, lineToIndex;
  37838. if (!this[fromOffsetCache]) {
  37839. let lines = this.css.split('\n');
  37840. lineToIndex = new Array(lines.length);
  37841. let prevIndex = 0;
  37842. for (let i = 0, l = lines.length; i < l; i++) {
  37843. lineToIndex[i] = prevIndex;
  37844. prevIndex += lines[i].length + 1;
  37845. }
  37846. this[fromOffsetCache] = lineToIndex;
  37847. } else {
  37848. lineToIndex = this[fromOffsetCache];
  37849. }
  37850. lastLine = lineToIndex[lineToIndex.length - 1];
  37851. let min = 0;
  37852. if (offset >= lastLine) {
  37853. min = lineToIndex.length - 1;
  37854. } else {
  37855. let max = lineToIndex.length - 2;
  37856. let mid;
  37857. while (min < max) {
  37858. mid = min + ((max - min) >> 1);
  37859. if (offset < lineToIndex[mid]) {
  37860. max = mid - 1;
  37861. } else if (offset >= lineToIndex[mid + 1]) {
  37862. min = mid + 1;
  37863. } else {
  37864. min = mid;
  37865. break
  37866. }
  37867. }
  37868. }
  37869. return {
  37870. line: min + 1,
  37871. col: offset - lineToIndex[min] + 1
  37872. }
  37873. }
  37874. error(message, line, column, opts = {}) {
  37875. let result, endLine, endColumn;
  37876. if (line && typeof line === 'object') {
  37877. let start = line;
  37878. let end = column;
  37879. if (typeof line.offset === 'number') {
  37880. let pos = this.fromOffset(start.offset);
  37881. line = pos.line;
  37882. column = pos.col;
  37883. } else {
  37884. line = start.line;
  37885. column = start.column;
  37886. }
  37887. if (typeof end.offset === 'number') {
  37888. let pos = this.fromOffset(end.offset);
  37889. endLine = pos.line;
  37890. endColumn = pos.col;
  37891. } else {
  37892. endLine = end.line;
  37893. endColumn = end.column;
  37894. }
  37895. } else if (!column) {
  37896. let pos = this.fromOffset(line);
  37897. line = pos.line;
  37898. column = pos.col;
  37899. }
  37900. let origin = this.origin(line, column, endLine, endColumn);
  37901. if (origin) {
  37902. result = new CssSyntaxError$1(
  37903. message,
  37904. origin.endLine === undefined
  37905. ? origin.line
  37906. : { line: origin.line, column: origin.column },
  37907. origin.endLine === undefined
  37908. ? origin.column
  37909. : { line: origin.endLine, column: origin.endColumn },
  37910. origin.source,
  37911. origin.file,
  37912. opts.plugin
  37913. );
  37914. } else {
  37915. result = new CssSyntaxError$1(
  37916. message,
  37917. endLine === undefined ? line : { line, column },
  37918. endLine === undefined ? column : { line: endLine, column: endColumn },
  37919. this.css,
  37920. this.file,
  37921. opts.plugin
  37922. );
  37923. }
  37924. result.input = { line, column, endLine, endColumn, source: this.css };
  37925. if (this.file) {
  37926. if (pathToFileURL$1) {
  37927. result.input.url = pathToFileURL$1(this.file).toString();
  37928. }
  37929. result.input.file = this.file;
  37930. }
  37931. return result
  37932. }
  37933. origin(line, column, endLine, endColumn) {
  37934. if (!this.map) return false
  37935. let consumer = this.map.consumer();
  37936. let from = consumer.originalPositionFor({ line, column });
  37937. if (!from.source) return false
  37938. let to;
  37939. if (typeof endLine === 'number') {
  37940. to = consumer.originalPositionFor({ line: endLine, column: endColumn });
  37941. }
  37942. let fromUrl;
  37943. if (isAbsolute(from.source)) {
  37944. fromUrl = pathToFileURL$1(from.source);
  37945. } else {
  37946. fromUrl = new URL(
  37947. from.source,
  37948. this.map.consumer().sourceRoot || pathToFileURL$1(this.map.mapFile)
  37949. );
  37950. }
  37951. let result = {
  37952. url: fromUrl.toString(),
  37953. line: from.line,
  37954. column: from.column,
  37955. endLine: to && to.line,
  37956. endColumn: to && to.column
  37957. };
  37958. if (fromUrl.protocol === 'file:') {
  37959. if (fileURLToPath) {
  37960. result.file = fileURLToPath(fromUrl);
  37961. } else {
  37962. /* c8 ignore next 2 */
  37963. throw new Error(`file: protocol is not available in this PostCSS build`)
  37964. }
  37965. }
  37966. let source = consumer.sourceContentFor(from.source);
  37967. if (source) result.source = source;
  37968. return result
  37969. }
  37970. mapResolve(file) {
  37971. if (/^\w+:\/\//.test(file)) {
  37972. return file
  37973. }
  37974. return resolve$1(this.map.consumer().sourceRoot || this.map.root || '.', file)
  37975. }
  37976. get from() {
  37977. return this.file || this.id
  37978. }
  37979. toJSON() {
  37980. let json = {};
  37981. for (let name of ['hasBOM', 'css', 'file', 'id']) {
  37982. if (this[name] != null) {
  37983. json[name] = this[name];
  37984. }
  37985. }
  37986. if (this.map) {
  37987. json.map = { ...this.map };
  37988. if (json.map.consumerCache) {
  37989. json.map.consumerCache = undefined;
  37990. }
  37991. }
  37992. return json
  37993. }
  37994. };
  37995. var input = Input$4;
  37996. Input$4.default = Input$4;
  37997. if (terminalHighlight && terminalHighlight.registerInput) {
  37998. terminalHighlight.registerInput(Input$4);
  37999. }
  38000. let { SourceMapConsumer: SourceMapConsumer$1, SourceMapGenerator: SourceMapGenerator$1 } = sourceMap$1;
  38001. let { dirname, resolve, relative, sep } = require$$2$1;
  38002. let { pathToFileURL } = require$$2;
  38003. let Input$3 = input;
  38004. let sourceMapAvailable = Boolean(SourceMapConsumer$1 && SourceMapGenerator$1);
  38005. let pathAvailable = Boolean(dirname && resolve && relative && sep);
  38006. let MapGenerator$2 = class MapGenerator {
  38007. constructor(stringify, root, opts, cssString) {
  38008. this.stringify = stringify;
  38009. this.mapOpts = opts.map || {};
  38010. this.root = root;
  38011. this.opts = opts;
  38012. this.css = cssString;
  38013. }
  38014. isMap() {
  38015. if (typeof this.opts.map !== 'undefined') {
  38016. return !!this.opts.map
  38017. }
  38018. return this.previous().length > 0
  38019. }
  38020. previous() {
  38021. if (!this.previousMaps) {
  38022. this.previousMaps = [];
  38023. if (this.root) {
  38024. this.root.walk(node => {
  38025. if (node.source && node.source.input.map) {
  38026. let map = node.source.input.map;
  38027. if (!this.previousMaps.includes(map)) {
  38028. this.previousMaps.push(map);
  38029. }
  38030. }
  38031. });
  38032. } else {
  38033. let input = new Input$3(this.css, this.opts);
  38034. if (input.map) this.previousMaps.push(input.map);
  38035. }
  38036. }
  38037. return this.previousMaps
  38038. }
  38039. isInline() {
  38040. if (typeof this.mapOpts.inline !== 'undefined') {
  38041. return this.mapOpts.inline
  38042. }
  38043. let annotation = this.mapOpts.annotation;
  38044. if (typeof annotation !== 'undefined' && annotation !== true) {
  38045. return false
  38046. }
  38047. if (this.previous().length) {
  38048. return this.previous().some(i => i.inline)
  38049. }
  38050. return true
  38051. }
  38052. isSourcesContent() {
  38053. if (typeof this.mapOpts.sourcesContent !== 'undefined') {
  38054. return this.mapOpts.sourcesContent
  38055. }
  38056. if (this.previous().length) {
  38057. return this.previous().some(i => i.withContent())
  38058. }
  38059. return true
  38060. }
  38061. clearAnnotation() {
  38062. if (this.mapOpts.annotation === false) return
  38063. if (this.root) {
  38064. let node;
  38065. for (let i = this.root.nodes.length - 1; i >= 0; i--) {
  38066. node = this.root.nodes[i];
  38067. if (node.type !== 'comment') continue
  38068. if (node.text.indexOf('# sourceMappingURL=') === 0) {
  38069. this.root.removeChild(i);
  38070. }
  38071. }
  38072. } else if (this.css) {
  38073. this.css = this.css.replace(/(\n)?\/\*#[\S\s]*?\*\/$/gm, '');
  38074. }
  38075. }
  38076. setSourcesContent() {
  38077. let already = {};
  38078. if (this.root) {
  38079. this.root.walk(node => {
  38080. if (node.source) {
  38081. let from = node.source.input.from;
  38082. if (from && !already[from]) {
  38083. already[from] = true;
  38084. this.map.setSourceContent(
  38085. this.toUrl(this.path(from)),
  38086. node.source.input.css
  38087. );
  38088. }
  38089. }
  38090. });
  38091. } else if (this.css) {
  38092. let from = this.opts.from
  38093. ? this.toUrl(this.path(this.opts.from))
  38094. : '<no source>';
  38095. this.map.setSourceContent(from, this.css);
  38096. }
  38097. }
  38098. applyPrevMaps() {
  38099. for (let prev of this.previous()) {
  38100. let from = this.toUrl(this.path(prev.file));
  38101. let root = prev.root || dirname(prev.file);
  38102. let map;
  38103. if (this.mapOpts.sourcesContent === false) {
  38104. map = new SourceMapConsumer$1(prev.text);
  38105. if (map.sourcesContent) {
  38106. map.sourcesContent = map.sourcesContent.map(() => null);
  38107. }
  38108. } else {
  38109. map = prev.consumer();
  38110. }
  38111. this.map.applySourceMap(map, from, this.toUrl(this.path(root)));
  38112. }
  38113. }
  38114. isAnnotation() {
  38115. if (this.isInline()) {
  38116. return true
  38117. }
  38118. if (typeof this.mapOpts.annotation !== 'undefined') {
  38119. return this.mapOpts.annotation
  38120. }
  38121. if (this.previous().length) {
  38122. return this.previous().some(i => i.annotation)
  38123. }
  38124. return true
  38125. }
  38126. toBase64(str) {
  38127. if (Buffer) {
  38128. return Buffer.from(str).toString('base64')
  38129. } else {
  38130. return window.btoa(unescape(encodeURIComponent(str)))
  38131. }
  38132. }
  38133. addAnnotation() {
  38134. let content;
  38135. if (this.isInline()) {
  38136. content =
  38137. 'data:application/json;base64,' + this.toBase64(this.map.toString());
  38138. } else if (typeof this.mapOpts.annotation === 'string') {
  38139. content = this.mapOpts.annotation;
  38140. } else if (typeof this.mapOpts.annotation === 'function') {
  38141. content = this.mapOpts.annotation(this.opts.to, this.root);
  38142. } else {
  38143. content = this.outputFile() + '.map';
  38144. }
  38145. let eol = '\n';
  38146. if (this.css.includes('\r\n')) eol = '\r\n';
  38147. this.css += eol + '/*# sourceMappingURL=' + content + ' */';
  38148. }
  38149. outputFile() {
  38150. if (this.opts.to) {
  38151. return this.path(this.opts.to)
  38152. } else if (this.opts.from) {
  38153. return this.path(this.opts.from)
  38154. } else {
  38155. return 'to.css'
  38156. }
  38157. }
  38158. generateMap() {
  38159. if (this.root) {
  38160. this.generateString();
  38161. } else if (this.previous().length === 1) {
  38162. let prev = this.previous()[0].consumer();
  38163. prev.file = this.outputFile();
  38164. this.map = SourceMapGenerator$1.fromSourceMap(prev);
  38165. } else {
  38166. this.map = new SourceMapGenerator$1({ file: this.outputFile() });
  38167. this.map.addMapping({
  38168. source: this.opts.from
  38169. ? this.toUrl(this.path(this.opts.from))
  38170. : '<no source>',
  38171. generated: { line: 1, column: 0 },
  38172. original: { line: 1, column: 0 }
  38173. });
  38174. }
  38175. if (this.isSourcesContent()) this.setSourcesContent();
  38176. if (this.root && this.previous().length > 0) this.applyPrevMaps();
  38177. if (this.isAnnotation()) this.addAnnotation();
  38178. if (this.isInline()) {
  38179. return [this.css]
  38180. } else {
  38181. return [this.css, this.map]
  38182. }
  38183. }
  38184. path(file) {
  38185. if (file.indexOf('<') === 0) return file
  38186. if (/^\w+:\/\//.test(file)) return file
  38187. if (this.mapOpts.absolute) return file
  38188. let from = this.opts.to ? dirname(this.opts.to) : '.';
  38189. if (typeof this.mapOpts.annotation === 'string') {
  38190. from = dirname(resolve(from, this.mapOpts.annotation));
  38191. }
  38192. file = relative(from, file);
  38193. return file
  38194. }
  38195. toUrl(path) {
  38196. if (sep === '\\') {
  38197. path = path.replace(/\\/g, '/');
  38198. }
  38199. return encodeURI(path).replace(/[#?]/g, encodeURIComponent)
  38200. }
  38201. sourcePath(node) {
  38202. if (this.mapOpts.from) {
  38203. return this.toUrl(this.mapOpts.from)
  38204. } else if (this.mapOpts.absolute) {
  38205. if (pathToFileURL) {
  38206. return pathToFileURL(node.source.input.from).toString()
  38207. } else {
  38208. throw new Error(
  38209. '`map.absolute` option is not available in this PostCSS build'
  38210. )
  38211. }
  38212. } else {
  38213. return this.toUrl(this.path(node.source.input.from))
  38214. }
  38215. }
  38216. generateString() {
  38217. this.css = '';
  38218. this.map = new SourceMapGenerator$1({ file: this.outputFile() });
  38219. let line = 1;
  38220. let column = 1;
  38221. let noSource = '<no source>';
  38222. let mapping = {
  38223. source: '',
  38224. generated: { line: 0, column: 0 },
  38225. original: { line: 0, column: 0 }
  38226. };
  38227. let lines, last;
  38228. this.stringify(this.root, (str, node, type) => {
  38229. this.css += str;
  38230. if (node && type !== 'end') {
  38231. mapping.generated.line = line;
  38232. mapping.generated.column = column - 1;
  38233. if (node.source && node.source.start) {
  38234. mapping.source = this.sourcePath(node);
  38235. mapping.original.line = node.source.start.line;
  38236. mapping.original.column = node.source.start.column - 1;
  38237. this.map.addMapping(mapping);
  38238. } else {
  38239. mapping.source = noSource;
  38240. mapping.original.line = 1;
  38241. mapping.original.column = 0;
  38242. this.map.addMapping(mapping);
  38243. }
  38244. }
  38245. lines = str.match(/\n/g);
  38246. if (lines) {
  38247. line += lines.length;
  38248. last = str.lastIndexOf('\n');
  38249. column = str.length - last;
  38250. } else {
  38251. column += str.length;
  38252. }
  38253. if (node && type !== 'start') {
  38254. let p = node.parent || { raws: {} };
  38255. if (node.type !== 'decl' || node !== p.last || p.raws.semicolon) {
  38256. if (node.source && node.source.end) {
  38257. mapping.source = this.sourcePath(node);
  38258. mapping.original.line = node.source.end.line;
  38259. mapping.original.column = node.source.end.column - 1;
  38260. mapping.generated.line = line;
  38261. mapping.generated.column = column - 2;
  38262. this.map.addMapping(mapping);
  38263. } else {
  38264. mapping.source = noSource;
  38265. mapping.original.line = 1;
  38266. mapping.original.column = 0;
  38267. mapping.generated.line = line;
  38268. mapping.generated.column = column - 1;
  38269. this.map.addMapping(mapping);
  38270. }
  38271. }
  38272. }
  38273. });
  38274. }
  38275. generate() {
  38276. this.clearAnnotation();
  38277. if (pathAvailable && sourceMapAvailable && this.isMap()) {
  38278. return this.generateMap()
  38279. } else {
  38280. let result = '';
  38281. this.stringify(this.root, i => {
  38282. result += i;
  38283. });
  38284. return [result]
  38285. }
  38286. }
  38287. };
  38288. var mapGenerator = MapGenerator$2;
  38289. let Node$2 = node$2;
  38290. let Comment$4 = class Comment extends Node$2 {
  38291. constructor(defaults) {
  38292. super(defaults);
  38293. this.type = 'comment';
  38294. }
  38295. };
  38296. var comment$3 = Comment$4;
  38297. Comment$4.default = Comment$4;
  38298. let { isClean: isClean$1, my: my$1 } = symbols;
  38299. let Declaration$3 = declaration;
  38300. let Comment$3 = comment$3;
  38301. let Node$1 = node$2;
  38302. let parse$4, Rule$4, AtRule$4;
  38303. function cleanSource(nodes) {
  38304. return nodes.map(i => {
  38305. if (i.nodes) i.nodes = cleanSource(i.nodes);
  38306. delete i.source;
  38307. return i
  38308. })
  38309. }
  38310. function markDirtyUp(node) {
  38311. node[isClean$1] = false;
  38312. if (node.proxyOf.nodes) {
  38313. for (let i of node.proxyOf.nodes) {
  38314. markDirtyUp(i);
  38315. }
  38316. }
  38317. }
  38318. let Container$7 = class Container extends Node$1 {
  38319. push(child) {
  38320. child.parent = this;
  38321. this.proxyOf.nodes.push(child);
  38322. return this
  38323. }
  38324. each(callback) {
  38325. if (!this.proxyOf.nodes) return undefined
  38326. let iterator = this.getIterator();
  38327. let index, result;
  38328. while (this.indexes[iterator] < this.proxyOf.nodes.length) {
  38329. index = this.indexes[iterator];
  38330. result = callback(this.proxyOf.nodes[index], index);
  38331. if (result === false) break
  38332. this.indexes[iterator] += 1;
  38333. }
  38334. delete this.indexes[iterator];
  38335. return result
  38336. }
  38337. walk(callback) {
  38338. return this.each((child, i) => {
  38339. let result;
  38340. try {
  38341. result = callback(child, i);
  38342. } catch (e) {
  38343. throw child.addToError(e)
  38344. }
  38345. if (result !== false && child.walk) {
  38346. result = child.walk(callback);
  38347. }
  38348. return result
  38349. })
  38350. }
  38351. walkDecls(prop, callback) {
  38352. if (!callback) {
  38353. callback = prop;
  38354. return this.walk((child, i) => {
  38355. if (child.type === 'decl') {
  38356. return callback(child, i)
  38357. }
  38358. })
  38359. }
  38360. if (prop instanceof RegExp) {
  38361. return this.walk((child, i) => {
  38362. if (child.type === 'decl' && prop.test(child.prop)) {
  38363. return callback(child, i)
  38364. }
  38365. })
  38366. }
  38367. return this.walk((child, i) => {
  38368. if (child.type === 'decl' && child.prop === prop) {
  38369. return callback(child, i)
  38370. }
  38371. })
  38372. }
  38373. walkRules(selector, callback) {
  38374. if (!callback) {
  38375. callback = selector;
  38376. return this.walk((child, i) => {
  38377. if (child.type === 'rule') {
  38378. return callback(child, i)
  38379. }
  38380. })
  38381. }
  38382. if (selector instanceof RegExp) {
  38383. return this.walk((child, i) => {
  38384. if (child.type === 'rule' && selector.test(child.selector)) {
  38385. return callback(child, i)
  38386. }
  38387. })
  38388. }
  38389. return this.walk((child, i) => {
  38390. if (child.type === 'rule' && child.selector === selector) {
  38391. return callback(child, i)
  38392. }
  38393. })
  38394. }
  38395. walkAtRules(name, callback) {
  38396. if (!callback) {
  38397. callback = name;
  38398. return this.walk((child, i) => {
  38399. if (child.type === 'atrule') {
  38400. return callback(child, i)
  38401. }
  38402. })
  38403. }
  38404. if (name instanceof RegExp) {
  38405. return this.walk((child, i) => {
  38406. if (child.type === 'atrule' && name.test(child.name)) {
  38407. return callback(child, i)
  38408. }
  38409. })
  38410. }
  38411. return this.walk((child, i) => {
  38412. if (child.type === 'atrule' && child.name === name) {
  38413. return callback(child, i)
  38414. }
  38415. })
  38416. }
  38417. walkComments(callback) {
  38418. return this.walk((child, i) => {
  38419. if (child.type === 'comment') {
  38420. return callback(child, i)
  38421. }
  38422. })
  38423. }
  38424. append(...children) {
  38425. for (let child of children) {
  38426. let nodes = this.normalize(child, this.last);
  38427. for (let node of nodes) this.proxyOf.nodes.push(node);
  38428. }
  38429. this.markDirty();
  38430. return this
  38431. }
  38432. prepend(...children) {
  38433. children = children.reverse();
  38434. for (let child of children) {
  38435. let nodes = this.normalize(child, this.first, 'prepend').reverse();
  38436. for (let node of nodes) this.proxyOf.nodes.unshift(node);
  38437. for (let id in this.indexes) {
  38438. this.indexes[id] = this.indexes[id] + nodes.length;
  38439. }
  38440. }
  38441. this.markDirty();
  38442. return this
  38443. }
  38444. cleanRaws(keepBetween) {
  38445. super.cleanRaws(keepBetween);
  38446. if (this.nodes) {
  38447. for (let node of this.nodes) node.cleanRaws(keepBetween);
  38448. }
  38449. }
  38450. insertBefore(exist, add) {
  38451. exist = this.index(exist);
  38452. let type = exist === 0 ? 'prepend' : false;
  38453. let nodes = this.normalize(add, this.proxyOf.nodes[exist], type).reverse();
  38454. for (let node of nodes) this.proxyOf.nodes.splice(exist, 0, node);
  38455. let index;
  38456. for (let id in this.indexes) {
  38457. index = this.indexes[id];
  38458. if (exist <= index) {
  38459. this.indexes[id] = index + nodes.length;
  38460. }
  38461. }
  38462. this.markDirty();
  38463. return this
  38464. }
  38465. insertAfter(exist, add) {
  38466. exist = this.index(exist);
  38467. let nodes = this.normalize(add, this.proxyOf.nodes[exist]).reverse();
  38468. for (let node of nodes) this.proxyOf.nodes.splice(exist + 1, 0, node);
  38469. let index;
  38470. for (let id in this.indexes) {
  38471. index = this.indexes[id];
  38472. if (exist < index) {
  38473. this.indexes[id] = index + nodes.length;
  38474. }
  38475. }
  38476. this.markDirty();
  38477. return this
  38478. }
  38479. removeChild(child) {
  38480. child = this.index(child);
  38481. this.proxyOf.nodes[child].parent = undefined;
  38482. this.proxyOf.nodes.splice(child, 1);
  38483. let index;
  38484. for (let id in this.indexes) {
  38485. index = this.indexes[id];
  38486. if (index >= child) {
  38487. this.indexes[id] = index - 1;
  38488. }
  38489. }
  38490. this.markDirty();
  38491. return this
  38492. }
  38493. removeAll() {
  38494. for (let node of this.proxyOf.nodes) node.parent = undefined;
  38495. this.proxyOf.nodes = [];
  38496. this.markDirty();
  38497. return this
  38498. }
  38499. replaceValues(pattern, opts, callback) {
  38500. if (!callback) {
  38501. callback = opts;
  38502. opts = {};
  38503. }
  38504. this.walkDecls(decl => {
  38505. if (opts.props && !opts.props.includes(decl.prop)) return
  38506. if (opts.fast && !decl.value.includes(opts.fast)) return
  38507. decl.value = decl.value.replace(pattern, callback);
  38508. });
  38509. this.markDirty();
  38510. return this
  38511. }
  38512. every(condition) {
  38513. return this.nodes.every(condition)
  38514. }
  38515. some(condition) {
  38516. return this.nodes.some(condition)
  38517. }
  38518. index(child) {
  38519. if (typeof child === 'number') return child
  38520. if (child.proxyOf) child = child.proxyOf;
  38521. return this.proxyOf.nodes.indexOf(child)
  38522. }
  38523. get first() {
  38524. if (!this.proxyOf.nodes) return undefined
  38525. return this.proxyOf.nodes[0]
  38526. }
  38527. get last() {
  38528. if (!this.proxyOf.nodes) return undefined
  38529. return this.proxyOf.nodes[this.proxyOf.nodes.length - 1]
  38530. }
  38531. normalize(nodes, sample) {
  38532. if (typeof nodes === 'string') {
  38533. nodes = cleanSource(parse$4(nodes).nodes);
  38534. } else if (Array.isArray(nodes)) {
  38535. nodes = nodes.slice(0);
  38536. for (let i of nodes) {
  38537. if (i.parent) i.parent.removeChild(i, 'ignore');
  38538. }
  38539. } else if (nodes.type === 'root' && this.type !== 'document') {
  38540. nodes = nodes.nodes.slice(0);
  38541. for (let i of nodes) {
  38542. if (i.parent) i.parent.removeChild(i, 'ignore');
  38543. }
  38544. } else if (nodes.type) {
  38545. nodes = [nodes];
  38546. } else if (nodes.prop) {
  38547. if (typeof nodes.value === 'undefined') {
  38548. throw new Error('Value field is missed in node creation')
  38549. } else if (typeof nodes.value !== 'string') {
  38550. nodes.value = String(nodes.value);
  38551. }
  38552. nodes = [new Declaration$3(nodes)];
  38553. } else if (nodes.selector) {
  38554. nodes = [new Rule$4(nodes)];
  38555. } else if (nodes.name) {
  38556. nodes = [new AtRule$4(nodes)];
  38557. } else if (nodes.text) {
  38558. nodes = [new Comment$3(nodes)];
  38559. } else {
  38560. throw new Error('Unknown node type in node creation')
  38561. }
  38562. let processed = nodes.map(i => {
  38563. /* c8 ignore next */
  38564. if (!i[my$1]) Container$7.rebuild(i);
  38565. i = i.proxyOf;
  38566. if (i.parent) i.parent.removeChild(i);
  38567. if (i[isClean$1]) markDirtyUp(i);
  38568. if (typeof i.raws.before === 'undefined') {
  38569. if (sample && typeof sample.raws.before !== 'undefined') {
  38570. i.raws.before = sample.raws.before.replace(/\S/g, '');
  38571. }
  38572. }
  38573. i.parent = this;
  38574. return i
  38575. });
  38576. return processed
  38577. }
  38578. getProxyProcessor() {
  38579. return {
  38580. set(node, prop, value) {
  38581. if (node[prop] === value) return true
  38582. node[prop] = value;
  38583. if (prop === 'name' || prop === 'params' || prop === 'selector') {
  38584. node.markDirty();
  38585. }
  38586. return true
  38587. },
  38588. get(node, prop) {
  38589. if (prop === 'proxyOf') {
  38590. return node
  38591. } else if (!node[prop]) {
  38592. return node[prop]
  38593. } else if (
  38594. prop === 'each' ||
  38595. (typeof prop === 'string' && prop.startsWith('walk'))
  38596. ) {
  38597. return (...args) => {
  38598. return node[prop](
  38599. ...args.map(i => {
  38600. if (typeof i === 'function') {
  38601. return (child, index) => i(child.toProxy(), index)
  38602. } else {
  38603. return i
  38604. }
  38605. })
  38606. )
  38607. }
  38608. } else if (prop === 'every' || prop === 'some') {
  38609. return cb => {
  38610. return node[prop]((child, ...other) =>
  38611. cb(child.toProxy(), ...other)
  38612. )
  38613. }
  38614. } else if (prop === 'root') {
  38615. return () => node.root().toProxy()
  38616. } else if (prop === 'nodes') {
  38617. return node.nodes.map(i => i.toProxy())
  38618. } else if (prop === 'first' || prop === 'last') {
  38619. return node[prop].toProxy()
  38620. } else {
  38621. return node[prop]
  38622. }
  38623. }
  38624. }
  38625. }
  38626. getIterator() {
  38627. if (!this.lastEach) this.lastEach = 0;
  38628. if (!this.indexes) this.indexes = {};
  38629. this.lastEach += 1;
  38630. let iterator = this.lastEach;
  38631. this.indexes[iterator] = 0;
  38632. return iterator
  38633. }
  38634. };
  38635. Container$7.registerParse = dependant => {
  38636. parse$4 = dependant;
  38637. };
  38638. Container$7.registerRule = dependant => {
  38639. Rule$4 = dependant;
  38640. };
  38641. Container$7.registerAtRule = dependant => {
  38642. AtRule$4 = dependant;
  38643. };
  38644. var container$1 = Container$7;
  38645. Container$7.default = Container$7;
  38646. /* c8 ignore start */
  38647. Container$7.rebuild = node => {
  38648. if (node.type === 'atrule') {
  38649. Object.setPrototypeOf(node, AtRule$4.prototype);
  38650. } else if (node.type === 'rule') {
  38651. Object.setPrototypeOf(node, Rule$4.prototype);
  38652. } else if (node.type === 'decl') {
  38653. Object.setPrototypeOf(node, Declaration$3.prototype);
  38654. } else if (node.type === 'comment') {
  38655. Object.setPrototypeOf(node, Comment$3.prototype);
  38656. }
  38657. node[my$1] = true;
  38658. if (node.nodes) {
  38659. node.nodes.forEach(child => {
  38660. Container$7.rebuild(child);
  38661. });
  38662. }
  38663. };
  38664. let Container$6 = container$1;
  38665. let LazyResult$4, Processor$3;
  38666. let Document$3 = class Document extends Container$6 {
  38667. constructor(defaults) {
  38668. // type needs to be passed to super, otherwise child roots won't be normalized correctly
  38669. super({ type: 'document', ...defaults });
  38670. if (!this.nodes) {
  38671. this.nodes = [];
  38672. }
  38673. }
  38674. toResult(opts = {}) {
  38675. let lazy = new LazyResult$4(new Processor$3(), this, opts);
  38676. return lazy.stringify()
  38677. }
  38678. };
  38679. Document$3.registerLazyResult = dependant => {
  38680. LazyResult$4 = dependant;
  38681. };
  38682. Document$3.registerProcessor = dependant => {
  38683. Processor$3 = dependant;
  38684. };
  38685. var document = Document$3;
  38686. Document$3.default = Document$3;
  38687. /* eslint-disable no-console */
  38688. let printed = {};
  38689. var warnOnce$2 = function warnOnce(message) {
  38690. if (printed[message]) return
  38691. printed[message] = true;
  38692. if (typeof console !== 'undefined' && console.warn) {
  38693. console.warn(message);
  38694. }
  38695. };
  38696. let Warning$2 = class Warning {
  38697. constructor(text, opts = {}) {
  38698. this.type = 'warning';
  38699. this.text = text;
  38700. if (opts.node && opts.node.source) {
  38701. let range = opts.node.rangeBy(opts);
  38702. this.line = range.start.line;
  38703. this.column = range.start.column;
  38704. this.endLine = range.end.line;
  38705. this.endColumn = range.end.column;
  38706. }
  38707. for (let opt in opts) this[opt] = opts[opt];
  38708. }
  38709. toString() {
  38710. if (this.node) {
  38711. return this.node.error(this.text, {
  38712. plugin: this.plugin,
  38713. index: this.index,
  38714. word: this.word
  38715. }).message
  38716. }
  38717. if (this.plugin) {
  38718. return this.plugin + ': ' + this.text
  38719. }
  38720. return this.text
  38721. }
  38722. };
  38723. var warning = Warning$2;
  38724. Warning$2.default = Warning$2;
  38725. let Warning$1 = warning;
  38726. let Result$3 = class Result {
  38727. constructor(processor, root, opts) {
  38728. this.processor = processor;
  38729. this.messages = [];
  38730. this.root = root;
  38731. this.opts = opts;
  38732. this.css = undefined;
  38733. this.map = undefined;
  38734. }
  38735. toString() {
  38736. return this.css
  38737. }
  38738. warn(text, opts = {}) {
  38739. if (!opts.plugin) {
  38740. if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
  38741. opts.plugin = this.lastPlugin.postcssPlugin;
  38742. }
  38743. }
  38744. let warning = new Warning$1(text, opts);
  38745. this.messages.push(warning);
  38746. return warning
  38747. }
  38748. warnings() {
  38749. return this.messages.filter(i => i.type === 'warning')
  38750. }
  38751. get content() {
  38752. return this.css
  38753. }
  38754. };
  38755. var result = Result$3;
  38756. Result$3.default = Result$3;
  38757. let Container$5 = container$1;
  38758. let AtRule$3 = class AtRule extends Container$5 {
  38759. constructor(defaults) {
  38760. super(defaults);
  38761. this.type = 'atrule';
  38762. }
  38763. append(...children) {
  38764. if (!this.proxyOf.nodes) this.nodes = [];
  38765. return super.append(...children)
  38766. }
  38767. prepend(...children) {
  38768. if (!this.proxyOf.nodes) this.nodes = [];
  38769. return super.prepend(...children)
  38770. }
  38771. };
  38772. var atRule = AtRule$3;
  38773. AtRule$3.default = AtRule$3;
  38774. Container$5.registerAtRule(AtRule$3);
  38775. let Container$4 = container$1;
  38776. let LazyResult$3, Processor$2;
  38777. let Root$5 = class Root extends Container$4 {
  38778. constructor(defaults) {
  38779. super(defaults);
  38780. this.type = 'root';
  38781. if (!this.nodes) this.nodes = [];
  38782. }
  38783. removeChild(child, ignore) {
  38784. let index = this.index(child);
  38785. if (!ignore && index === 0 && this.nodes.length > 1) {
  38786. this.nodes[1].raws.before = this.nodes[index].raws.before;
  38787. }
  38788. return super.removeChild(child)
  38789. }
  38790. normalize(child, sample, type) {
  38791. let nodes = super.normalize(child);
  38792. if (sample) {
  38793. if (type === 'prepend') {
  38794. if (this.nodes.length > 1) {
  38795. sample.raws.before = this.nodes[1].raws.before;
  38796. } else {
  38797. delete sample.raws.before;
  38798. }
  38799. } else if (this.first !== sample) {
  38800. for (let node of nodes) {
  38801. node.raws.before = sample.raws.before;
  38802. }
  38803. }
  38804. }
  38805. return nodes
  38806. }
  38807. toResult(opts = {}) {
  38808. let lazy = new LazyResult$3(new Processor$2(), this, opts);
  38809. return lazy.stringify()
  38810. }
  38811. };
  38812. Root$5.registerLazyResult = dependant => {
  38813. LazyResult$3 = dependant;
  38814. };
  38815. Root$5.registerProcessor = dependant => {
  38816. Processor$2 = dependant;
  38817. };
  38818. var root$2 = Root$5;
  38819. Root$5.default = Root$5;
  38820. let list$2 = {
  38821. split(string, separators, last) {
  38822. let array = [];
  38823. let current = '';
  38824. let split = false;
  38825. let func = 0;
  38826. let quote = false;
  38827. let escape = false;
  38828. for (let letter of string) {
  38829. if (escape) {
  38830. escape = false;
  38831. } else if (letter === '\\') {
  38832. escape = true;
  38833. } else if (quote) {
  38834. if (letter === quote) {
  38835. quote = false;
  38836. }
  38837. } else if (letter === '"' || letter === "'") {
  38838. quote = letter;
  38839. } else if (letter === '(') {
  38840. func += 1;
  38841. } else if (letter === ')') {
  38842. if (func > 0) func -= 1;
  38843. } else if (func === 0) {
  38844. if (separators.includes(letter)) split = true;
  38845. }
  38846. if (split) {
  38847. if (current !== '') array.push(current.trim());
  38848. current = '';
  38849. split = false;
  38850. } else {
  38851. current += letter;
  38852. }
  38853. }
  38854. if (last || current !== '') array.push(current.trim());
  38855. return array
  38856. },
  38857. space(string) {
  38858. let spaces = [' ', '\n', '\t'];
  38859. return list$2.split(string, spaces)
  38860. },
  38861. comma(string) {
  38862. return list$2.split(string, [','], true)
  38863. }
  38864. };
  38865. var list_1 = list$2;
  38866. list$2.default = list$2;
  38867. let Container$3 = container$1;
  38868. let list$1 = list_1;
  38869. let Rule$3 = class Rule extends Container$3 {
  38870. constructor(defaults) {
  38871. super(defaults);
  38872. this.type = 'rule';
  38873. if (!this.nodes) this.nodes = [];
  38874. }
  38875. get selectors() {
  38876. return list$1.comma(this.selector)
  38877. }
  38878. set selectors(values) {
  38879. let match = this.selector ? this.selector.match(/,\s*/) : null;
  38880. let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen');
  38881. this.selector = values.join(sep);
  38882. }
  38883. };
  38884. var rule = Rule$3;
  38885. Rule$3.default = Rule$3;
  38886. Container$3.registerRule(Rule$3);
  38887. let Declaration$2 = declaration;
  38888. let tokenizer = tokenize$1;
  38889. let Comment$2 = comment$3;
  38890. let AtRule$2 = atRule;
  38891. let Root$4 = root$2;
  38892. let Rule$2 = rule;
  38893. let Parser$1 = class Parser {
  38894. constructor(input) {
  38895. this.input = input;
  38896. this.root = new Root$4();
  38897. this.current = this.root;
  38898. this.spaces = '';
  38899. this.semicolon = false;
  38900. this.customProperty = false;
  38901. this.createTokenizer();
  38902. this.root.source = { input, start: { offset: 0, line: 1, column: 1 } };
  38903. }
  38904. createTokenizer() {
  38905. this.tokenizer = tokenizer(this.input);
  38906. }
  38907. parse() {
  38908. let token;
  38909. while (!this.tokenizer.endOfFile()) {
  38910. token = this.tokenizer.nextToken();
  38911. switch (token[0]) {
  38912. case 'space':
  38913. this.spaces += token[1];
  38914. break
  38915. case ';':
  38916. this.freeSemicolon(token);
  38917. break
  38918. case '}':
  38919. this.end(token);
  38920. break
  38921. case 'comment':
  38922. this.comment(token);
  38923. break
  38924. case 'at-word':
  38925. this.atrule(token);
  38926. break
  38927. case '{':
  38928. this.emptyRule(token);
  38929. break
  38930. default:
  38931. this.other(token);
  38932. break
  38933. }
  38934. }
  38935. this.endFile();
  38936. }
  38937. comment(token) {
  38938. let node = new Comment$2();
  38939. this.init(node, token[2]);
  38940. node.source.end = this.getPosition(token[3] || token[2]);
  38941. let text = token[1].slice(2, -2);
  38942. if (/^\s*$/.test(text)) {
  38943. node.text = '';
  38944. node.raws.left = text;
  38945. node.raws.right = '';
  38946. } else {
  38947. let match = text.match(/^(\s*)([^]*\S)(\s*)$/);
  38948. node.text = match[2];
  38949. node.raws.left = match[1];
  38950. node.raws.right = match[3];
  38951. }
  38952. }
  38953. emptyRule(token) {
  38954. let node = new Rule$2();
  38955. this.init(node, token[2]);
  38956. node.selector = '';
  38957. node.raws.between = '';
  38958. this.current = node;
  38959. }
  38960. other(start) {
  38961. let end = false;
  38962. let type = null;
  38963. let colon = false;
  38964. let bracket = null;
  38965. let brackets = [];
  38966. let customProperty = start[1].startsWith('--');
  38967. let tokens = [];
  38968. let token = start;
  38969. while (token) {
  38970. type = token[0];
  38971. tokens.push(token);
  38972. if (type === '(' || type === '[') {
  38973. if (!bracket) bracket = token;
  38974. brackets.push(type === '(' ? ')' : ']');
  38975. } else if (customProperty && colon && type === '{') {
  38976. if (!bracket) bracket = token;
  38977. brackets.push('}');
  38978. } else if (brackets.length === 0) {
  38979. if (type === ';') {
  38980. if (colon) {
  38981. this.decl(tokens, customProperty);
  38982. return
  38983. } else {
  38984. break
  38985. }
  38986. } else if (type === '{') {
  38987. this.rule(tokens);
  38988. return
  38989. } else if (type === '}') {
  38990. this.tokenizer.back(tokens.pop());
  38991. end = true;
  38992. break
  38993. } else if (type === ':') {
  38994. colon = true;
  38995. }
  38996. } else if (type === brackets[brackets.length - 1]) {
  38997. brackets.pop();
  38998. if (brackets.length === 0) bracket = null;
  38999. }
  39000. token = this.tokenizer.nextToken();
  39001. }
  39002. if (this.tokenizer.endOfFile()) end = true;
  39003. if (brackets.length > 0) this.unclosedBracket(bracket);
  39004. if (end && colon) {
  39005. while (tokens.length) {
  39006. token = tokens[tokens.length - 1][0];
  39007. if (token !== 'space' && token !== 'comment') break
  39008. this.tokenizer.back(tokens.pop());
  39009. }
  39010. this.decl(tokens, customProperty);
  39011. } else {
  39012. this.unknownWord(tokens);
  39013. }
  39014. }
  39015. rule(tokens) {
  39016. tokens.pop();
  39017. let node = new Rule$2();
  39018. this.init(node, tokens[0][2]);
  39019. node.raws.between = this.spacesAndCommentsFromEnd(tokens);
  39020. this.raw(node, 'selector', tokens);
  39021. this.current = node;
  39022. }
  39023. decl(tokens, customProperty) {
  39024. let node = new Declaration$2();
  39025. this.init(node, tokens[0][2]);
  39026. let last = tokens[tokens.length - 1];
  39027. if (last[0] === ';') {
  39028. this.semicolon = true;
  39029. tokens.pop();
  39030. }
  39031. node.source.end = this.getPosition(last[3] || last[2]);
  39032. while (tokens[0][0] !== 'word') {
  39033. if (tokens.length === 1) this.unknownWord(tokens);
  39034. node.raws.before += tokens.shift()[1];
  39035. }
  39036. node.source.start = this.getPosition(tokens[0][2]);
  39037. node.prop = '';
  39038. while (tokens.length) {
  39039. let type = tokens[0][0];
  39040. if (type === ':' || type === 'space' || type === 'comment') {
  39041. break
  39042. }
  39043. node.prop += tokens.shift()[1];
  39044. }
  39045. node.raws.between = '';
  39046. let token;
  39047. while (tokens.length) {
  39048. token = tokens.shift();
  39049. if (token[0] === ':') {
  39050. node.raws.between += token[1];
  39051. break
  39052. } else {
  39053. if (token[0] === 'word' && /\w/.test(token[1])) {
  39054. this.unknownWord([token]);
  39055. }
  39056. node.raws.between += token[1];
  39057. }
  39058. }
  39059. if (node.prop[0] === '_' || node.prop[0] === '*') {
  39060. node.raws.before += node.prop[0];
  39061. node.prop = node.prop.slice(1);
  39062. }
  39063. let firstSpaces = this.spacesAndCommentsFromStart(tokens);
  39064. this.precheckMissedSemicolon(tokens);
  39065. for (let i = tokens.length - 1; i >= 0; i--) {
  39066. token = tokens[i];
  39067. if (token[1].toLowerCase() === '!important') {
  39068. node.important = true;
  39069. let string = this.stringFrom(tokens, i);
  39070. string = this.spacesFromEnd(tokens) + string;
  39071. if (string !== ' !important') node.raws.important = string;
  39072. break
  39073. } else if (token[1].toLowerCase() === 'important') {
  39074. let cache = tokens.slice(0);
  39075. let str = '';
  39076. for (let j = i; j > 0; j--) {
  39077. let type = cache[j][0];
  39078. if (str.trim().indexOf('!') === 0 && type !== 'space') {
  39079. break
  39080. }
  39081. str = cache.pop()[1] + str;
  39082. }
  39083. if (str.trim().indexOf('!') === 0) {
  39084. node.important = true;
  39085. node.raws.important = str;
  39086. tokens = cache;
  39087. }
  39088. }
  39089. if (token[0] !== 'space' && token[0] !== 'comment') {
  39090. break
  39091. }
  39092. }
  39093. let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment');
  39094. this.raw(node, 'value', tokens);
  39095. if (hasWord) {
  39096. node.raws.between += firstSpaces;
  39097. } else {
  39098. node.value = firstSpaces + node.value;
  39099. }
  39100. if (node.value.includes(':') && !customProperty) {
  39101. this.checkMissedSemicolon(tokens);
  39102. }
  39103. }
  39104. atrule(token) {
  39105. let node = new AtRule$2();
  39106. node.name = token[1].slice(1);
  39107. if (node.name === '') {
  39108. this.unnamedAtrule(node, token);
  39109. }
  39110. this.init(node, token[2]);
  39111. let type;
  39112. let prev;
  39113. let shift;
  39114. let last = false;
  39115. let open = false;
  39116. let params = [];
  39117. let brackets = [];
  39118. while (!this.tokenizer.endOfFile()) {
  39119. token = this.tokenizer.nextToken();
  39120. type = token[0];
  39121. if (type === '(' || type === '[') {
  39122. brackets.push(type === '(' ? ')' : ']');
  39123. } else if (type === '{' && brackets.length > 0) {
  39124. brackets.push('}');
  39125. } else if (type === brackets[brackets.length - 1]) {
  39126. brackets.pop();
  39127. }
  39128. if (brackets.length === 0) {
  39129. if (type === ';') {
  39130. node.source.end = this.getPosition(token[2]);
  39131. this.semicolon = true;
  39132. break
  39133. } else if (type === '{') {
  39134. open = true;
  39135. break
  39136. } else if (type === '}') {
  39137. if (params.length > 0) {
  39138. shift = params.length - 1;
  39139. prev = params[shift];
  39140. while (prev && prev[0] === 'space') {
  39141. prev = params[--shift];
  39142. }
  39143. if (prev) {
  39144. node.source.end = this.getPosition(prev[3] || prev[2]);
  39145. }
  39146. }
  39147. this.end(token);
  39148. break
  39149. } else {
  39150. params.push(token);
  39151. }
  39152. } else {
  39153. params.push(token);
  39154. }
  39155. if (this.tokenizer.endOfFile()) {
  39156. last = true;
  39157. break
  39158. }
  39159. }
  39160. node.raws.between = this.spacesAndCommentsFromEnd(params);
  39161. if (params.length) {
  39162. node.raws.afterName = this.spacesAndCommentsFromStart(params);
  39163. this.raw(node, 'params', params);
  39164. if (last) {
  39165. token = params[params.length - 1];
  39166. node.source.end = this.getPosition(token[3] || token[2]);
  39167. this.spaces = node.raws.between;
  39168. node.raws.between = '';
  39169. }
  39170. } else {
  39171. node.raws.afterName = '';
  39172. node.params = '';
  39173. }
  39174. if (open) {
  39175. node.nodes = [];
  39176. this.current = node;
  39177. }
  39178. }
  39179. end(token) {
  39180. if (this.current.nodes && this.current.nodes.length) {
  39181. this.current.raws.semicolon = this.semicolon;
  39182. }
  39183. this.semicolon = false;
  39184. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  39185. this.spaces = '';
  39186. if (this.current.parent) {
  39187. this.current.source.end = this.getPosition(token[2]);
  39188. this.current = this.current.parent;
  39189. } else {
  39190. this.unexpectedClose(token);
  39191. }
  39192. }
  39193. endFile() {
  39194. if (this.current.parent) this.unclosedBlock();
  39195. if (this.current.nodes && this.current.nodes.length) {
  39196. this.current.raws.semicolon = this.semicolon;
  39197. }
  39198. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  39199. }
  39200. freeSemicolon(token) {
  39201. this.spaces += token[1];
  39202. if (this.current.nodes) {
  39203. let prev = this.current.nodes[this.current.nodes.length - 1];
  39204. if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) {
  39205. prev.raws.ownSemicolon = this.spaces;
  39206. this.spaces = '';
  39207. }
  39208. }
  39209. }
  39210. // Helpers
  39211. getPosition(offset) {
  39212. let pos = this.input.fromOffset(offset);
  39213. return {
  39214. offset,
  39215. line: pos.line,
  39216. column: pos.col
  39217. }
  39218. }
  39219. init(node, offset) {
  39220. this.current.push(node);
  39221. node.source = {
  39222. start: this.getPosition(offset),
  39223. input: this.input
  39224. };
  39225. node.raws.before = this.spaces;
  39226. this.spaces = '';
  39227. if (node.type !== 'comment') this.semicolon = false;
  39228. }
  39229. raw(node, prop, tokens) {
  39230. let token, type;
  39231. let length = tokens.length;
  39232. let value = '';
  39233. let clean = true;
  39234. let next, prev;
  39235. let pattern = /^([#.|])?(\w)+/i;
  39236. for (let i = 0; i < length; i += 1) {
  39237. token = tokens[i];
  39238. type = token[0];
  39239. if (type === 'comment' && node.type === 'rule') {
  39240. prev = tokens[i - 1];
  39241. next = tokens[i + 1];
  39242. if (
  39243. prev[0] !== 'space' &&
  39244. next[0] !== 'space' &&
  39245. pattern.test(prev[1]) &&
  39246. pattern.test(next[1])
  39247. ) {
  39248. value += token[1];
  39249. } else {
  39250. clean = false;
  39251. }
  39252. continue
  39253. }
  39254. if (type === 'comment' || (type === 'space' && i === length - 1)) {
  39255. clean = false;
  39256. } else {
  39257. value += token[1];
  39258. }
  39259. }
  39260. if (!clean) {
  39261. let raw = tokens.reduce((all, i) => all + i[1], '');
  39262. node.raws[prop] = { value, raw };
  39263. }
  39264. node[prop] = value;
  39265. }
  39266. spacesAndCommentsFromEnd(tokens) {
  39267. let lastTokenType;
  39268. let spaces = '';
  39269. while (tokens.length) {
  39270. lastTokenType = tokens[tokens.length - 1][0];
  39271. if (lastTokenType !== 'space' && lastTokenType !== 'comment') break
  39272. spaces = tokens.pop()[1] + spaces;
  39273. }
  39274. return spaces
  39275. }
  39276. spacesAndCommentsFromStart(tokens) {
  39277. let next;
  39278. let spaces = '';
  39279. while (tokens.length) {
  39280. next = tokens[0][0];
  39281. if (next !== 'space' && next !== 'comment') break
  39282. spaces += tokens.shift()[1];
  39283. }
  39284. return spaces
  39285. }
  39286. spacesFromEnd(tokens) {
  39287. let lastTokenType;
  39288. let spaces = '';
  39289. while (tokens.length) {
  39290. lastTokenType = tokens[tokens.length - 1][0];
  39291. if (lastTokenType !== 'space') break
  39292. spaces = tokens.pop()[1] + spaces;
  39293. }
  39294. return spaces
  39295. }
  39296. stringFrom(tokens, from) {
  39297. let result = '';
  39298. for (let i = from; i < tokens.length; i++) {
  39299. result += tokens[i][1];
  39300. }
  39301. tokens.splice(from, tokens.length - from);
  39302. return result
  39303. }
  39304. colon(tokens) {
  39305. let brackets = 0;
  39306. let token, type, prev;
  39307. for (let [i, element] of tokens.entries()) {
  39308. token = element;
  39309. type = token[0];
  39310. if (type === '(') {
  39311. brackets += 1;
  39312. }
  39313. if (type === ')') {
  39314. brackets -= 1;
  39315. }
  39316. if (brackets === 0 && type === ':') {
  39317. if (!prev) {
  39318. this.doubleColon(token);
  39319. } else if (prev[0] === 'word' && prev[1] === 'progid') {
  39320. continue
  39321. } else {
  39322. return i
  39323. }
  39324. }
  39325. prev = token;
  39326. }
  39327. return false
  39328. }
  39329. // Errors
  39330. unclosedBracket(bracket) {
  39331. throw this.input.error(
  39332. 'Unclosed bracket',
  39333. { offset: bracket[2] },
  39334. { offset: bracket[2] + 1 }
  39335. )
  39336. }
  39337. unknownWord(tokens) {
  39338. throw this.input.error(
  39339. 'Unknown word',
  39340. { offset: tokens[0][2] },
  39341. { offset: tokens[0][2] + tokens[0][1].length }
  39342. )
  39343. }
  39344. unexpectedClose(token) {
  39345. throw this.input.error(
  39346. 'Unexpected }',
  39347. { offset: token[2] },
  39348. { offset: token[2] + 1 }
  39349. )
  39350. }
  39351. unclosedBlock() {
  39352. let pos = this.current.source.start;
  39353. throw this.input.error('Unclosed block', pos.line, pos.column)
  39354. }
  39355. doubleColon(token) {
  39356. throw this.input.error(
  39357. 'Double colon',
  39358. { offset: token[2] },
  39359. { offset: token[2] + token[1].length }
  39360. )
  39361. }
  39362. unnamedAtrule(node, token) {
  39363. throw this.input.error(
  39364. 'At-rule without name',
  39365. { offset: token[2] },
  39366. { offset: token[2] + token[1].length }
  39367. )
  39368. }
  39369. precheckMissedSemicolon(/* tokens */) {
  39370. // Hook for Safe Parser
  39371. }
  39372. checkMissedSemicolon(tokens) {
  39373. let colon = this.colon(tokens);
  39374. if (colon === false) return
  39375. let founded = 0;
  39376. let token;
  39377. for (let j = colon - 1; j >= 0; j--) {
  39378. token = tokens[j];
  39379. if (token[0] !== 'space') {
  39380. founded += 1;
  39381. if (founded === 2) break
  39382. }
  39383. }
  39384. // If the token is a word, e.g. `!important`, `red` or any other valid property's value.
  39385. // Then we need to return the colon after that word token. [3] is the "end" colon of that word.
  39386. // And because we need it after that one we do +1 to get the next one.
  39387. throw this.input.error(
  39388. 'Missed semicolon',
  39389. token[0] === 'word' ? token[3] + 1 : token[2]
  39390. )
  39391. }
  39392. };
  39393. var parser$1 = Parser$1;
  39394. let Container$2 = container$1;
  39395. let Parser = parser$1;
  39396. let Input$2 = input;
  39397. function parse$3(css, opts) {
  39398. let input = new Input$2(css, opts);
  39399. let parser = new Parser(input);
  39400. try {
  39401. parser.parse();
  39402. } catch (e) {
  39403. if (browser$1.env.NODE_ENV !== 'production') {
  39404. if (e.name === 'CssSyntaxError' && opts && opts.from) {
  39405. if (/\.scss$/i.test(opts.from)) {
  39406. e.message +=
  39407. '\nYou tried to parse SCSS with ' +
  39408. 'the standard CSS parser; ' +
  39409. 'try again with the postcss-scss parser';
  39410. } else if (/\.sass/i.test(opts.from)) {
  39411. e.message +=
  39412. '\nYou tried to parse Sass with ' +
  39413. 'the standard CSS parser; ' +
  39414. 'try again with the postcss-sass parser';
  39415. } else if (/\.less$/i.test(opts.from)) {
  39416. e.message +=
  39417. '\nYou tried to parse Less with ' +
  39418. 'the standard CSS parser; ' +
  39419. 'try again with the postcss-less parser';
  39420. }
  39421. }
  39422. }
  39423. throw e
  39424. }
  39425. return parser.root
  39426. }
  39427. var parse_1 = parse$3;
  39428. parse$3.default = parse$3;
  39429. Container$2.registerParse(parse$3);
  39430. let { isClean, my } = symbols;
  39431. let MapGenerator$1 = mapGenerator;
  39432. let stringify$2 = stringify_1;
  39433. let Container$1 = container$1;
  39434. let Document$2 = document;
  39435. let warnOnce$1 = warnOnce$2;
  39436. let Result$2 = result;
  39437. let parse$2 = parse_1;
  39438. let Root$3 = root$2;
  39439. const TYPE_TO_CLASS_NAME = {
  39440. document: 'Document',
  39441. root: 'Root',
  39442. atrule: 'AtRule',
  39443. rule: 'Rule',
  39444. decl: 'Declaration',
  39445. comment: 'Comment'
  39446. };
  39447. const PLUGIN_PROPS = {
  39448. postcssPlugin: true,
  39449. prepare: true,
  39450. Once: true,
  39451. Document: true,
  39452. Root: true,
  39453. Declaration: true,
  39454. Rule: true,
  39455. AtRule: true,
  39456. Comment: true,
  39457. DeclarationExit: true,
  39458. RuleExit: true,
  39459. AtRuleExit: true,
  39460. CommentExit: true,
  39461. RootExit: true,
  39462. DocumentExit: true,
  39463. OnceExit: true
  39464. };
  39465. const NOT_VISITORS = {
  39466. postcssPlugin: true,
  39467. prepare: true,
  39468. Once: true
  39469. };
  39470. const CHILDREN = 0;
  39471. function isPromise(obj) {
  39472. return typeof obj === 'object' && typeof obj.then === 'function'
  39473. }
  39474. function getEvents(node) {
  39475. let key = false;
  39476. let type = TYPE_TO_CLASS_NAME[node.type];
  39477. if (node.type === 'decl') {
  39478. key = node.prop.toLowerCase();
  39479. } else if (node.type === 'atrule') {
  39480. key = node.name.toLowerCase();
  39481. }
  39482. if (key && node.append) {
  39483. return [
  39484. type,
  39485. type + '-' + key,
  39486. CHILDREN,
  39487. type + 'Exit',
  39488. type + 'Exit-' + key
  39489. ]
  39490. } else if (key) {
  39491. return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key]
  39492. } else if (node.append) {
  39493. return [type, CHILDREN, type + 'Exit']
  39494. } else {
  39495. return [type, type + 'Exit']
  39496. }
  39497. }
  39498. function toStack(node) {
  39499. let events;
  39500. if (node.type === 'document') {
  39501. events = ['Document', CHILDREN, 'DocumentExit'];
  39502. } else if (node.type === 'root') {
  39503. events = ['Root', CHILDREN, 'RootExit'];
  39504. } else {
  39505. events = getEvents(node);
  39506. }
  39507. return {
  39508. node,
  39509. events,
  39510. eventIndex: 0,
  39511. visitors: [],
  39512. visitorIndex: 0,
  39513. iterator: 0
  39514. }
  39515. }
  39516. function cleanMarks(node) {
  39517. node[isClean] = false;
  39518. if (node.nodes) node.nodes.forEach(i => cleanMarks(i));
  39519. return node
  39520. }
  39521. let postcss$2 = {};
  39522. let LazyResult$2 = class LazyResult {
  39523. constructor(processor, css, opts) {
  39524. this.stringified = false;
  39525. this.processed = false;
  39526. let root;
  39527. if (
  39528. typeof css === 'object' &&
  39529. css !== null &&
  39530. (css.type === 'root' || css.type === 'document')
  39531. ) {
  39532. root = cleanMarks(css);
  39533. } else if (css instanceof LazyResult$2 || css instanceof Result$2) {
  39534. root = cleanMarks(css.root);
  39535. if (css.map) {
  39536. if (typeof opts.map === 'undefined') opts.map = {};
  39537. if (!opts.map.inline) opts.map.inline = false;
  39538. opts.map.prev = css.map;
  39539. }
  39540. } else {
  39541. let parser = parse$2;
  39542. if (opts.syntax) parser = opts.syntax.parse;
  39543. if (opts.parser) parser = opts.parser;
  39544. if (parser.parse) parser = parser.parse;
  39545. try {
  39546. root = parser(css, opts);
  39547. } catch (error) {
  39548. this.processed = true;
  39549. this.error = error;
  39550. }
  39551. if (root && !root[my]) {
  39552. /* c8 ignore next 2 */
  39553. Container$1.rebuild(root);
  39554. }
  39555. }
  39556. this.result = new Result$2(processor, root, opts);
  39557. this.helpers = { ...postcss$2, result: this.result, postcss: postcss$2 };
  39558. this.plugins = this.processor.plugins.map(plugin => {
  39559. if (typeof plugin === 'object' && plugin.prepare) {
  39560. return { ...plugin, ...plugin.prepare(this.result) }
  39561. } else {
  39562. return plugin
  39563. }
  39564. });
  39565. }
  39566. get [Symbol.toStringTag]() {
  39567. return 'LazyResult'
  39568. }
  39569. get processor() {
  39570. return this.result.processor
  39571. }
  39572. get opts() {
  39573. return this.result.opts
  39574. }
  39575. get css() {
  39576. return this.stringify().css
  39577. }
  39578. get content() {
  39579. return this.stringify().content
  39580. }
  39581. get map() {
  39582. return this.stringify().map
  39583. }
  39584. get root() {
  39585. return this.sync().root
  39586. }
  39587. get messages() {
  39588. return this.sync().messages
  39589. }
  39590. warnings() {
  39591. return this.sync().warnings()
  39592. }
  39593. toString() {
  39594. return this.css
  39595. }
  39596. then(onFulfilled, onRejected) {
  39597. if (browser$1.env.NODE_ENV !== 'production') {
  39598. if (!('from' in this.opts)) {
  39599. warnOnce$1(
  39600. 'Without `from` option PostCSS could generate wrong source map ' +
  39601. 'and will not find Browserslist config. Set it to CSS file path ' +
  39602. 'or to `undefined` to prevent this warning.'
  39603. );
  39604. }
  39605. }
  39606. return this.async().then(onFulfilled, onRejected)
  39607. }
  39608. catch(onRejected) {
  39609. return this.async().catch(onRejected)
  39610. }
  39611. finally(onFinally) {
  39612. return this.async().then(onFinally, onFinally)
  39613. }
  39614. async() {
  39615. if (this.error) return Promise.reject(this.error)
  39616. if (this.processed) return Promise.resolve(this.result)
  39617. if (!this.processing) {
  39618. this.processing = this.runAsync();
  39619. }
  39620. return this.processing
  39621. }
  39622. sync() {
  39623. if (this.error) throw this.error
  39624. if (this.processed) return this.result
  39625. this.processed = true;
  39626. if (this.processing) {
  39627. throw this.getAsyncError()
  39628. }
  39629. for (let plugin of this.plugins) {
  39630. let promise = this.runOnRoot(plugin);
  39631. if (isPromise(promise)) {
  39632. throw this.getAsyncError()
  39633. }
  39634. }
  39635. this.prepareVisitors();
  39636. if (this.hasListener) {
  39637. let root = this.result.root;
  39638. while (!root[isClean]) {
  39639. root[isClean] = true;
  39640. this.walkSync(root);
  39641. }
  39642. if (this.listeners.OnceExit) {
  39643. if (root.type === 'document') {
  39644. for (let subRoot of root.nodes) {
  39645. this.visitSync(this.listeners.OnceExit, subRoot);
  39646. }
  39647. } else {
  39648. this.visitSync(this.listeners.OnceExit, root);
  39649. }
  39650. }
  39651. }
  39652. return this.result
  39653. }
  39654. stringify() {
  39655. if (this.error) throw this.error
  39656. if (this.stringified) return this.result
  39657. this.stringified = true;
  39658. this.sync();
  39659. let opts = this.result.opts;
  39660. let str = stringify$2;
  39661. if (opts.syntax) str = opts.syntax.stringify;
  39662. if (opts.stringifier) str = opts.stringifier;
  39663. if (str.stringify) str = str.stringify;
  39664. let map = new MapGenerator$1(str, this.result.root, this.result.opts);
  39665. let data = map.generate();
  39666. this.result.css = data[0];
  39667. this.result.map = data[1];
  39668. return this.result
  39669. }
  39670. walkSync(node) {
  39671. node[isClean] = true;
  39672. let events = getEvents(node);
  39673. for (let event of events) {
  39674. if (event === CHILDREN) {
  39675. if (node.nodes) {
  39676. node.each(child => {
  39677. if (!child[isClean]) this.walkSync(child);
  39678. });
  39679. }
  39680. } else {
  39681. let visitors = this.listeners[event];
  39682. if (visitors) {
  39683. if (this.visitSync(visitors, node.toProxy())) return
  39684. }
  39685. }
  39686. }
  39687. }
  39688. visitSync(visitors, node) {
  39689. for (let [plugin, visitor] of visitors) {
  39690. this.result.lastPlugin = plugin;
  39691. let promise;
  39692. try {
  39693. promise = visitor(node, this.helpers);
  39694. } catch (e) {
  39695. throw this.handleError(e, node.proxyOf)
  39696. }
  39697. if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
  39698. return true
  39699. }
  39700. if (isPromise(promise)) {
  39701. throw this.getAsyncError()
  39702. }
  39703. }
  39704. }
  39705. runOnRoot(plugin) {
  39706. this.result.lastPlugin = plugin;
  39707. try {
  39708. if (typeof plugin === 'object' && plugin.Once) {
  39709. if (this.result.root.type === 'document') {
  39710. let roots = this.result.root.nodes.map(root =>
  39711. plugin.Once(root, this.helpers)
  39712. );
  39713. if (isPromise(roots[0])) {
  39714. return Promise.all(roots)
  39715. }
  39716. return roots
  39717. }
  39718. return plugin.Once(this.result.root, this.helpers)
  39719. } else if (typeof plugin === 'function') {
  39720. return plugin(this.result.root, this.result)
  39721. }
  39722. } catch (error) {
  39723. throw this.handleError(error)
  39724. }
  39725. }
  39726. getAsyncError() {
  39727. throw new Error('Use process(css).then(cb) to work with async plugins')
  39728. }
  39729. handleError(error, node) {
  39730. let plugin = this.result.lastPlugin;
  39731. try {
  39732. if (node) node.addToError(error);
  39733. this.error = error;
  39734. if (error.name === 'CssSyntaxError' && !error.plugin) {
  39735. error.plugin = plugin.postcssPlugin;
  39736. error.setMessage();
  39737. } else if (plugin.postcssVersion) {
  39738. if (browser$1.env.NODE_ENV !== 'production') {
  39739. let pluginName = plugin.postcssPlugin;
  39740. let pluginVer = plugin.postcssVersion;
  39741. let runtimeVer = this.result.processor.version;
  39742. let a = pluginVer.split('.');
  39743. let b = runtimeVer.split('.');
  39744. if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
  39745. // eslint-disable-next-line no-console
  39746. console.error(
  39747. 'Unknown error from PostCSS plugin. Your current PostCSS ' +
  39748. 'version is ' +
  39749. runtimeVer +
  39750. ', but ' +
  39751. pluginName +
  39752. ' uses ' +
  39753. pluginVer +
  39754. '. Perhaps this is the source of the error below.'
  39755. );
  39756. }
  39757. }
  39758. }
  39759. } catch (err) {
  39760. /* c8 ignore next 3 */
  39761. // eslint-disable-next-line no-console
  39762. if (console && console.error) console.error(err);
  39763. }
  39764. return error
  39765. }
  39766. async runAsync() {
  39767. this.plugin = 0;
  39768. for (let i = 0; i < this.plugins.length; i++) {
  39769. let plugin = this.plugins[i];
  39770. let promise = this.runOnRoot(plugin);
  39771. if (isPromise(promise)) {
  39772. try {
  39773. await promise;
  39774. } catch (error) {
  39775. throw this.handleError(error)
  39776. }
  39777. }
  39778. }
  39779. this.prepareVisitors();
  39780. if (this.hasListener) {
  39781. let root = this.result.root;
  39782. while (!root[isClean]) {
  39783. root[isClean] = true;
  39784. let stack = [toStack(root)];
  39785. while (stack.length > 0) {
  39786. let promise = this.visitTick(stack);
  39787. if (isPromise(promise)) {
  39788. try {
  39789. await promise;
  39790. } catch (e) {
  39791. let node = stack[stack.length - 1].node;
  39792. throw this.handleError(e, node)
  39793. }
  39794. }
  39795. }
  39796. }
  39797. if (this.listeners.OnceExit) {
  39798. for (let [plugin, visitor] of this.listeners.OnceExit) {
  39799. this.result.lastPlugin = plugin;
  39800. try {
  39801. if (root.type === 'document') {
  39802. let roots = root.nodes.map(subRoot =>
  39803. visitor(subRoot, this.helpers)
  39804. );
  39805. await Promise.all(roots);
  39806. } else {
  39807. await visitor(root, this.helpers);
  39808. }
  39809. } catch (e) {
  39810. throw this.handleError(e)
  39811. }
  39812. }
  39813. }
  39814. }
  39815. this.processed = true;
  39816. return this.stringify()
  39817. }
  39818. prepareVisitors() {
  39819. this.listeners = {};
  39820. let add = (plugin, type, cb) => {
  39821. if (!this.listeners[type]) this.listeners[type] = [];
  39822. this.listeners[type].push([plugin, cb]);
  39823. };
  39824. for (let plugin of this.plugins) {
  39825. if (typeof plugin === 'object') {
  39826. for (let event in plugin) {
  39827. if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
  39828. throw new Error(
  39829. `Unknown event ${event} in ${plugin.postcssPlugin}. ` +
  39830. `Try to update PostCSS (${this.processor.version} now).`
  39831. )
  39832. }
  39833. if (!NOT_VISITORS[event]) {
  39834. if (typeof plugin[event] === 'object') {
  39835. for (let filter in plugin[event]) {
  39836. if (filter === '*') {
  39837. add(plugin, event, plugin[event][filter]);
  39838. } else {
  39839. add(
  39840. plugin,
  39841. event + '-' + filter.toLowerCase(),
  39842. plugin[event][filter]
  39843. );
  39844. }
  39845. }
  39846. } else if (typeof plugin[event] === 'function') {
  39847. add(plugin, event, plugin[event]);
  39848. }
  39849. }
  39850. }
  39851. }
  39852. }
  39853. this.hasListener = Object.keys(this.listeners).length > 0;
  39854. }
  39855. visitTick(stack) {
  39856. let visit = stack[stack.length - 1];
  39857. let { node, visitors } = visit;
  39858. if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
  39859. stack.pop();
  39860. return
  39861. }
  39862. if (visitors.length > 0 && visit.visitorIndex < visitors.length) {
  39863. let [plugin, visitor] = visitors[visit.visitorIndex];
  39864. visit.visitorIndex += 1;
  39865. if (visit.visitorIndex === visitors.length) {
  39866. visit.visitors = [];
  39867. visit.visitorIndex = 0;
  39868. }
  39869. this.result.lastPlugin = plugin;
  39870. try {
  39871. return visitor(node.toProxy(), this.helpers)
  39872. } catch (e) {
  39873. throw this.handleError(e, node)
  39874. }
  39875. }
  39876. if (visit.iterator !== 0) {
  39877. let iterator = visit.iterator;
  39878. let child;
  39879. while ((child = node.nodes[node.indexes[iterator]])) {
  39880. node.indexes[iterator] += 1;
  39881. if (!child[isClean]) {
  39882. child[isClean] = true;
  39883. stack.push(toStack(child));
  39884. return
  39885. }
  39886. }
  39887. visit.iterator = 0;
  39888. delete node.indexes[iterator];
  39889. }
  39890. let events = visit.events;
  39891. while (visit.eventIndex < events.length) {
  39892. let event = events[visit.eventIndex];
  39893. visit.eventIndex += 1;
  39894. if (event === CHILDREN) {
  39895. if (node.nodes && node.nodes.length) {
  39896. node[isClean] = true;
  39897. visit.iterator = node.getIterator();
  39898. }
  39899. return
  39900. } else if (this.listeners[event]) {
  39901. visit.visitors = this.listeners[event];
  39902. return
  39903. }
  39904. }
  39905. stack.pop();
  39906. }
  39907. };
  39908. LazyResult$2.registerPostcss = dependant => {
  39909. postcss$2 = dependant;
  39910. };
  39911. var lazyResult = LazyResult$2;
  39912. LazyResult$2.default = LazyResult$2;
  39913. Root$3.registerLazyResult(LazyResult$2);
  39914. Document$2.registerLazyResult(LazyResult$2);
  39915. let MapGenerator = mapGenerator;
  39916. let stringify$1 = stringify_1;
  39917. let warnOnce = warnOnce$2;
  39918. let parse$1 = parse_1;
  39919. const Result$1 = result;
  39920. let NoWorkResult$1 = class NoWorkResult {
  39921. constructor(processor, css, opts) {
  39922. css = css.toString();
  39923. this.stringified = false;
  39924. this._processor = processor;
  39925. this._css = css;
  39926. this._opts = opts;
  39927. this._map = undefined;
  39928. let root;
  39929. let str = stringify$1;
  39930. this.result = new Result$1(this._processor, root, this._opts);
  39931. this.result.css = css;
  39932. let self = this;
  39933. Object.defineProperty(this.result, 'root', {
  39934. get() {
  39935. return self.root
  39936. }
  39937. });
  39938. let map = new MapGenerator(str, root, this._opts, css);
  39939. if (map.isMap()) {
  39940. let [generatedCSS, generatedMap] = map.generate();
  39941. if (generatedCSS) {
  39942. this.result.css = generatedCSS;
  39943. }
  39944. if (generatedMap) {
  39945. this.result.map = generatedMap;
  39946. }
  39947. }
  39948. }
  39949. get [Symbol.toStringTag]() {
  39950. return 'NoWorkResult'
  39951. }
  39952. get processor() {
  39953. return this.result.processor
  39954. }
  39955. get opts() {
  39956. return this.result.opts
  39957. }
  39958. get css() {
  39959. return this.result.css
  39960. }
  39961. get content() {
  39962. return this.result.css
  39963. }
  39964. get map() {
  39965. return this.result.map
  39966. }
  39967. get root() {
  39968. if (this._root) {
  39969. return this._root
  39970. }
  39971. let root;
  39972. let parser = parse$1;
  39973. try {
  39974. root = parser(this._css, this._opts);
  39975. } catch (error) {
  39976. this.error = error;
  39977. }
  39978. this._root = root;
  39979. return root
  39980. }
  39981. get messages() {
  39982. return []
  39983. }
  39984. warnings() {
  39985. return []
  39986. }
  39987. toString() {
  39988. return this._css
  39989. }
  39990. then(onFulfilled, onRejected) {
  39991. if (browser$1.env.NODE_ENV !== 'production') {
  39992. if (!('from' in this._opts)) {
  39993. warnOnce(
  39994. 'Without `from` option PostCSS could generate wrong source map ' +
  39995. 'and will not find Browserslist config. Set it to CSS file path ' +
  39996. 'or to `undefined` to prevent this warning.'
  39997. );
  39998. }
  39999. }
  40000. return this.async().then(onFulfilled, onRejected)
  40001. }
  40002. catch(onRejected) {
  40003. return this.async().catch(onRejected)
  40004. }
  40005. finally(onFinally) {
  40006. return this.async().then(onFinally, onFinally)
  40007. }
  40008. async() {
  40009. if (this.error) return Promise.reject(this.error)
  40010. return Promise.resolve(this.result)
  40011. }
  40012. sync() {
  40013. if (this.error) throw this.error
  40014. return this.result
  40015. }
  40016. };
  40017. var noWorkResult = NoWorkResult$1;
  40018. NoWorkResult$1.default = NoWorkResult$1;
  40019. let NoWorkResult = noWorkResult;
  40020. let LazyResult$1 = lazyResult;
  40021. let Document$1 = document;
  40022. let Root$2 = root$2;
  40023. let Processor$1 = class Processor {
  40024. constructor(plugins = []) {
  40025. this.version = '8.4.4';
  40026. this.plugins = this.normalize(plugins);
  40027. }
  40028. use(plugin) {
  40029. this.plugins = this.plugins.concat(this.normalize([plugin]));
  40030. return this
  40031. }
  40032. process(css, opts = {}) {
  40033. if (
  40034. this.plugins.length === 0 &&
  40035. typeof opts.parser === 'undefined' &&
  40036. typeof opts.stringifier === 'undefined' &&
  40037. typeof opts.syntax === 'undefined'
  40038. ) {
  40039. return new NoWorkResult(this, css, opts)
  40040. } else {
  40041. return new LazyResult$1(this, css, opts)
  40042. }
  40043. }
  40044. normalize(plugins) {
  40045. let normalized = [];
  40046. for (let i of plugins) {
  40047. if (i.postcss === true) {
  40048. i = i();
  40049. } else if (i.postcss) {
  40050. i = i.postcss;
  40051. }
  40052. if (typeof i === 'object' && Array.isArray(i.plugins)) {
  40053. normalized = normalized.concat(i.plugins);
  40054. } else if (typeof i === 'object' && i.postcssPlugin) {
  40055. normalized.push(i);
  40056. } else if (typeof i === 'function') {
  40057. normalized.push(i);
  40058. } else if (typeof i === 'object' && (i.parse || i.stringify)) {
  40059. if (browser$1.env.NODE_ENV !== 'production') {
  40060. throw new Error(
  40061. 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' +
  40062. 'one of the syntax/parser/stringifier options as outlined ' +
  40063. 'in your PostCSS runner documentation.'
  40064. )
  40065. }
  40066. } else {
  40067. throw new Error(i + ' is not a PostCSS plugin')
  40068. }
  40069. }
  40070. return normalized
  40071. }
  40072. };
  40073. var processor$1 = Processor$1;
  40074. Processor$1.default = Processor$1;
  40075. Root$2.registerProcessor(Processor$1);
  40076. Document$1.registerProcessor(Processor$1);
  40077. let Declaration$1 = declaration;
  40078. let PreviousMap = previousMap;
  40079. let Comment$1 = comment$3;
  40080. let AtRule$1 = atRule;
  40081. let Input$1 = input;
  40082. let Root$1 = root$2;
  40083. let Rule$1 = rule;
  40084. function fromJSON$1(json, inputs) {
  40085. if (Array.isArray(json)) return json.map(n => fromJSON$1(n))
  40086. let { inputs: ownInputs, ...defaults } = json;
  40087. if (ownInputs) {
  40088. inputs = [];
  40089. for (let input of ownInputs) {
  40090. let inputHydrated = { ...input, __proto__: Input$1.prototype };
  40091. if (inputHydrated.map) {
  40092. inputHydrated.map = {
  40093. ...inputHydrated.map,
  40094. __proto__: PreviousMap.prototype
  40095. };
  40096. }
  40097. inputs.push(inputHydrated);
  40098. }
  40099. }
  40100. if (defaults.nodes) {
  40101. defaults.nodes = json.nodes.map(n => fromJSON$1(n, inputs));
  40102. }
  40103. if (defaults.source) {
  40104. let { inputId, ...source } = defaults.source;
  40105. defaults.source = source;
  40106. if (inputId != null) {
  40107. defaults.source.input = inputs[inputId];
  40108. }
  40109. }
  40110. if (defaults.type === 'root') {
  40111. return new Root$1(defaults)
  40112. } else if (defaults.type === 'decl') {
  40113. return new Declaration$1(defaults)
  40114. } else if (defaults.type === 'rule') {
  40115. return new Rule$1(defaults)
  40116. } else if (defaults.type === 'comment') {
  40117. return new Comment$1(defaults)
  40118. } else if (defaults.type === 'atrule') {
  40119. return new AtRule$1(defaults)
  40120. } else {
  40121. throw new Error('Unknown node type: ' + json.type)
  40122. }
  40123. }
  40124. var fromJSON_1 = fromJSON$1;
  40125. fromJSON$1.default = fromJSON$1;
  40126. let CssSyntaxError = cssSyntaxError;
  40127. let Declaration = declaration;
  40128. let LazyResult = lazyResult;
  40129. let Container = container$1;
  40130. let Processor = processor$1;
  40131. let stringify = stringify_1;
  40132. let fromJSON = fromJSON_1;
  40133. let Document = document;
  40134. let Warning = warning;
  40135. let Comment = comment$3;
  40136. let AtRule = atRule;
  40137. let Result = result;
  40138. let Input = input;
  40139. let parse = parse_1;
  40140. let list = list_1;
  40141. let Rule = rule;
  40142. let Root = root$2;
  40143. let Node = node$2;
  40144. function postcss(...plugins) {
  40145. if (plugins.length === 1 && Array.isArray(plugins[0])) {
  40146. plugins = plugins[0];
  40147. }
  40148. return new Processor(plugins)
  40149. }
  40150. postcss.plugin = function plugin(name, initializer) {
  40151. // eslint-disable-next-line no-console
  40152. if (console && console.warn) {
  40153. // eslint-disable-next-line no-console
  40154. console.warn(
  40155. name +
  40156. ': postcss.plugin was deprecated. Migration guide:\n' +
  40157. 'https://evilmartians.com/chronicles/postcss-8-plugin-migration'
  40158. );
  40159. if (browser$1.env.LANG && browser$1.env.LANG.startsWith('cn')) {
  40160. /* c8 ignore next 7 */
  40161. // eslint-disable-next-line no-console
  40162. console.warn(
  40163. name +
  40164. ': 里面 postcss.plugin 被弃用. 迁移指南:\n' +
  40165. 'https://www.w3ctech.com/topic/2226'
  40166. );
  40167. }
  40168. }
  40169. function creator(...args) {
  40170. let transformer = initializer(...args);
  40171. transformer.postcssPlugin = name;
  40172. transformer.postcssVersion = new Processor().version;
  40173. return transformer
  40174. }
  40175. let cache;
  40176. Object.defineProperty(creator, 'postcss', {
  40177. get() {
  40178. if (!cache) cache = creator();
  40179. return cache
  40180. }
  40181. });
  40182. creator.process = function (css, processOpts, pluginOpts) {
  40183. return postcss([creator(pluginOpts)]).process(css, processOpts)
  40184. };
  40185. return creator
  40186. };
  40187. postcss.stringify = stringify;
  40188. postcss.parse = parse;
  40189. postcss.fromJSON = fromJSON;
  40190. postcss.list = list;
  40191. postcss.comment = defaults => new Comment(defaults);
  40192. postcss.atRule = defaults => new AtRule(defaults);
  40193. postcss.decl = defaults => new Declaration(defaults);
  40194. postcss.rule = defaults => new Rule(defaults);
  40195. postcss.root = defaults => new Root(defaults);
  40196. postcss.document = defaults => new Document(defaults);
  40197. postcss.CssSyntaxError = CssSyntaxError;
  40198. postcss.Declaration = Declaration;
  40199. postcss.Container = Container;
  40200. postcss.Processor = Processor;
  40201. postcss.Document = Document;
  40202. postcss.Comment = Comment;
  40203. postcss.Warning = Warning;
  40204. postcss.AtRule = AtRule;
  40205. postcss.Result = Result;
  40206. postcss.Input = Input;
  40207. postcss.Rule = Rule;
  40208. postcss.Root = Root;
  40209. postcss.Node = Node;
  40210. LazyResult.registerPostcss(postcss);
  40211. var postcss_1 = postcss;
  40212. postcss.default = postcss;
  40213. var postcss$1 = postcss_1;
  40214. postcss$1.stringify;
  40215. postcss$1.fromJSON;
  40216. postcss$1.plugin;
  40217. postcss$1.parse;
  40218. postcss$1.list;
  40219. postcss$1.document;
  40220. postcss$1.comment;
  40221. postcss$1.atRule;
  40222. postcss$1.rule;
  40223. postcss$1.decl;
  40224. postcss$1.root;
  40225. postcss$1.CssSyntaxError;
  40226. postcss$1.Declaration;
  40227. postcss$1.Container;
  40228. postcss$1.Processor;
  40229. postcss$1.Document;
  40230. postcss$1.Comment;
  40231. postcss$1.Warning;
  40232. postcss$1.AtRule;
  40233. postcss$1.Result;
  40234. postcss$1.Input;
  40235. postcss$1.Rule;
  40236. postcss$1.Root;
  40237. postcss$1.Node;
  40238. const trimPlugin = () => {
  40239. return {
  40240. postcssPlugin: 'vue-sfc-trim',
  40241. Once(root) {
  40242. root.walk(({ type, raws }) => {
  40243. if (type === 'rule' || type === 'atrule') {
  40244. if (raws.before)
  40245. raws.before = '\n';
  40246. if ('after' in raws && raws.after)
  40247. raws.after = '\n';
  40248. }
  40249. });
  40250. }
  40251. };
  40252. };
  40253. trimPlugin.postcss = true;
  40254. var trimPlugin$1 = trimPlugin;
  40255. var dist = {exports: {}};
  40256. var processor = {exports: {}};
  40257. var parser = {exports: {}};
  40258. var root$1 = {exports: {}};
  40259. var container = {exports: {}};
  40260. var node$1 = {exports: {}};
  40261. var util = {};
  40262. var unesc = {exports: {}};
  40263. (function (module, exports) {
  40264. exports.__esModule = true;
  40265. exports["default"] = unesc;
  40266. // Many thanks for this post which made this migration much easier.
  40267. // https://mathiasbynens.be/notes/css-escapes
  40268. /**
  40269. *
  40270. * @param {string} str
  40271. * @returns {[string, number]|undefined}
  40272. */
  40273. function gobbleHex(str) {
  40274. var lower = str.toLowerCase();
  40275. var hex = '';
  40276. var spaceTerminated = false;
  40277. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  40278. var code = lower.charCodeAt(i); // check to see if we are dealing with a valid hex char [a-f|0-9]
  40279. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57; // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  40280. spaceTerminated = code === 32;
  40281. if (!valid) {
  40282. break;
  40283. }
  40284. hex += lower[i];
  40285. }
  40286. if (hex.length === 0) {
  40287. return undefined;
  40288. }
  40289. var codePoint = parseInt(hex, 16);
  40290. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF; // Add special case for
  40291. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  40292. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  40293. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  40294. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  40295. }
  40296. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  40297. }
  40298. var CONTAINS_ESCAPE = /\\/;
  40299. function unesc(str) {
  40300. var needToProcess = CONTAINS_ESCAPE.test(str);
  40301. if (!needToProcess) {
  40302. return str;
  40303. }
  40304. var ret = "";
  40305. for (var i = 0; i < str.length; i++) {
  40306. if (str[i] === "\\") {
  40307. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  40308. if (gobbled !== undefined) {
  40309. ret += gobbled[0];
  40310. i += gobbled[1];
  40311. continue;
  40312. } // Retain a pair of \\ if double escaped `\\\\`
  40313. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  40314. if (str[i + 1] === "\\") {
  40315. ret += "\\";
  40316. i++;
  40317. continue;
  40318. } // if \\ is at the end of the string retain it
  40319. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  40320. if (str.length === i + 1) {
  40321. ret += str[i];
  40322. }
  40323. continue;
  40324. }
  40325. ret += str[i];
  40326. }
  40327. return ret;
  40328. }
  40329. module.exports = exports.default;
  40330. } (unesc, unesc.exports));
  40331. var getProp = {exports: {}};
  40332. (function (module, exports) {
  40333. exports.__esModule = true;
  40334. exports["default"] = getProp;
  40335. function getProp(obj) {
  40336. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  40337. props[_key - 1] = arguments[_key];
  40338. }
  40339. while (props.length > 0) {
  40340. var prop = props.shift();
  40341. if (!obj[prop]) {
  40342. return undefined;
  40343. }
  40344. obj = obj[prop];
  40345. }
  40346. return obj;
  40347. }
  40348. module.exports = exports.default;
  40349. } (getProp, getProp.exports));
  40350. var ensureObject = {exports: {}};
  40351. (function (module, exports) {
  40352. exports.__esModule = true;
  40353. exports["default"] = ensureObject;
  40354. function ensureObject(obj) {
  40355. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  40356. props[_key - 1] = arguments[_key];
  40357. }
  40358. while (props.length > 0) {
  40359. var prop = props.shift();
  40360. if (!obj[prop]) {
  40361. obj[prop] = {};
  40362. }
  40363. obj = obj[prop];
  40364. }
  40365. }
  40366. module.exports = exports.default;
  40367. } (ensureObject, ensureObject.exports));
  40368. var stripComments = {exports: {}};
  40369. (function (module, exports) {
  40370. exports.__esModule = true;
  40371. exports["default"] = stripComments;
  40372. function stripComments(str) {
  40373. var s = "";
  40374. var commentStart = str.indexOf("/*");
  40375. var lastEnd = 0;
  40376. while (commentStart >= 0) {
  40377. s = s + str.slice(lastEnd, commentStart);
  40378. var commentEnd = str.indexOf("*/", commentStart + 2);
  40379. if (commentEnd < 0) {
  40380. return s;
  40381. }
  40382. lastEnd = commentEnd + 2;
  40383. commentStart = str.indexOf("/*", lastEnd);
  40384. }
  40385. s = s + str.slice(lastEnd);
  40386. return s;
  40387. }
  40388. module.exports = exports.default;
  40389. } (stripComments, stripComments.exports));
  40390. util.__esModule = true;
  40391. util.stripComments = util.ensureObject = util.getProp = util.unesc = void 0;
  40392. var _unesc = _interopRequireDefault$1(unesc.exports);
  40393. util.unesc = _unesc["default"];
  40394. var _getProp = _interopRequireDefault$1(getProp.exports);
  40395. util.getProp = _getProp["default"];
  40396. var _ensureObject = _interopRequireDefault$1(ensureObject.exports);
  40397. util.ensureObject = _ensureObject["default"];
  40398. var _stripComments = _interopRequireDefault$1(stripComments.exports);
  40399. util.stripComments = _stripComments["default"];
  40400. function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40401. (function (module, exports) {
  40402. exports.__esModule = true;
  40403. exports["default"] = void 0;
  40404. var _util = util;
  40405. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  40406. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  40407. var cloneNode = function cloneNode(obj, parent) {
  40408. if (typeof obj !== 'object' || obj === null) {
  40409. return obj;
  40410. }
  40411. var cloned = new obj.constructor();
  40412. for (var i in obj) {
  40413. if (!obj.hasOwnProperty(i)) {
  40414. continue;
  40415. }
  40416. var value = obj[i];
  40417. var type = typeof value;
  40418. if (i === 'parent' && type === 'object') {
  40419. if (parent) {
  40420. cloned[i] = parent;
  40421. }
  40422. } else if (value instanceof Array) {
  40423. cloned[i] = value.map(function (j) {
  40424. return cloneNode(j, cloned);
  40425. });
  40426. } else {
  40427. cloned[i] = cloneNode(value, cloned);
  40428. }
  40429. }
  40430. return cloned;
  40431. };
  40432. var Node = /*#__PURE__*/function () {
  40433. function Node(opts) {
  40434. if (opts === void 0) {
  40435. opts = {};
  40436. }
  40437. Object.assign(this, opts);
  40438. this.spaces = this.spaces || {};
  40439. this.spaces.before = this.spaces.before || '';
  40440. this.spaces.after = this.spaces.after || '';
  40441. }
  40442. var _proto = Node.prototype;
  40443. _proto.remove = function remove() {
  40444. if (this.parent) {
  40445. this.parent.removeChild(this);
  40446. }
  40447. this.parent = undefined;
  40448. return this;
  40449. };
  40450. _proto.replaceWith = function replaceWith() {
  40451. if (this.parent) {
  40452. for (var index in arguments) {
  40453. this.parent.insertBefore(this, arguments[index]);
  40454. }
  40455. this.remove();
  40456. }
  40457. return this;
  40458. };
  40459. _proto.next = function next() {
  40460. return this.parent.at(this.parent.index(this) + 1);
  40461. };
  40462. _proto.prev = function prev() {
  40463. return this.parent.at(this.parent.index(this) - 1);
  40464. };
  40465. _proto.clone = function clone(overrides) {
  40466. if (overrides === void 0) {
  40467. overrides = {};
  40468. }
  40469. var cloned = cloneNode(this);
  40470. for (var name in overrides) {
  40471. cloned[name] = overrides[name];
  40472. }
  40473. return cloned;
  40474. }
  40475. /**
  40476. * Some non-standard syntax doesn't follow normal escaping rules for css.
  40477. * This allows non standard syntax to be appended to an existing property
  40478. * by specifying the escaped value. By specifying the escaped value,
  40479. * illegal characters are allowed to be directly inserted into css output.
  40480. * @param {string} name the property to set
  40481. * @param {any} value the unescaped value of the property
  40482. * @param {string} valueEscaped optional. the escaped value of the property.
  40483. */
  40484. ;
  40485. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  40486. if (!this.raws) {
  40487. this.raws = {};
  40488. }
  40489. var originalValue = this[name];
  40490. var originalEscaped = this.raws[name];
  40491. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  40492. if (originalEscaped || valueEscaped !== value) {
  40493. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  40494. } else {
  40495. delete this.raws[name]; // delete any escaped value that was created by the setter.
  40496. }
  40497. }
  40498. /**
  40499. * Some non-standard syntax doesn't follow normal escaping rules for css.
  40500. * This allows the escaped value to be specified directly, allowing illegal
  40501. * characters to be directly inserted into css output.
  40502. * @param {string} name the property to set
  40503. * @param {any} value the unescaped value of the property
  40504. * @param {string} valueEscaped the escaped value of the property.
  40505. */
  40506. ;
  40507. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  40508. if (!this.raws) {
  40509. this.raws = {};
  40510. }
  40511. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  40512. this.raws[name] = valueEscaped;
  40513. }
  40514. /**
  40515. * When you want a value to passed through to CSS directly. This method
  40516. * deletes the corresponding raw value causing the stringifier to fallback
  40517. * to the unescaped value.
  40518. * @param {string} name the property to set.
  40519. * @param {any} value The value that is both escaped and unescaped.
  40520. */
  40521. ;
  40522. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  40523. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  40524. if (this.raws) {
  40525. delete this.raws[name];
  40526. }
  40527. }
  40528. /**
  40529. *
  40530. * @param {number} line The number (starting with 1)
  40531. * @param {number} column The column number (starting with 1)
  40532. */
  40533. ;
  40534. _proto.isAtPosition = function isAtPosition(line, column) {
  40535. if (this.source && this.source.start && this.source.end) {
  40536. if (this.source.start.line > line) {
  40537. return false;
  40538. }
  40539. if (this.source.end.line < line) {
  40540. return false;
  40541. }
  40542. if (this.source.start.line === line && this.source.start.column > column) {
  40543. return false;
  40544. }
  40545. if (this.source.end.line === line && this.source.end.column < column) {
  40546. return false;
  40547. }
  40548. return true;
  40549. }
  40550. return undefined;
  40551. };
  40552. _proto.stringifyProperty = function stringifyProperty(name) {
  40553. return this.raws && this.raws[name] || this[name];
  40554. };
  40555. _proto.valueToString = function valueToString() {
  40556. return String(this.stringifyProperty("value"));
  40557. };
  40558. _proto.toString = function toString() {
  40559. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  40560. };
  40561. _createClass(Node, [{
  40562. key: "rawSpaceBefore",
  40563. get: function get() {
  40564. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  40565. if (rawSpace === undefined) {
  40566. rawSpace = this.spaces && this.spaces.before;
  40567. }
  40568. return rawSpace || "";
  40569. },
  40570. set: function set(raw) {
  40571. (0, _util.ensureObject)(this, "raws", "spaces");
  40572. this.raws.spaces.before = raw;
  40573. }
  40574. }, {
  40575. key: "rawSpaceAfter",
  40576. get: function get() {
  40577. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  40578. if (rawSpace === undefined) {
  40579. rawSpace = this.spaces.after;
  40580. }
  40581. return rawSpace || "";
  40582. },
  40583. set: function set(raw) {
  40584. (0, _util.ensureObject)(this, "raws", "spaces");
  40585. this.raws.spaces.after = raw;
  40586. }
  40587. }]);
  40588. return Node;
  40589. }();
  40590. exports["default"] = Node;
  40591. module.exports = exports.default;
  40592. } (node$1, node$1.exports));
  40593. var types = {};
  40594. types.__esModule = true;
  40595. types.UNIVERSAL = types.ATTRIBUTE = types.CLASS = types.COMBINATOR = types.COMMENT = types.ID = types.NESTING = types.PSEUDO = types.ROOT = types.SELECTOR = types.STRING = types.TAG = void 0;
  40596. var TAG = 'tag';
  40597. types.TAG = TAG;
  40598. var STRING = 'string';
  40599. types.STRING = STRING;
  40600. var SELECTOR = 'selector';
  40601. types.SELECTOR = SELECTOR;
  40602. var ROOT = 'root';
  40603. types.ROOT = ROOT;
  40604. var PSEUDO = 'pseudo';
  40605. types.PSEUDO = PSEUDO;
  40606. var NESTING = 'nesting';
  40607. types.NESTING = NESTING;
  40608. var ID = 'id';
  40609. types.ID = ID;
  40610. var COMMENT = 'comment';
  40611. types.COMMENT = COMMENT;
  40612. var COMBINATOR = 'combinator';
  40613. types.COMBINATOR = COMBINATOR;
  40614. var CLASS = 'class';
  40615. types.CLASS = CLASS;
  40616. var ATTRIBUTE = 'attribute';
  40617. types.ATTRIBUTE = ATTRIBUTE;
  40618. var UNIVERSAL = 'universal';
  40619. types.UNIVERSAL = UNIVERSAL;
  40620. (function (module, exports) {
  40621. exports.__esModule = true;
  40622. exports["default"] = void 0;
  40623. var _node = _interopRequireDefault(node$1.exports);
  40624. var types$1 = _interopRequireWildcard(types);
  40625. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  40626. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  40627. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40628. function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); }
  40629. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  40630. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  40631. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  40632. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  40633. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40634. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40635. var Container = /*#__PURE__*/function (_Node) {
  40636. _inheritsLoose(Container, _Node);
  40637. function Container(opts) {
  40638. var _this;
  40639. _this = _Node.call(this, opts) || this;
  40640. if (!_this.nodes) {
  40641. _this.nodes = [];
  40642. }
  40643. return _this;
  40644. }
  40645. var _proto = Container.prototype;
  40646. _proto.append = function append(selector) {
  40647. selector.parent = this;
  40648. this.nodes.push(selector);
  40649. return this;
  40650. };
  40651. _proto.prepend = function prepend(selector) {
  40652. selector.parent = this;
  40653. this.nodes.unshift(selector);
  40654. return this;
  40655. };
  40656. _proto.at = function at(index) {
  40657. return this.nodes[index];
  40658. };
  40659. _proto.index = function index(child) {
  40660. if (typeof child === 'number') {
  40661. return child;
  40662. }
  40663. return this.nodes.indexOf(child);
  40664. };
  40665. _proto.removeChild = function removeChild(child) {
  40666. child = this.index(child);
  40667. this.at(child).parent = undefined;
  40668. this.nodes.splice(child, 1);
  40669. var index;
  40670. for (var id in this.indexes) {
  40671. index = this.indexes[id];
  40672. if (index >= child) {
  40673. this.indexes[id] = index - 1;
  40674. }
  40675. }
  40676. return this;
  40677. };
  40678. _proto.removeAll = function removeAll() {
  40679. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  40680. var node = _step.value;
  40681. node.parent = undefined;
  40682. }
  40683. this.nodes = [];
  40684. return this;
  40685. };
  40686. _proto.empty = function empty() {
  40687. return this.removeAll();
  40688. };
  40689. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  40690. newNode.parent = this;
  40691. var oldIndex = this.index(oldNode);
  40692. this.nodes.splice(oldIndex + 1, 0, newNode);
  40693. newNode.parent = this;
  40694. var index;
  40695. for (var id in this.indexes) {
  40696. index = this.indexes[id];
  40697. if (oldIndex <= index) {
  40698. this.indexes[id] = index + 1;
  40699. }
  40700. }
  40701. return this;
  40702. };
  40703. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  40704. newNode.parent = this;
  40705. var oldIndex = this.index(oldNode);
  40706. this.nodes.splice(oldIndex, 0, newNode);
  40707. newNode.parent = this;
  40708. var index;
  40709. for (var id in this.indexes) {
  40710. index = this.indexes[id];
  40711. if (index <= oldIndex) {
  40712. this.indexes[id] = index + 1;
  40713. }
  40714. }
  40715. return this;
  40716. };
  40717. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  40718. var found = undefined;
  40719. this.each(function (node) {
  40720. if (node.atPosition) {
  40721. var foundChild = node.atPosition(line, col);
  40722. if (foundChild) {
  40723. found = foundChild;
  40724. return false;
  40725. }
  40726. } else if (node.isAtPosition(line, col)) {
  40727. found = node;
  40728. return false;
  40729. }
  40730. });
  40731. return found;
  40732. }
  40733. /**
  40734. * Return the most specific node at the line and column number given.
  40735. * The source location is based on the original parsed location, locations aren't
  40736. * updated as selector nodes are mutated.
  40737. *
  40738. * Note that this location is relative to the location of the first character
  40739. * of the selector, and not the location of the selector in the overall document
  40740. * when used in conjunction with postcss.
  40741. *
  40742. * If not found, returns undefined.
  40743. * @param {number} line The line number of the node to find. (1-based index)
  40744. * @param {number} col The column number of the node to find. (1-based index)
  40745. */
  40746. ;
  40747. _proto.atPosition = function atPosition(line, col) {
  40748. if (this.isAtPosition(line, col)) {
  40749. return this._findChildAtPosition(line, col) || this;
  40750. } else {
  40751. return undefined;
  40752. }
  40753. };
  40754. _proto._inferEndPosition = function _inferEndPosition() {
  40755. if (this.last && this.last.source && this.last.source.end) {
  40756. this.source = this.source || {};
  40757. this.source.end = this.source.end || {};
  40758. Object.assign(this.source.end, this.last.source.end);
  40759. }
  40760. };
  40761. _proto.each = function each(callback) {
  40762. if (!this.lastEach) {
  40763. this.lastEach = 0;
  40764. }
  40765. if (!this.indexes) {
  40766. this.indexes = {};
  40767. }
  40768. this.lastEach++;
  40769. var id = this.lastEach;
  40770. this.indexes[id] = 0;
  40771. if (!this.length) {
  40772. return undefined;
  40773. }
  40774. var index, result;
  40775. while (this.indexes[id] < this.length) {
  40776. index = this.indexes[id];
  40777. result = callback(this.at(index), index);
  40778. if (result === false) {
  40779. break;
  40780. }
  40781. this.indexes[id] += 1;
  40782. }
  40783. delete this.indexes[id];
  40784. if (result === false) {
  40785. return false;
  40786. }
  40787. };
  40788. _proto.walk = function walk(callback) {
  40789. return this.each(function (node, i) {
  40790. var result = callback(node, i);
  40791. if (result !== false && node.length) {
  40792. result = node.walk(callback);
  40793. }
  40794. if (result === false) {
  40795. return false;
  40796. }
  40797. });
  40798. };
  40799. _proto.walkAttributes = function walkAttributes(callback) {
  40800. var _this2 = this;
  40801. return this.walk(function (selector) {
  40802. if (selector.type === types$1.ATTRIBUTE) {
  40803. return callback.call(_this2, selector);
  40804. }
  40805. });
  40806. };
  40807. _proto.walkClasses = function walkClasses(callback) {
  40808. var _this3 = this;
  40809. return this.walk(function (selector) {
  40810. if (selector.type === types$1.CLASS) {
  40811. return callback.call(_this3, selector);
  40812. }
  40813. });
  40814. };
  40815. _proto.walkCombinators = function walkCombinators(callback) {
  40816. var _this4 = this;
  40817. return this.walk(function (selector) {
  40818. if (selector.type === types$1.COMBINATOR) {
  40819. return callback.call(_this4, selector);
  40820. }
  40821. });
  40822. };
  40823. _proto.walkComments = function walkComments(callback) {
  40824. var _this5 = this;
  40825. return this.walk(function (selector) {
  40826. if (selector.type === types$1.COMMENT) {
  40827. return callback.call(_this5, selector);
  40828. }
  40829. });
  40830. };
  40831. _proto.walkIds = function walkIds(callback) {
  40832. var _this6 = this;
  40833. return this.walk(function (selector) {
  40834. if (selector.type === types$1.ID) {
  40835. return callback.call(_this6, selector);
  40836. }
  40837. });
  40838. };
  40839. _proto.walkNesting = function walkNesting(callback) {
  40840. var _this7 = this;
  40841. return this.walk(function (selector) {
  40842. if (selector.type === types$1.NESTING) {
  40843. return callback.call(_this7, selector);
  40844. }
  40845. });
  40846. };
  40847. _proto.walkPseudos = function walkPseudos(callback) {
  40848. var _this8 = this;
  40849. return this.walk(function (selector) {
  40850. if (selector.type === types$1.PSEUDO) {
  40851. return callback.call(_this8, selector);
  40852. }
  40853. });
  40854. };
  40855. _proto.walkTags = function walkTags(callback) {
  40856. var _this9 = this;
  40857. return this.walk(function (selector) {
  40858. if (selector.type === types$1.TAG) {
  40859. return callback.call(_this9, selector);
  40860. }
  40861. });
  40862. };
  40863. _proto.walkUniversals = function walkUniversals(callback) {
  40864. var _this10 = this;
  40865. return this.walk(function (selector) {
  40866. if (selector.type === types$1.UNIVERSAL) {
  40867. return callback.call(_this10, selector);
  40868. }
  40869. });
  40870. };
  40871. _proto.split = function split(callback) {
  40872. var _this11 = this;
  40873. var current = [];
  40874. return this.reduce(function (memo, node, index) {
  40875. var split = callback.call(_this11, node);
  40876. current.push(node);
  40877. if (split) {
  40878. memo.push(current);
  40879. current = [];
  40880. } else if (index === _this11.length - 1) {
  40881. memo.push(current);
  40882. }
  40883. return memo;
  40884. }, []);
  40885. };
  40886. _proto.map = function map(callback) {
  40887. return this.nodes.map(callback);
  40888. };
  40889. _proto.reduce = function reduce(callback, memo) {
  40890. return this.nodes.reduce(callback, memo);
  40891. };
  40892. _proto.every = function every(callback) {
  40893. return this.nodes.every(callback);
  40894. };
  40895. _proto.some = function some(callback) {
  40896. return this.nodes.some(callback);
  40897. };
  40898. _proto.filter = function filter(callback) {
  40899. return this.nodes.filter(callback);
  40900. };
  40901. _proto.sort = function sort(callback) {
  40902. return this.nodes.sort(callback);
  40903. };
  40904. _proto.toString = function toString() {
  40905. return this.map(String).join('');
  40906. };
  40907. _createClass(Container, [{
  40908. key: "first",
  40909. get: function get() {
  40910. return this.at(0);
  40911. }
  40912. }, {
  40913. key: "last",
  40914. get: function get() {
  40915. return this.at(this.length - 1);
  40916. }
  40917. }, {
  40918. key: "length",
  40919. get: function get() {
  40920. return this.nodes.length;
  40921. }
  40922. }]);
  40923. return Container;
  40924. }(_node["default"]);
  40925. exports["default"] = Container;
  40926. module.exports = exports.default;
  40927. } (container, container.exports));
  40928. (function (module, exports) {
  40929. exports.__esModule = true;
  40930. exports["default"] = void 0;
  40931. var _container = _interopRequireDefault(container.exports);
  40932. var _types = types;
  40933. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40934. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  40935. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  40936. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40937. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40938. var Root = /*#__PURE__*/function (_Container) {
  40939. _inheritsLoose(Root, _Container);
  40940. function Root(opts) {
  40941. var _this;
  40942. _this = _Container.call(this, opts) || this;
  40943. _this.type = _types.ROOT;
  40944. return _this;
  40945. }
  40946. var _proto = Root.prototype;
  40947. _proto.toString = function toString() {
  40948. var str = this.reduce(function (memo, selector) {
  40949. memo.push(String(selector));
  40950. return memo;
  40951. }, []).join(',');
  40952. return this.trailingComma ? str + ',' : str;
  40953. };
  40954. _proto.error = function error(message, options) {
  40955. if (this._error) {
  40956. return this._error(message, options);
  40957. } else {
  40958. return new Error(message);
  40959. }
  40960. };
  40961. _createClass(Root, [{
  40962. key: "errorGenerator",
  40963. set: function set(handler) {
  40964. this._error = handler;
  40965. }
  40966. }]);
  40967. return Root;
  40968. }(_container["default"]);
  40969. exports["default"] = Root;
  40970. module.exports = exports.default;
  40971. } (root$1, root$1.exports));
  40972. var selector$1 = {exports: {}};
  40973. (function (module, exports) {
  40974. exports.__esModule = true;
  40975. exports["default"] = void 0;
  40976. var _container = _interopRequireDefault(container.exports);
  40977. var _types = types;
  40978. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40979. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40980. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40981. var Selector = /*#__PURE__*/function (_Container) {
  40982. _inheritsLoose(Selector, _Container);
  40983. function Selector(opts) {
  40984. var _this;
  40985. _this = _Container.call(this, opts) || this;
  40986. _this.type = _types.SELECTOR;
  40987. return _this;
  40988. }
  40989. return Selector;
  40990. }(_container["default"]);
  40991. exports["default"] = Selector;
  40992. module.exports = exports.default;
  40993. } (selector$1, selector$1.exports));
  40994. var className$1 = {exports: {}};
  40995. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  40996. var object = {};
  40997. var hasOwnProperty = object.hasOwnProperty;
  40998. var merge$2 = function merge(options, defaults) {
  40999. if (!options) {
  41000. return defaults;
  41001. }
  41002. var result = {};
  41003. for (var key in defaults) {
  41004. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  41005. // only recognized option names are used.
  41006. result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
  41007. }
  41008. return result;
  41009. };
  41010. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  41011. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  41012. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  41013. // https://mathiasbynens.be/notes/css-escapes#css
  41014. var cssesc = function cssesc(string, options) {
  41015. options = merge$2(options, cssesc.options);
  41016. if (options.quotes != 'single' && options.quotes != 'double') {
  41017. options.quotes = 'single';
  41018. }
  41019. var quote = options.quotes == 'double' ? '"' : '\'';
  41020. var isIdentifier = options.isIdentifier;
  41021. var firstChar = string.charAt(0);
  41022. var output = '';
  41023. var counter = 0;
  41024. var length = string.length;
  41025. while (counter < length) {
  41026. var character = string.charAt(counter++);
  41027. var codePoint = character.charCodeAt();
  41028. var value = void 0;
  41029. // If it’s not a printable ASCII character…
  41030. if (codePoint < 0x20 || codePoint > 0x7E) {
  41031. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  41032. // It’s a high surrogate, and there is a next character.
  41033. var extra = string.charCodeAt(counter++);
  41034. if ((extra & 0xFC00) == 0xDC00) {
  41035. // next character is low surrogate
  41036. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  41037. } else {
  41038. // It’s an unmatched surrogate; only append this code unit, in case
  41039. // the next code unit is the high surrogate of a surrogate pair.
  41040. counter--;
  41041. }
  41042. }
  41043. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  41044. } else {
  41045. if (options.escapeEverything) {
  41046. if (regexAnySingleEscape.test(character)) {
  41047. value = '\\' + character;
  41048. } else {
  41049. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  41050. }
  41051. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  41052. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  41053. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  41054. value = '\\' + character;
  41055. } else {
  41056. value = character;
  41057. }
  41058. }
  41059. output += value;
  41060. }
  41061. if (isIdentifier) {
  41062. if (/^-[-\d]/.test(output)) {
  41063. output = '\\-' + output.slice(1);
  41064. } else if (/\d/.test(firstChar)) {
  41065. output = '\\3' + firstChar + ' ' + output.slice(1);
  41066. }
  41067. }
  41068. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  41069. // since they’re redundant. Note that this is only possible if the escape
  41070. // sequence isn’t preceded by an odd number of backslashes.
  41071. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  41072. if ($1 && $1.length % 2) {
  41073. // It’s not safe to remove the space, so don’t.
  41074. return $0;
  41075. }
  41076. // Strip the space.
  41077. return ($1 || '') + $2;
  41078. });
  41079. if (!isIdentifier && options.wrap) {
  41080. return quote + output + quote;
  41081. }
  41082. return output;
  41083. };
  41084. // Expose default options (so they can be overridden globally).
  41085. cssesc.options = {
  41086. 'escapeEverything': false,
  41087. 'isIdentifier': false,
  41088. 'quotes': 'single',
  41089. 'wrap': false
  41090. };
  41091. cssesc.version = '3.0.0';
  41092. var cssesc_1 = cssesc;
  41093. (function (module, exports) {
  41094. exports.__esModule = true;
  41095. exports["default"] = void 0;
  41096. var _cssesc = _interopRequireDefault(cssesc_1);
  41097. var _util = util;
  41098. var _node = _interopRequireDefault(node$1.exports);
  41099. var _types = types;
  41100. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41101. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  41102. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  41103. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41104. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41105. var ClassName = /*#__PURE__*/function (_Node) {
  41106. _inheritsLoose(ClassName, _Node);
  41107. function ClassName(opts) {
  41108. var _this;
  41109. _this = _Node.call(this, opts) || this;
  41110. _this.type = _types.CLASS;
  41111. _this._constructed = true;
  41112. return _this;
  41113. }
  41114. var _proto = ClassName.prototype;
  41115. _proto.valueToString = function valueToString() {
  41116. return '.' + _Node.prototype.valueToString.call(this);
  41117. };
  41118. _createClass(ClassName, [{
  41119. key: "value",
  41120. get: function get() {
  41121. return this._value;
  41122. },
  41123. set: function set(v) {
  41124. if (this._constructed) {
  41125. var escaped = (0, _cssesc["default"])(v, {
  41126. isIdentifier: true
  41127. });
  41128. if (escaped !== v) {
  41129. (0, _util.ensureObject)(this, "raws");
  41130. this.raws.value = escaped;
  41131. } else if (this.raws) {
  41132. delete this.raws.value;
  41133. }
  41134. }
  41135. this._value = v;
  41136. }
  41137. }]);
  41138. return ClassName;
  41139. }(_node["default"]);
  41140. exports["default"] = ClassName;
  41141. module.exports = exports.default;
  41142. } (className$1, className$1.exports));
  41143. var comment$2 = {exports: {}};
  41144. (function (module, exports) {
  41145. exports.__esModule = true;
  41146. exports["default"] = void 0;
  41147. var _node = _interopRequireDefault(node$1.exports);
  41148. var _types = types;
  41149. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41150. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41151. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41152. var Comment = /*#__PURE__*/function (_Node) {
  41153. _inheritsLoose(Comment, _Node);
  41154. function Comment(opts) {
  41155. var _this;
  41156. _this = _Node.call(this, opts) || this;
  41157. _this.type = _types.COMMENT;
  41158. return _this;
  41159. }
  41160. return Comment;
  41161. }(_node["default"]);
  41162. exports["default"] = Comment;
  41163. module.exports = exports.default;
  41164. } (comment$2, comment$2.exports));
  41165. var id$1 = {exports: {}};
  41166. (function (module, exports) {
  41167. exports.__esModule = true;
  41168. exports["default"] = void 0;
  41169. var _node = _interopRequireDefault(node$1.exports);
  41170. var _types = types;
  41171. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41172. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41173. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41174. var ID = /*#__PURE__*/function (_Node) {
  41175. _inheritsLoose(ID, _Node);
  41176. function ID(opts) {
  41177. var _this;
  41178. _this = _Node.call(this, opts) || this;
  41179. _this.type = _types.ID;
  41180. return _this;
  41181. }
  41182. var _proto = ID.prototype;
  41183. _proto.valueToString = function valueToString() {
  41184. return '#' + _Node.prototype.valueToString.call(this);
  41185. };
  41186. return ID;
  41187. }(_node["default"]);
  41188. exports["default"] = ID;
  41189. module.exports = exports.default;
  41190. } (id$1, id$1.exports));
  41191. var tag$1 = {exports: {}};
  41192. var namespace = {exports: {}};
  41193. (function (module, exports) {
  41194. exports.__esModule = true;
  41195. exports["default"] = void 0;
  41196. var _cssesc = _interopRequireDefault(cssesc_1);
  41197. var _util = util;
  41198. var _node = _interopRequireDefault(node$1.exports);
  41199. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41200. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  41201. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  41202. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41203. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41204. var Namespace = /*#__PURE__*/function (_Node) {
  41205. _inheritsLoose(Namespace, _Node);
  41206. function Namespace() {
  41207. return _Node.apply(this, arguments) || this;
  41208. }
  41209. var _proto = Namespace.prototype;
  41210. _proto.qualifiedName = function qualifiedName(value) {
  41211. if (this.namespace) {
  41212. return this.namespaceString + "|" + value;
  41213. } else {
  41214. return value;
  41215. }
  41216. };
  41217. _proto.valueToString = function valueToString() {
  41218. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  41219. };
  41220. _createClass(Namespace, [{
  41221. key: "namespace",
  41222. get: function get() {
  41223. return this._namespace;
  41224. },
  41225. set: function set(namespace) {
  41226. if (namespace === true || namespace === "*" || namespace === "&") {
  41227. this._namespace = namespace;
  41228. if (this.raws) {
  41229. delete this.raws.namespace;
  41230. }
  41231. return;
  41232. }
  41233. var escaped = (0, _cssesc["default"])(namespace, {
  41234. isIdentifier: true
  41235. });
  41236. this._namespace = namespace;
  41237. if (escaped !== namespace) {
  41238. (0, _util.ensureObject)(this, "raws");
  41239. this.raws.namespace = escaped;
  41240. } else if (this.raws) {
  41241. delete this.raws.namespace;
  41242. }
  41243. }
  41244. }, {
  41245. key: "ns",
  41246. get: function get() {
  41247. return this._namespace;
  41248. },
  41249. set: function set(namespace) {
  41250. this.namespace = namespace;
  41251. }
  41252. }, {
  41253. key: "namespaceString",
  41254. get: function get() {
  41255. if (this.namespace) {
  41256. var ns = this.stringifyProperty("namespace");
  41257. if (ns === true) {
  41258. return '';
  41259. } else {
  41260. return ns;
  41261. }
  41262. } else {
  41263. return '';
  41264. }
  41265. }
  41266. }]);
  41267. return Namespace;
  41268. }(_node["default"]);
  41269. exports["default"] = Namespace;
  41270. module.exports = exports.default;
  41271. } (namespace, namespace.exports));
  41272. (function (module, exports) {
  41273. exports.__esModule = true;
  41274. exports["default"] = void 0;
  41275. var _namespace = _interopRequireDefault(namespace.exports);
  41276. var _types = types;
  41277. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41278. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41279. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41280. var Tag = /*#__PURE__*/function (_Namespace) {
  41281. _inheritsLoose(Tag, _Namespace);
  41282. function Tag(opts) {
  41283. var _this;
  41284. _this = _Namespace.call(this, opts) || this;
  41285. _this.type = _types.TAG;
  41286. return _this;
  41287. }
  41288. return Tag;
  41289. }(_namespace["default"]);
  41290. exports["default"] = Tag;
  41291. module.exports = exports.default;
  41292. } (tag$1, tag$1.exports));
  41293. var string$1 = {exports: {}};
  41294. (function (module, exports) {
  41295. exports.__esModule = true;
  41296. exports["default"] = void 0;
  41297. var _node = _interopRequireDefault(node$1.exports);
  41298. var _types = types;
  41299. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41300. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41301. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41302. var String = /*#__PURE__*/function (_Node) {
  41303. _inheritsLoose(String, _Node);
  41304. function String(opts) {
  41305. var _this;
  41306. _this = _Node.call(this, opts) || this;
  41307. _this.type = _types.STRING;
  41308. return _this;
  41309. }
  41310. return String;
  41311. }(_node["default"]);
  41312. exports["default"] = String;
  41313. module.exports = exports.default;
  41314. } (string$1, string$1.exports));
  41315. var pseudo$1 = {exports: {}};
  41316. (function (module, exports) {
  41317. exports.__esModule = true;
  41318. exports["default"] = void 0;
  41319. var _container = _interopRequireDefault(container.exports);
  41320. var _types = types;
  41321. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41322. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41323. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41324. var Pseudo = /*#__PURE__*/function (_Container) {
  41325. _inheritsLoose(Pseudo, _Container);
  41326. function Pseudo(opts) {
  41327. var _this;
  41328. _this = _Container.call(this, opts) || this;
  41329. _this.type = _types.PSEUDO;
  41330. return _this;
  41331. }
  41332. var _proto = Pseudo.prototype;
  41333. _proto.toString = function toString() {
  41334. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  41335. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  41336. };
  41337. return Pseudo;
  41338. }(_container["default"]);
  41339. exports["default"] = Pseudo;
  41340. module.exports = exports.default;
  41341. } (pseudo$1, pseudo$1.exports));
  41342. var attribute$1 = {};
  41343. /**
  41344. * For Node.js, simply re-export the core `util.deprecate` function.
  41345. */
  41346. var node = require$$0$1.deprecate;
  41347. (function (exports) {
  41348. exports.__esModule = true;
  41349. exports.unescapeValue = unescapeValue;
  41350. exports["default"] = void 0;
  41351. var _cssesc = _interopRequireDefault(cssesc_1);
  41352. var _unesc = _interopRequireDefault(unesc.exports);
  41353. var _namespace = _interopRequireDefault(namespace.exports);
  41354. var _types = types;
  41355. var _CSSESC_QUOTE_OPTIONS;
  41356. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41357. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  41358. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  41359. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41360. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41361. var deprecate = node;
  41362. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  41363. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  41364. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  41365. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  41366. function unescapeValue(value) {
  41367. var deprecatedUsage = false;
  41368. var quoteMark = null;
  41369. var unescaped = value;
  41370. var m = unescaped.match(WRAPPED_IN_QUOTES);
  41371. if (m) {
  41372. quoteMark = m[1];
  41373. unescaped = m[2];
  41374. }
  41375. unescaped = (0, _unesc["default"])(unescaped);
  41376. if (unescaped !== value) {
  41377. deprecatedUsage = true;
  41378. }
  41379. return {
  41380. deprecatedUsage: deprecatedUsage,
  41381. unescaped: unescaped,
  41382. quoteMark: quoteMark
  41383. };
  41384. }
  41385. function handleDeprecatedContructorOpts(opts) {
  41386. if (opts.quoteMark !== undefined) {
  41387. return opts;
  41388. }
  41389. if (opts.value === undefined) {
  41390. return opts;
  41391. }
  41392. warnOfDeprecatedConstructor();
  41393. var _unescapeValue = unescapeValue(opts.value),
  41394. quoteMark = _unescapeValue.quoteMark,
  41395. unescaped = _unescapeValue.unescaped;
  41396. if (!opts.raws) {
  41397. opts.raws = {};
  41398. }
  41399. if (opts.raws.value === undefined) {
  41400. opts.raws.value = opts.value;
  41401. }
  41402. opts.value = unescaped;
  41403. opts.quoteMark = quoteMark;
  41404. return opts;
  41405. }
  41406. var Attribute = /*#__PURE__*/function (_Namespace) {
  41407. _inheritsLoose(Attribute, _Namespace);
  41408. function Attribute(opts) {
  41409. var _this;
  41410. if (opts === void 0) {
  41411. opts = {};
  41412. }
  41413. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  41414. _this.type = _types.ATTRIBUTE;
  41415. _this.raws = _this.raws || {};
  41416. Object.defineProperty(_this.raws, 'unquoted', {
  41417. get: deprecate(function () {
  41418. return _this.value;
  41419. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  41420. set: deprecate(function () {
  41421. return _this.value;
  41422. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  41423. });
  41424. _this._constructed = true;
  41425. return _this;
  41426. }
  41427. /**
  41428. * Returns the Attribute's value quoted such that it would be legal to use
  41429. * in the value of a css file. The original value's quotation setting
  41430. * used for stringification is left unchanged. See `setValue(value, options)`
  41431. * if you want to control the quote settings of a new value for the attribute.
  41432. *
  41433. * You can also change the quotation used for the current value by setting quoteMark.
  41434. *
  41435. * Options:
  41436. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  41437. * option is not set, the original value for quoteMark will be used. If
  41438. * indeterminate, a double quote is used. The legal values are:
  41439. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  41440. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  41441. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  41442. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  41443. * over the quoteMark option value.
  41444. * * smart {boolean} - if true, will select a quote mark based on the value
  41445. * and the other options specified here. See the `smartQuoteMark()`
  41446. * method.
  41447. **/
  41448. var _proto = Attribute.prototype;
  41449. _proto.getQuotedValue = function getQuotedValue(options) {
  41450. if (options === void 0) {
  41451. options = {};
  41452. }
  41453. var quoteMark = this._determineQuoteMark(options);
  41454. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  41455. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  41456. return escaped;
  41457. };
  41458. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  41459. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  41460. }
  41461. /**
  41462. * Set the unescaped value with the specified quotation options. The value
  41463. * provided must not include any wrapping quote marks -- those quotes will
  41464. * be interpreted as part of the value and escaped accordingly.
  41465. */
  41466. ;
  41467. _proto.setValue = function setValue(value, options) {
  41468. if (options === void 0) {
  41469. options = {};
  41470. }
  41471. this._value = value;
  41472. this._quoteMark = this._determineQuoteMark(options);
  41473. this._syncRawValue();
  41474. }
  41475. /**
  41476. * Intelligently select a quoteMark value based on the value's contents. If
  41477. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  41478. * mark will be picked that minimizes the number of escapes.
  41479. *
  41480. * If there's no clear winner, the quote mark from these options is used,
  41481. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  41482. * true). If the quoteMark is unspecified, a double quote is used.
  41483. *
  41484. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  41485. * from the quoteValue method.
  41486. */
  41487. ;
  41488. _proto.smartQuoteMark = function smartQuoteMark(options) {
  41489. var v = this.value;
  41490. var numSingleQuotes = v.replace(/[^']/g, '').length;
  41491. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  41492. if (numSingleQuotes + numDoubleQuotes === 0) {
  41493. var escaped = (0, _cssesc["default"])(v, {
  41494. isIdentifier: true
  41495. });
  41496. if (escaped === v) {
  41497. return Attribute.NO_QUOTE;
  41498. } else {
  41499. var pref = this.preferredQuoteMark(options);
  41500. if (pref === Attribute.NO_QUOTE) {
  41501. // pick a quote mark that isn't none and see if it's smaller
  41502. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  41503. var opts = CSSESC_QUOTE_OPTIONS[quote];
  41504. var quoteValue = (0, _cssesc["default"])(v, opts);
  41505. if (quoteValue.length < escaped.length) {
  41506. return quote;
  41507. }
  41508. }
  41509. return pref;
  41510. }
  41511. } else if (numDoubleQuotes === numSingleQuotes) {
  41512. return this.preferredQuoteMark(options);
  41513. } else if (numDoubleQuotes < numSingleQuotes) {
  41514. return Attribute.DOUBLE_QUOTE;
  41515. } else {
  41516. return Attribute.SINGLE_QUOTE;
  41517. }
  41518. }
  41519. /**
  41520. * Selects the preferred quote mark based on the options and the current quote mark value.
  41521. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  41522. * instead.
  41523. */
  41524. ;
  41525. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  41526. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  41527. if (quoteMark === undefined) {
  41528. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  41529. }
  41530. if (quoteMark === undefined) {
  41531. quoteMark = Attribute.DOUBLE_QUOTE;
  41532. }
  41533. return quoteMark;
  41534. };
  41535. _proto._syncRawValue = function _syncRawValue() {
  41536. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  41537. if (rawValue === this._value) {
  41538. if (this.raws) {
  41539. delete this.raws.value;
  41540. }
  41541. } else {
  41542. this.raws.value = rawValue;
  41543. }
  41544. };
  41545. _proto._handleEscapes = function _handleEscapes(prop, value) {
  41546. if (this._constructed) {
  41547. var escaped = (0, _cssesc["default"])(value, {
  41548. isIdentifier: true
  41549. });
  41550. if (escaped !== value) {
  41551. this.raws[prop] = escaped;
  41552. } else {
  41553. delete this.raws[prop];
  41554. }
  41555. }
  41556. };
  41557. _proto._spacesFor = function _spacesFor(name) {
  41558. var attrSpaces = {
  41559. before: '',
  41560. after: ''
  41561. };
  41562. var spaces = this.spaces[name] || {};
  41563. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  41564. return Object.assign(attrSpaces, spaces, rawSpaces);
  41565. };
  41566. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  41567. if (spaceName === void 0) {
  41568. spaceName = name;
  41569. }
  41570. if (concat === void 0) {
  41571. concat = defaultAttrConcat;
  41572. }
  41573. var attrSpaces = this._spacesFor(spaceName);
  41574. return concat(this.stringifyProperty(name), attrSpaces);
  41575. }
  41576. /**
  41577. * returns the offset of the attribute part specified relative to the
  41578. * start of the node of the output string.
  41579. *
  41580. * * "ns" - alias for "namespace"
  41581. * * "namespace" - the namespace if it exists.
  41582. * * "attribute" - the attribute name
  41583. * * "attributeNS" - the start of the attribute or its namespace
  41584. * * "operator" - the match operator of the attribute
  41585. * * "value" - The value (string or identifier)
  41586. * * "insensitive" - the case insensitivity flag;
  41587. * @param part One of the possible values inside an attribute.
  41588. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  41589. */
  41590. ;
  41591. _proto.offsetOf = function offsetOf(name) {
  41592. var count = 1;
  41593. var attributeSpaces = this._spacesFor("attribute");
  41594. count += attributeSpaces.before.length;
  41595. if (name === "namespace" || name === "ns") {
  41596. return this.namespace ? count : -1;
  41597. }
  41598. if (name === "attributeNS") {
  41599. return count;
  41600. }
  41601. count += this.namespaceString.length;
  41602. if (this.namespace) {
  41603. count += 1;
  41604. }
  41605. if (name === "attribute") {
  41606. return count;
  41607. }
  41608. count += this.stringifyProperty("attribute").length;
  41609. count += attributeSpaces.after.length;
  41610. var operatorSpaces = this._spacesFor("operator");
  41611. count += operatorSpaces.before.length;
  41612. var operator = this.stringifyProperty("operator");
  41613. if (name === "operator") {
  41614. return operator ? count : -1;
  41615. }
  41616. count += operator.length;
  41617. count += operatorSpaces.after.length;
  41618. var valueSpaces = this._spacesFor("value");
  41619. count += valueSpaces.before.length;
  41620. var value = this.stringifyProperty("value");
  41621. if (name === "value") {
  41622. return value ? count : -1;
  41623. }
  41624. count += value.length;
  41625. count += valueSpaces.after.length;
  41626. var insensitiveSpaces = this._spacesFor("insensitive");
  41627. count += insensitiveSpaces.before.length;
  41628. if (name === "insensitive") {
  41629. return this.insensitive ? count : -1;
  41630. }
  41631. return -1;
  41632. };
  41633. _proto.toString = function toString() {
  41634. var _this2 = this;
  41635. var selector = [this.rawSpaceBefore, '['];
  41636. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  41637. if (this.operator && (this.value || this.value === '')) {
  41638. selector.push(this._stringFor('operator'));
  41639. selector.push(this._stringFor('value'));
  41640. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  41641. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  41642. attrSpaces.before = " ";
  41643. }
  41644. return defaultAttrConcat(attrValue, attrSpaces);
  41645. }));
  41646. }
  41647. selector.push(']');
  41648. selector.push(this.rawSpaceAfter);
  41649. return selector.join('');
  41650. };
  41651. _createClass(Attribute, [{
  41652. key: "quoted",
  41653. get: function get() {
  41654. var qm = this.quoteMark;
  41655. return qm === "'" || qm === '"';
  41656. },
  41657. set: function set(value) {
  41658. warnOfDeprecatedQuotedAssignment();
  41659. }
  41660. /**
  41661. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  41662. * returns `null` if the value is not quoted.
  41663. * returns `undefined` if the quotation state is unknown (this can happen when
  41664. * the attribute is constructed without specifying a quote mark.)
  41665. */
  41666. }, {
  41667. key: "quoteMark",
  41668. get: function get() {
  41669. return this._quoteMark;
  41670. }
  41671. /**
  41672. * Set the quote mark to be used by this attribute's value.
  41673. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  41674. * value is updated accordingly.
  41675. *
  41676. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  41677. */
  41678. ,
  41679. set: function set(quoteMark) {
  41680. if (!this._constructed) {
  41681. this._quoteMark = quoteMark;
  41682. return;
  41683. }
  41684. if (this._quoteMark !== quoteMark) {
  41685. this._quoteMark = quoteMark;
  41686. this._syncRawValue();
  41687. }
  41688. }
  41689. }, {
  41690. key: "qualifiedAttribute",
  41691. get: function get() {
  41692. return this.qualifiedName(this.raws.attribute || this.attribute);
  41693. }
  41694. }, {
  41695. key: "insensitiveFlag",
  41696. get: function get() {
  41697. return this.insensitive ? 'i' : '';
  41698. }
  41699. }, {
  41700. key: "value",
  41701. get: function get() {
  41702. return this._value;
  41703. }
  41704. /**
  41705. * Before 3.0, the value had to be set to an escaped value including any wrapped
  41706. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  41707. * is unescaped during parsing and any quote marks are removed.
  41708. *
  41709. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  41710. * a deprecation warning is raised when the new value contains any characters that would
  41711. * require escaping (including if it contains wrapped quotes).
  41712. *
  41713. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  41714. * how the new value is quoted.
  41715. */
  41716. ,
  41717. set: function set(v) {
  41718. if (this._constructed) {
  41719. var _unescapeValue2 = unescapeValue(v),
  41720. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  41721. unescaped = _unescapeValue2.unescaped,
  41722. quoteMark = _unescapeValue2.quoteMark;
  41723. if (deprecatedUsage) {
  41724. warnOfDeprecatedValueAssignment();
  41725. }
  41726. if (unescaped === this._value && quoteMark === this._quoteMark) {
  41727. return;
  41728. }
  41729. this._value = unescaped;
  41730. this._quoteMark = quoteMark;
  41731. this._syncRawValue();
  41732. } else {
  41733. this._value = v;
  41734. }
  41735. }
  41736. }, {
  41737. key: "attribute",
  41738. get: function get() {
  41739. return this._attribute;
  41740. },
  41741. set: function set(name) {
  41742. this._handleEscapes("attribute", name);
  41743. this._attribute = name;
  41744. }
  41745. }]);
  41746. return Attribute;
  41747. }(_namespace["default"]);
  41748. exports["default"] = Attribute;
  41749. Attribute.NO_QUOTE = null;
  41750. Attribute.SINGLE_QUOTE = "'";
  41751. Attribute.DOUBLE_QUOTE = '"';
  41752. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  41753. "'": {
  41754. quotes: 'single',
  41755. wrap: true
  41756. },
  41757. '"': {
  41758. quotes: 'double',
  41759. wrap: true
  41760. }
  41761. }, _CSSESC_QUOTE_OPTIONS[null] = {
  41762. isIdentifier: true
  41763. }, _CSSESC_QUOTE_OPTIONS);
  41764. function defaultAttrConcat(attrValue, attrSpaces) {
  41765. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  41766. }
  41767. } (attribute$1));
  41768. var universal$1 = {exports: {}};
  41769. (function (module, exports) {
  41770. exports.__esModule = true;
  41771. exports["default"] = void 0;
  41772. var _namespace = _interopRequireDefault(namespace.exports);
  41773. var _types = types;
  41774. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41775. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41776. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41777. var Universal = /*#__PURE__*/function (_Namespace) {
  41778. _inheritsLoose(Universal, _Namespace);
  41779. function Universal(opts) {
  41780. var _this;
  41781. _this = _Namespace.call(this, opts) || this;
  41782. _this.type = _types.UNIVERSAL;
  41783. _this.value = '*';
  41784. return _this;
  41785. }
  41786. return Universal;
  41787. }(_namespace["default"]);
  41788. exports["default"] = Universal;
  41789. module.exports = exports.default;
  41790. } (universal$1, universal$1.exports));
  41791. var combinator$2 = {exports: {}};
  41792. (function (module, exports) {
  41793. exports.__esModule = true;
  41794. exports["default"] = void 0;
  41795. var _node = _interopRequireDefault(node$1.exports);
  41796. var _types = types;
  41797. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41798. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41799. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41800. var Combinator = /*#__PURE__*/function (_Node) {
  41801. _inheritsLoose(Combinator, _Node);
  41802. function Combinator(opts) {
  41803. var _this;
  41804. _this = _Node.call(this, opts) || this;
  41805. _this.type = _types.COMBINATOR;
  41806. return _this;
  41807. }
  41808. return Combinator;
  41809. }(_node["default"]);
  41810. exports["default"] = Combinator;
  41811. module.exports = exports.default;
  41812. } (combinator$2, combinator$2.exports));
  41813. var nesting$1 = {exports: {}};
  41814. (function (module, exports) {
  41815. exports.__esModule = true;
  41816. exports["default"] = void 0;
  41817. var _node = _interopRequireDefault(node$1.exports);
  41818. var _types = types;
  41819. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41820. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41821. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41822. var Nesting = /*#__PURE__*/function (_Node) {
  41823. _inheritsLoose(Nesting, _Node);
  41824. function Nesting(opts) {
  41825. var _this;
  41826. _this = _Node.call(this, opts) || this;
  41827. _this.type = _types.NESTING;
  41828. _this.value = '&';
  41829. return _this;
  41830. }
  41831. return Nesting;
  41832. }(_node["default"]);
  41833. exports["default"] = Nesting;
  41834. module.exports = exports.default;
  41835. } (nesting$1, nesting$1.exports));
  41836. var sortAscending = {exports: {}};
  41837. (function (module, exports) {
  41838. exports.__esModule = true;
  41839. exports["default"] = sortAscending;
  41840. function sortAscending(list) {
  41841. return list.sort(function (a, b) {
  41842. return a - b;
  41843. });
  41844. }
  41845. module.exports = exports.default;
  41846. } (sortAscending, sortAscending.exports));
  41847. var tokenize = {};
  41848. var tokenTypes = {};
  41849. tokenTypes.__esModule = true;
  41850. tokenTypes.combinator = tokenTypes.word = tokenTypes.comment = tokenTypes.str = tokenTypes.tab = tokenTypes.newline = tokenTypes.feed = tokenTypes.cr = tokenTypes.backslash = tokenTypes.bang = tokenTypes.slash = tokenTypes.doubleQuote = tokenTypes.singleQuote = tokenTypes.space = tokenTypes.greaterThan = tokenTypes.pipe = tokenTypes.equals = tokenTypes.plus = tokenTypes.caret = tokenTypes.tilde = tokenTypes.dollar = tokenTypes.closeSquare = tokenTypes.openSquare = tokenTypes.closeParenthesis = tokenTypes.openParenthesis = tokenTypes.semicolon = tokenTypes.colon = tokenTypes.comma = tokenTypes.at = tokenTypes.asterisk = tokenTypes.ampersand = void 0;
  41851. var ampersand = 38; // `&`.charCodeAt(0);
  41852. tokenTypes.ampersand = ampersand;
  41853. var asterisk = 42; // `*`.charCodeAt(0);
  41854. tokenTypes.asterisk = asterisk;
  41855. var at = 64; // `@`.charCodeAt(0);
  41856. tokenTypes.at = at;
  41857. var comma = 44; // `,`.charCodeAt(0);
  41858. tokenTypes.comma = comma;
  41859. var colon = 58; // `:`.charCodeAt(0);
  41860. tokenTypes.colon = colon;
  41861. var semicolon = 59; // `;`.charCodeAt(0);
  41862. tokenTypes.semicolon = semicolon;
  41863. var openParenthesis = 40; // `(`.charCodeAt(0);
  41864. tokenTypes.openParenthesis = openParenthesis;
  41865. var closeParenthesis = 41; // `)`.charCodeAt(0);
  41866. tokenTypes.closeParenthesis = closeParenthesis;
  41867. var openSquare = 91; // `[`.charCodeAt(0);
  41868. tokenTypes.openSquare = openSquare;
  41869. var closeSquare = 93; // `]`.charCodeAt(0);
  41870. tokenTypes.closeSquare = closeSquare;
  41871. var dollar = 36; // `$`.charCodeAt(0);
  41872. tokenTypes.dollar = dollar;
  41873. var tilde = 126; // `~`.charCodeAt(0);
  41874. tokenTypes.tilde = tilde;
  41875. var caret = 94; // `^`.charCodeAt(0);
  41876. tokenTypes.caret = caret;
  41877. var plus = 43; // `+`.charCodeAt(0);
  41878. tokenTypes.plus = plus;
  41879. var equals = 61; // `=`.charCodeAt(0);
  41880. tokenTypes.equals = equals;
  41881. var pipe = 124; // `|`.charCodeAt(0);
  41882. tokenTypes.pipe = pipe;
  41883. var greaterThan = 62; // `>`.charCodeAt(0);
  41884. tokenTypes.greaterThan = greaterThan;
  41885. var space = 32; // ` `.charCodeAt(0);
  41886. tokenTypes.space = space;
  41887. var singleQuote = 39; // `'`.charCodeAt(0);
  41888. tokenTypes.singleQuote = singleQuote;
  41889. var doubleQuote = 34; // `"`.charCodeAt(0);
  41890. tokenTypes.doubleQuote = doubleQuote;
  41891. var slash = 47; // `/`.charCodeAt(0);
  41892. tokenTypes.slash = slash;
  41893. var bang = 33; // `!`.charCodeAt(0);
  41894. tokenTypes.bang = bang;
  41895. var backslash = 92; // '\\'.charCodeAt(0);
  41896. tokenTypes.backslash = backslash;
  41897. var cr = 13; // '\r'.charCodeAt(0);
  41898. tokenTypes.cr = cr;
  41899. var feed = 12; // '\f'.charCodeAt(0);
  41900. tokenTypes.feed = feed;
  41901. var newline = 10; // '\n'.charCodeAt(0);
  41902. tokenTypes.newline = newline;
  41903. var tab = 9; // '\t'.charCodeAt(0);
  41904. // Expose aliases primarily for readability.
  41905. tokenTypes.tab = tab;
  41906. var str = singleQuote; // No good single character representation!
  41907. tokenTypes.str = str;
  41908. var comment$1 = -1;
  41909. tokenTypes.comment = comment$1;
  41910. var word = -2;
  41911. tokenTypes.word = word;
  41912. var combinator$1 = -3;
  41913. tokenTypes.combinator = combinator$1;
  41914. (function (exports) {
  41915. exports.__esModule = true;
  41916. exports["default"] = tokenize;
  41917. exports.FIELDS = void 0;
  41918. var t = _interopRequireWildcard(tokenTypes);
  41919. var _unescapable, _wordDelimiters;
  41920. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  41921. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  41922. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  41923. var wordDelimiters = (_wordDelimiters = {}, _wordDelimiters[t.space] = true, _wordDelimiters[t.tab] = true, _wordDelimiters[t.newline] = true, _wordDelimiters[t.cr] = true, _wordDelimiters[t.feed] = true, _wordDelimiters[t.ampersand] = true, _wordDelimiters[t.asterisk] = true, _wordDelimiters[t.bang] = true, _wordDelimiters[t.comma] = true, _wordDelimiters[t.colon] = true, _wordDelimiters[t.semicolon] = true, _wordDelimiters[t.openParenthesis] = true, _wordDelimiters[t.closeParenthesis] = true, _wordDelimiters[t.openSquare] = true, _wordDelimiters[t.closeSquare] = true, _wordDelimiters[t.singleQuote] = true, _wordDelimiters[t.doubleQuote] = true, _wordDelimiters[t.plus] = true, _wordDelimiters[t.pipe] = true, _wordDelimiters[t.tilde] = true, _wordDelimiters[t.greaterThan] = true, _wordDelimiters[t.equals] = true, _wordDelimiters[t.dollar] = true, _wordDelimiters[t.caret] = true, _wordDelimiters[t.slash] = true, _wordDelimiters);
  41924. var hex = {};
  41925. var hexChars = "0123456789abcdefABCDEF";
  41926. for (var i = 0; i < hexChars.length; i++) {
  41927. hex[hexChars.charCodeAt(i)] = true;
  41928. }
  41929. /**
  41930. * Returns the last index of the bar css word
  41931. * @param {string} css The string in which the word begins
  41932. * @param {number} start The index into the string where word's first letter occurs
  41933. */
  41934. function consumeWord(css, start) {
  41935. var next = start;
  41936. var code;
  41937. do {
  41938. code = css.charCodeAt(next);
  41939. if (wordDelimiters[code]) {
  41940. return next - 1;
  41941. } else if (code === t.backslash) {
  41942. next = consumeEscape(css, next) + 1;
  41943. } else {
  41944. // All other characters are part of the word
  41945. next++;
  41946. }
  41947. } while (next < css.length);
  41948. return next - 1;
  41949. }
  41950. /**
  41951. * Returns the last index of the escape sequence
  41952. * @param {string} css The string in which the sequence begins
  41953. * @param {number} start The index into the string where escape character (`\`) occurs.
  41954. */
  41955. function consumeEscape(css, start) {
  41956. var next = start;
  41957. var code = css.charCodeAt(next + 1);
  41958. if (unescapable[code]) ; else if (hex[code]) {
  41959. var hexDigits = 0; // consume up to 6 hex chars
  41960. do {
  41961. next++;
  41962. hexDigits++;
  41963. code = css.charCodeAt(next + 1);
  41964. } while (hex[code] && hexDigits < 6); // if fewer than 6 hex chars, a trailing space ends the escape
  41965. if (hexDigits < 6 && code === t.space) {
  41966. next++;
  41967. }
  41968. } else {
  41969. // the next char is part of the current word
  41970. next++;
  41971. }
  41972. return next;
  41973. }
  41974. var FIELDS = {
  41975. TYPE: 0,
  41976. START_LINE: 1,
  41977. START_COL: 2,
  41978. END_LINE: 3,
  41979. END_COL: 4,
  41980. START_POS: 5,
  41981. END_POS: 6
  41982. };
  41983. exports.FIELDS = FIELDS;
  41984. function tokenize(input) {
  41985. var tokens = [];
  41986. var css = input.css.valueOf();
  41987. var _css = css,
  41988. length = _css.length;
  41989. var offset = -1;
  41990. var line = 1;
  41991. var start = 0;
  41992. var end = 0;
  41993. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  41994. function unclosed(what, fix) {
  41995. if (input.safe) {
  41996. // fyi: this is never set to true.
  41997. css += fix;
  41998. next = css.length - 1;
  41999. } else {
  42000. throw input.error('Unclosed ' + what, line, start - offset, start);
  42001. }
  42002. }
  42003. while (start < length) {
  42004. code = css.charCodeAt(start);
  42005. if (code === t.newline) {
  42006. offset = start;
  42007. line += 1;
  42008. }
  42009. switch (code) {
  42010. case t.space:
  42011. case t.tab:
  42012. case t.newline:
  42013. case t.cr:
  42014. case t.feed:
  42015. next = start;
  42016. do {
  42017. next += 1;
  42018. code = css.charCodeAt(next);
  42019. if (code === t.newline) {
  42020. offset = next;
  42021. line += 1;
  42022. }
  42023. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  42024. tokenType = t.space;
  42025. endLine = line;
  42026. endColumn = next - offset - 1;
  42027. end = next;
  42028. break;
  42029. case t.plus:
  42030. case t.greaterThan:
  42031. case t.tilde:
  42032. case t.pipe:
  42033. next = start;
  42034. do {
  42035. next += 1;
  42036. code = css.charCodeAt(next);
  42037. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  42038. tokenType = t.combinator;
  42039. endLine = line;
  42040. endColumn = start - offset;
  42041. end = next;
  42042. break;
  42043. // Consume these characters as single tokens.
  42044. case t.asterisk:
  42045. case t.ampersand:
  42046. case t.bang:
  42047. case t.comma:
  42048. case t.equals:
  42049. case t.dollar:
  42050. case t.caret:
  42051. case t.openSquare:
  42052. case t.closeSquare:
  42053. case t.colon:
  42054. case t.semicolon:
  42055. case t.openParenthesis:
  42056. case t.closeParenthesis:
  42057. next = start;
  42058. tokenType = code;
  42059. endLine = line;
  42060. endColumn = start - offset;
  42061. end = next + 1;
  42062. break;
  42063. case t.singleQuote:
  42064. case t.doubleQuote:
  42065. quote = code === t.singleQuote ? "'" : '"';
  42066. next = start;
  42067. do {
  42068. escaped = false;
  42069. next = css.indexOf(quote, next + 1);
  42070. if (next === -1) {
  42071. unclosed('quote', quote);
  42072. }
  42073. escapePos = next;
  42074. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  42075. escapePos -= 1;
  42076. escaped = !escaped;
  42077. }
  42078. } while (escaped);
  42079. tokenType = t.str;
  42080. endLine = line;
  42081. endColumn = start - offset;
  42082. end = next + 1;
  42083. break;
  42084. default:
  42085. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  42086. next = css.indexOf('*/', start + 2) + 1;
  42087. if (next === 0) {
  42088. unclosed('comment', '*/');
  42089. }
  42090. content = css.slice(start, next + 1);
  42091. lines = content.split('\n');
  42092. last = lines.length - 1;
  42093. if (last > 0) {
  42094. nextLine = line + last;
  42095. nextOffset = next - lines[last].length;
  42096. } else {
  42097. nextLine = line;
  42098. nextOffset = offset;
  42099. }
  42100. tokenType = t.comment;
  42101. line = nextLine;
  42102. endLine = nextLine;
  42103. endColumn = next - nextOffset;
  42104. } else if (code === t.slash) {
  42105. next = start;
  42106. tokenType = code;
  42107. endLine = line;
  42108. endColumn = start - offset;
  42109. end = next + 1;
  42110. } else {
  42111. next = consumeWord(css, start);
  42112. tokenType = t.word;
  42113. endLine = line;
  42114. endColumn = next - offset;
  42115. }
  42116. end = next + 1;
  42117. break;
  42118. } // Ensure that the token structure remains consistent
  42119. tokens.push([tokenType, // [0] Token type
  42120. line, // [1] Starting line
  42121. start - offset, // [2] Starting column
  42122. endLine, // [3] Ending line
  42123. endColumn, // [4] Ending column
  42124. start, // [5] Start position / Source index
  42125. end // [6] End position
  42126. ]); // Reset offset for the next token
  42127. if (nextOffset) {
  42128. offset = nextOffset;
  42129. nextOffset = null;
  42130. }
  42131. start = end;
  42132. }
  42133. return tokens;
  42134. }
  42135. } (tokenize));
  42136. (function (module, exports) {
  42137. exports.__esModule = true;
  42138. exports["default"] = void 0;
  42139. var _root = _interopRequireDefault(root$1.exports);
  42140. var _selector = _interopRequireDefault(selector$1.exports);
  42141. var _className = _interopRequireDefault(className$1.exports);
  42142. var _comment = _interopRequireDefault(comment$2.exports);
  42143. var _id = _interopRequireDefault(id$1.exports);
  42144. var _tag = _interopRequireDefault(tag$1.exports);
  42145. var _string = _interopRequireDefault(string$1.exports);
  42146. var _pseudo = _interopRequireDefault(pseudo$1.exports);
  42147. var _attribute = _interopRequireWildcard(attribute$1);
  42148. var _universal = _interopRequireDefault(universal$1.exports);
  42149. var _combinator = _interopRequireDefault(combinator$2.exports);
  42150. var _nesting = _interopRequireDefault(nesting$1.exports);
  42151. var _sortAscending = _interopRequireDefault(sortAscending.exports);
  42152. var _tokenize = _interopRequireWildcard(tokenize);
  42153. var tokens = _interopRequireWildcard(tokenTypes);
  42154. var types$1 = _interopRequireWildcard(types);
  42155. var _util = util;
  42156. var _WHITESPACE_TOKENS, _Object$assign;
  42157. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  42158. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  42159. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  42160. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  42161. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  42162. var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS);
  42163. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  42164. function tokenStart(token) {
  42165. return {
  42166. line: token[_tokenize.FIELDS.START_LINE],
  42167. column: token[_tokenize.FIELDS.START_COL]
  42168. };
  42169. }
  42170. function tokenEnd(token) {
  42171. return {
  42172. line: token[_tokenize.FIELDS.END_LINE],
  42173. column: token[_tokenize.FIELDS.END_COL]
  42174. };
  42175. }
  42176. function getSource(startLine, startColumn, endLine, endColumn) {
  42177. return {
  42178. start: {
  42179. line: startLine,
  42180. column: startColumn
  42181. },
  42182. end: {
  42183. line: endLine,
  42184. column: endColumn
  42185. }
  42186. };
  42187. }
  42188. function getTokenSource(token) {
  42189. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  42190. }
  42191. function getTokenSourceSpan(startToken, endToken) {
  42192. if (!startToken) {
  42193. return undefined;
  42194. }
  42195. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  42196. }
  42197. function unescapeProp(node, prop) {
  42198. var value = node[prop];
  42199. if (typeof value !== "string") {
  42200. return;
  42201. }
  42202. if (value.indexOf("\\") !== -1) {
  42203. (0, _util.ensureObject)(node, 'raws');
  42204. node[prop] = (0, _util.unesc)(value);
  42205. if (node.raws[prop] === undefined) {
  42206. node.raws[prop] = value;
  42207. }
  42208. }
  42209. return node;
  42210. }
  42211. function indexesOf(array, item) {
  42212. var i = -1;
  42213. var indexes = [];
  42214. while ((i = array.indexOf(item, i + 1)) !== -1) {
  42215. indexes.push(i);
  42216. }
  42217. return indexes;
  42218. }
  42219. function uniqs() {
  42220. var list = Array.prototype.concat.apply([], arguments);
  42221. return list.filter(function (item, i) {
  42222. return i === list.indexOf(item);
  42223. });
  42224. }
  42225. var Parser = /*#__PURE__*/function () {
  42226. function Parser(rule, options) {
  42227. if (options === void 0) {
  42228. options = {};
  42229. }
  42230. this.rule = rule;
  42231. this.options = Object.assign({
  42232. lossy: false,
  42233. safe: false
  42234. }, options);
  42235. this.position = 0;
  42236. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  42237. this.tokens = (0, _tokenize["default"])({
  42238. css: this.css,
  42239. error: this._errorGenerator(),
  42240. safe: this.options.safe
  42241. });
  42242. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  42243. this.root = new _root["default"]({
  42244. source: rootSource
  42245. });
  42246. this.root.errorGenerator = this._errorGenerator();
  42247. var selector = new _selector["default"]({
  42248. source: {
  42249. start: {
  42250. line: 1,
  42251. column: 1
  42252. }
  42253. }
  42254. });
  42255. this.root.append(selector);
  42256. this.current = selector;
  42257. this.loop();
  42258. }
  42259. var _proto = Parser.prototype;
  42260. _proto._errorGenerator = function _errorGenerator() {
  42261. var _this = this;
  42262. return function (message, errorOptions) {
  42263. if (typeof _this.rule === 'string') {
  42264. return new Error(message);
  42265. }
  42266. return _this.rule.error(message, errorOptions);
  42267. };
  42268. };
  42269. _proto.attribute = function attribute() {
  42270. var attr = [];
  42271. var startingToken = this.currToken;
  42272. this.position++;
  42273. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  42274. attr.push(this.currToken);
  42275. this.position++;
  42276. }
  42277. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  42278. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  42279. }
  42280. var len = attr.length;
  42281. var node = {
  42282. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  42283. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  42284. };
  42285. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  42286. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  42287. }
  42288. var pos = 0;
  42289. var spaceBefore = '';
  42290. var commentBefore = '';
  42291. var lastAdded = null;
  42292. var spaceAfterMeaningfulToken = false;
  42293. while (pos < len) {
  42294. var token = attr[pos];
  42295. var content = this.content(token);
  42296. var next = attr[pos + 1];
  42297. switch (token[_tokenize.FIELDS.TYPE]) {
  42298. case tokens.space:
  42299. // if (
  42300. // len === 1 ||
  42301. // pos === 0 && this.content(next) === '|'
  42302. // ) {
  42303. // return this.expected('attribute', token[TOKEN.START_POS], content);
  42304. // }
  42305. spaceAfterMeaningfulToken = true;
  42306. if (this.options.lossy) {
  42307. break;
  42308. }
  42309. if (lastAdded) {
  42310. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  42311. var prevContent = node.spaces[lastAdded].after || '';
  42312. node.spaces[lastAdded].after = prevContent + content;
  42313. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  42314. if (existingComment) {
  42315. node.raws.spaces[lastAdded].after = existingComment + content;
  42316. }
  42317. } else {
  42318. spaceBefore = spaceBefore + content;
  42319. commentBefore = commentBefore + content;
  42320. }
  42321. break;
  42322. case tokens.asterisk:
  42323. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  42324. node.operator = content;
  42325. lastAdded = 'operator';
  42326. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  42327. if (spaceBefore) {
  42328. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  42329. node.spaces.attribute.before = spaceBefore;
  42330. spaceBefore = '';
  42331. }
  42332. if (commentBefore) {
  42333. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  42334. node.raws.spaces.attribute.before = spaceBefore;
  42335. commentBefore = '';
  42336. }
  42337. node.namespace = (node.namespace || "") + content;
  42338. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  42339. if (rawValue) {
  42340. node.raws.namespace += content;
  42341. }
  42342. lastAdded = 'namespace';
  42343. }
  42344. spaceAfterMeaningfulToken = false;
  42345. break;
  42346. case tokens.dollar:
  42347. if (lastAdded === "value") {
  42348. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  42349. node.value += "$";
  42350. if (oldRawValue) {
  42351. node.raws.value = oldRawValue + "$";
  42352. }
  42353. break;
  42354. }
  42355. // Falls through
  42356. case tokens.caret:
  42357. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  42358. node.operator = content;
  42359. lastAdded = 'operator';
  42360. }
  42361. spaceAfterMeaningfulToken = false;
  42362. break;
  42363. case tokens.combinator:
  42364. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  42365. node.operator = content;
  42366. lastAdded = 'operator';
  42367. }
  42368. if (content !== '|') {
  42369. spaceAfterMeaningfulToken = false;
  42370. break;
  42371. }
  42372. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  42373. node.operator = content;
  42374. lastAdded = 'operator';
  42375. } else if (!node.namespace && !node.attribute) {
  42376. node.namespace = true;
  42377. }
  42378. spaceAfterMeaningfulToken = false;
  42379. break;
  42380. case tokens.word:
  42381. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals && // this look-ahead probably fails with comment nodes involved.
  42382. !node.operator && !node.namespace) {
  42383. node.namespace = content;
  42384. lastAdded = 'namespace';
  42385. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  42386. if (spaceBefore) {
  42387. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  42388. node.spaces.attribute.before = spaceBefore;
  42389. spaceBefore = '';
  42390. }
  42391. if (commentBefore) {
  42392. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  42393. node.raws.spaces.attribute.before = commentBefore;
  42394. commentBefore = '';
  42395. }
  42396. node.attribute = (node.attribute || "") + content;
  42397. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  42398. if (_rawValue) {
  42399. node.raws.attribute += content;
  42400. }
  42401. lastAdded = 'attribute';
  42402. } else if (!node.value && node.value !== "" || lastAdded === "value" && !spaceAfterMeaningfulToken) {
  42403. var _unescaped = (0, _util.unesc)(content);
  42404. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  42405. var oldValue = node.value || '';
  42406. node.value = oldValue + _unescaped;
  42407. node.quoteMark = null;
  42408. if (_unescaped !== content || _oldRawValue) {
  42409. (0, _util.ensureObject)(node, 'raws');
  42410. node.raws.value = (_oldRawValue || oldValue) + content;
  42411. }
  42412. lastAdded = 'value';
  42413. } else {
  42414. var insensitive = content === 'i' || content === "I";
  42415. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  42416. node.insensitive = insensitive;
  42417. if (!insensitive || content === "I") {
  42418. (0, _util.ensureObject)(node, 'raws');
  42419. node.raws.insensitiveFlag = content;
  42420. }
  42421. lastAdded = 'insensitive';
  42422. if (spaceBefore) {
  42423. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  42424. node.spaces.insensitive.before = spaceBefore;
  42425. spaceBefore = '';
  42426. }
  42427. if (commentBefore) {
  42428. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  42429. node.raws.spaces.insensitive.before = commentBefore;
  42430. commentBefore = '';
  42431. }
  42432. } else if (node.value || node.value === '') {
  42433. lastAdded = 'value';
  42434. node.value += content;
  42435. if (node.raws.value) {
  42436. node.raws.value += content;
  42437. }
  42438. }
  42439. }
  42440. spaceAfterMeaningfulToken = false;
  42441. break;
  42442. case tokens.str:
  42443. if (!node.attribute || !node.operator) {
  42444. return this.error("Expected an attribute followed by an operator preceding the string.", {
  42445. index: token[_tokenize.FIELDS.START_POS]
  42446. });
  42447. }
  42448. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  42449. unescaped = _unescapeValue.unescaped,
  42450. quoteMark = _unescapeValue.quoteMark;
  42451. node.value = unescaped;
  42452. node.quoteMark = quoteMark;
  42453. lastAdded = 'value';
  42454. (0, _util.ensureObject)(node, 'raws');
  42455. node.raws.value = content;
  42456. spaceAfterMeaningfulToken = false;
  42457. break;
  42458. case tokens.equals:
  42459. if (!node.attribute) {
  42460. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  42461. }
  42462. if (node.value) {
  42463. return this.error('Unexpected "=" found; an operator was already defined.', {
  42464. index: token[_tokenize.FIELDS.START_POS]
  42465. });
  42466. }
  42467. node.operator = node.operator ? node.operator + content : content;
  42468. lastAdded = 'operator';
  42469. spaceAfterMeaningfulToken = false;
  42470. break;
  42471. case tokens.comment:
  42472. if (lastAdded) {
  42473. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  42474. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  42475. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  42476. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  42477. node.raws.spaces[lastAdded].after = rawLastComment + content;
  42478. } else {
  42479. var lastValue = node[lastAdded] || '';
  42480. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  42481. (0, _util.ensureObject)(node, 'raws');
  42482. node.raws[lastAdded] = rawLastValue + content;
  42483. }
  42484. } else {
  42485. commentBefore = commentBefore + content;
  42486. }
  42487. break;
  42488. default:
  42489. return this.error("Unexpected \"" + content + "\" found.", {
  42490. index: token[_tokenize.FIELDS.START_POS]
  42491. });
  42492. }
  42493. pos++;
  42494. }
  42495. unescapeProp(node, "attribute");
  42496. unescapeProp(node, "namespace");
  42497. this.newNode(new _attribute["default"](node));
  42498. this.position++;
  42499. }
  42500. /**
  42501. * return a node containing meaningless garbage up to (but not including) the specified token position.
  42502. * if the token position is negative, all remaining tokens are consumed.
  42503. *
  42504. * This returns an array containing a single string node if all whitespace,
  42505. * otherwise an array of comment nodes with space before and after.
  42506. *
  42507. * These tokens are not added to the current selector, the caller can add them or use them to amend
  42508. * a previous node's space metadata.
  42509. *
  42510. * In lossy mode, this returns only comments.
  42511. */
  42512. ;
  42513. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  42514. if (stopPosition < 0) {
  42515. stopPosition = this.tokens.length;
  42516. }
  42517. var startPosition = this.position;
  42518. var nodes = [];
  42519. var space = "";
  42520. var lastComment = undefined;
  42521. do {
  42522. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  42523. if (!this.options.lossy) {
  42524. space += this.content();
  42525. }
  42526. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  42527. var spaces = {};
  42528. if (space) {
  42529. spaces.before = space;
  42530. space = "";
  42531. }
  42532. lastComment = new _comment["default"]({
  42533. value: this.content(),
  42534. source: getTokenSource(this.currToken),
  42535. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  42536. spaces: spaces
  42537. });
  42538. nodes.push(lastComment);
  42539. }
  42540. } while (++this.position < stopPosition);
  42541. if (space) {
  42542. if (lastComment) {
  42543. lastComment.spaces.after = space;
  42544. } else if (!this.options.lossy) {
  42545. var firstToken = this.tokens[startPosition];
  42546. var lastToken = this.tokens[this.position - 1];
  42547. nodes.push(new _string["default"]({
  42548. value: '',
  42549. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  42550. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  42551. spaces: {
  42552. before: space,
  42553. after: ''
  42554. }
  42555. }));
  42556. }
  42557. }
  42558. return nodes;
  42559. }
  42560. /**
  42561. *
  42562. * @param {*} nodes
  42563. */
  42564. ;
  42565. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  42566. var _this2 = this;
  42567. if (requiredSpace === void 0) {
  42568. requiredSpace = false;
  42569. }
  42570. var space = "";
  42571. var rawSpace = "";
  42572. nodes.forEach(function (n) {
  42573. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  42574. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  42575. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  42576. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  42577. });
  42578. if (rawSpace === space) {
  42579. rawSpace = undefined;
  42580. }
  42581. var result = {
  42582. space: space,
  42583. rawSpace: rawSpace
  42584. };
  42585. return result;
  42586. };
  42587. _proto.isNamedCombinator = function isNamedCombinator(position) {
  42588. if (position === void 0) {
  42589. position = this.position;
  42590. }
  42591. return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash;
  42592. };
  42593. _proto.namedCombinator = function namedCombinator() {
  42594. if (this.isNamedCombinator()) {
  42595. var nameRaw = this.content(this.tokens[this.position + 1]);
  42596. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  42597. var raws = {};
  42598. if (name !== nameRaw) {
  42599. raws.value = "/" + nameRaw + "/";
  42600. }
  42601. var node = new _combinator["default"]({
  42602. value: "/" + name + "/",
  42603. source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]),
  42604. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  42605. raws: raws
  42606. });
  42607. this.position = this.position + 3;
  42608. return node;
  42609. } else {
  42610. this.unexpected();
  42611. }
  42612. };
  42613. _proto.combinator = function combinator() {
  42614. var _this3 = this;
  42615. if (this.content() === '|') {
  42616. return this.namespace();
  42617. } // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  42618. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  42619. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
  42620. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  42621. if (nodes.length > 0) {
  42622. var last = this.current.last;
  42623. if (last) {
  42624. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  42625. space = _this$convertWhitespa.space,
  42626. rawSpace = _this$convertWhitespa.rawSpace;
  42627. if (rawSpace !== undefined) {
  42628. last.rawSpaceAfter += rawSpace;
  42629. }
  42630. last.spaces.after += space;
  42631. } else {
  42632. nodes.forEach(function (n) {
  42633. return _this3.newNode(n);
  42634. });
  42635. }
  42636. }
  42637. return;
  42638. }
  42639. var firstToken = this.currToken;
  42640. var spaceOrDescendantSelectorNodes = undefined;
  42641. if (nextSigTokenPos > this.position) {
  42642. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  42643. }
  42644. var node;
  42645. if (this.isNamedCombinator()) {
  42646. node = this.namedCombinator();
  42647. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  42648. node = new _combinator["default"]({
  42649. value: this.content(),
  42650. source: getTokenSource(this.currToken),
  42651. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  42652. });
  42653. this.position++;
  42654. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  42655. this.unexpected();
  42656. }
  42657. if (node) {
  42658. if (spaceOrDescendantSelectorNodes) {
  42659. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  42660. _space = _this$convertWhitespa2.space,
  42661. _rawSpace = _this$convertWhitespa2.rawSpace;
  42662. node.spaces.before = _space;
  42663. node.rawSpaceBefore = _rawSpace;
  42664. }
  42665. } else {
  42666. // descendant combinator
  42667. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  42668. _space2 = _this$convertWhitespa3.space,
  42669. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  42670. if (!_rawSpace2) {
  42671. _rawSpace2 = _space2;
  42672. }
  42673. var spaces = {};
  42674. var raws = {
  42675. spaces: {}
  42676. };
  42677. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  42678. spaces.before = _space2.slice(0, _space2.length - 1);
  42679. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  42680. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  42681. spaces.after = _space2.slice(1);
  42682. raws.spaces.after = _rawSpace2.slice(1);
  42683. } else {
  42684. raws.value = _rawSpace2;
  42685. }
  42686. node = new _combinator["default"]({
  42687. value: ' ',
  42688. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  42689. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  42690. spaces: spaces,
  42691. raws: raws
  42692. });
  42693. }
  42694. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  42695. node.spaces.after = this.optionalSpace(this.content());
  42696. this.position++;
  42697. }
  42698. return this.newNode(node);
  42699. };
  42700. _proto.comma = function comma() {
  42701. if (this.position === this.tokens.length - 1) {
  42702. this.root.trailingComma = true;
  42703. this.position++;
  42704. return;
  42705. }
  42706. this.current._inferEndPosition();
  42707. var selector = new _selector["default"]({
  42708. source: {
  42709. start: tokenStart(this.tokens[this.position + 1])
  42710. }
  42711. });
  42712. this.current.parent.append(selector);
  42713. this.current = selector;
  42714. this.position++;
  42715. };
  42716. _proto.comment = function comment() {
  42717. var current = this.currToken;
  42718. this.newNode(new _comment["default"]({
  42719. value: this.content(),
  42720. source: getTokenSource(current),
  42721. sourceIndex: current[_tokenize.FIELDS.START_POS]
  42722. }));
  42723. this.position++;
  42724. };
  42725. _proto.error = function error(message, opts) {
  42726. throw this.root.error(message, opts);
  42727. };
  42728. _proto.missingBackslash = function missingBackslash() {
  42729. return this.error('Expected a backslash preceding the semicolon.', {
  42730. index: this.currToken[_tokenize.FIELDS.START_POS]
  42731. });
  42732. };
  42733. _proto.missingParenthesis = function missingParenthesis() {
  42734. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  42735. };
  42736. _proto.missingSquareBracket = function missingSquareBracket() {
  42737. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  42738. };
  42739. _proto.unexpected = function unexpected() {
  42740. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  42741. };
  42742. _proto.namespace = function namespace() {
  42743. var before = this.prevToken && this.content(this.prevToken) || true;
  42744. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  42745. this.position++;
  42746. return this.word(before);
  42747. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  42748. this.position++;
  42749. return this.universal(before);
  42750. }
  42751. };
  42752. _proto.nesting = function nesting() {
  42753. if (this.nextToken) {
  42754. var nextContent = this.content(this.nextToken);
  42755. if (nextContent === "|") {
  42756. this.position++;
  42757. return;
  42758. }
  42759. }
  42760. var current = this.currToken;
  42761. this.newNode(new _nesting["default"]({
  42762. value: this.content(),
  42763. source: getTokenSource(current),
  42764. sourceIndex: current[_tokenize.FIELDS.START_POS]
  42765. }));
  42766. this.position++;
  42767. };
  42768. _proto.parentheses = function parentheses() {
  42769. var last = this.current.last;
  42770. var unbalanced = 1;
  42771. this.position++;
  42772. if (last && last.type === types$1.PSEUDO) {
  42773. var selector = new _selector["default"]({
  42774. source: {
  42775. start: tokenStart(this.tokens[this.position - 1])
  42776. }
  42777. });
  42778. var cache = this.current;
  42779. last.append(selector);
  42780. this.current = selector;
  42781. while (this.position < this.tokens.length && unbalanced) {
  42782. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  42783. unbalanced++;
  42784. }
  42785. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  42786. unbalanced--;
  42787. }
  42788. if (unbalanced) {
  42789. this.parse();
  42790. } else {
  42791. this.current.source.end = tokenEnd(this.currToken);
  42792. this.current.parent.source.end = tokenEnd(this.currToken);
  42793. this.position++;
  42794. }
  42795. }
  42796. this.current = cache;
  42797. } else {
  42798. // I think this case should be an error. It's used to implement a basic parse of media queries
  42799. // but I don't think it's a good idea.
  42800. var parenStart = this.currToken;
  42801. var parenValue = "(";
  42802. var parenEnd;
  42803. while (this.position < this.tokens.length && unbalanced) {
  42804. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  42805. unbalanced++;
  42806. }
  42807. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  42808. unbalanced--;
  42809. }
  42810. parenEnd = this.currToken;
  42811. parenValue += this.parseParenthesisToken(this.currToken);
  42812. this.position++;
  42813. }
  42814. if (last) {
  42815. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  42816. } else {
  42817. this.newNode(new _string["default"]({
  42818. value: parenValue,
  42819. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  42820. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  42821. }));
  42822. }
  42823. }
  42824. if (unbalanced) {
  42825. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  42826. }
  42827. };
  42828. _proto.pseudo = function pseudo() {
  42829. var _this4 = this;
  42830. var pseudoStr = '';
  42831. var startingToken = this.currToken;
  42832. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  42833. pseudoStr += this.content();
  42834. this.position++;
  42835. }
  42836. if (!this.currToken) {
  42837. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  42838. }
  42839. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  42840. this.splitWord(false, function (first, length) {
  42841. pseudoStr += first;
  42842. _this4.newNode(new _pseudo["default"]({
  42843. value: pseudoStr,
  42844. source: getTokenSourceSpan(startingToken, _this4.currToken),
  42845. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  42846. }));
  42847. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  42848. _this4.error('Misplaced parenthesis.', {
  42849. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  42850. });
  42851. }
  42852. });
  42853. } else {
  42854. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  42855. }
  42856. };
  42857. _proto.space = function space() {
  42858. var content = this.content(); // Handle space before and after the selector
  42859. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  42860. return node.type === 'comment';
  42861. })) {
  42862. this.spaces = this.optionalSpace(content);
  42863. this.position++;
  42864. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  42865. this.current.last.spaces.after = this.optionalSpace(content);
  42866. this.position++;
  42867. } else {
  42868. this.combinator();
  42869. }
  42870. };
  42871. _proto.string = function string() {
  42872. var current = this.currToken;
  42873. this.newNode(new _string["default"]({
  42874. value: this.content(),
  42875. source: getTokenSource(current),
  42876. sourceIndex: current[_tokenize.FIELDS.START_POS]
  42877. }));
  42878. this.position++;
  42879. };
  42880. _proto.universal = function universal(namespace) {
  42881. var nextToken = this.nextToken;
  42882. if (nextToken && this.content(nextToken) === '|') {
  42883. this.position++;
  42884. return this.namespace();
  42885. }
  42886. var current = this.currToken;
  42887. this.newNode(new _universal["default"]({
  42888. value: this.content(),
  42889. source: getTokenSource(current),
  42890. sourceIndex: current[_tokenize.FIELDS.START_POS]
  42891. }), namespace);
  42892. this.position++;
  42893. };
  42894. _proto.splitWord = function splitWord(namespace, firstCallback) {
  42895. var _this5 = this;
  42896. var nextToken = this.nextToken;
  42897. var word = this.content();
  42898. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  42899. this.position++;
  42900. var current = this.content();
  42901. word += current;
  42902. if (current.lastIndexOf('\\') === current.length - 1) {
  42903. var next = this.nextToken;
  42904. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  42905. word += this.requiredSpace(this.content(next));
  42906. this.position++;
  42907. }
  42908. }
  42909. nextToken = this.nextToken;
  42910. }
  42911. var hasClass = indexesOf(word, '.').filter(function (i) {
  42912. // Allow escaped dot within class name
  42913. var escapedDot = word[i - 1] === '\\'; // Allow decimal numbers percent in @keyframes
  42914. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  42915. return !escapedDot && !isKeyframesPercent;
  42916. });
  42917. var hasId = indexesOf(word, '#').filter(function (i) {
  42918. return word[i - 1] !== '\\';
  42919. }); // Eliminate Sass interpolations from the list of id indexes
  42920. var interpolations = indexesOf(word, '#{');
  42921. if (interpolations.length) {
  42922. hasId = hasId.filter(function (hashIndex) {
  42923. return !~interpolations.indexOf(hashIndex);
  42924. });
  42925. }
  42926. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  42927. indices.forEach(function (ind, i) {
  42928. var index = indices[i + 1] || word.length;
  42929. var value = word.slice(ind, index);
  42930. if (i === 0 && firstCallback) {
  42931. return firstCallback.call(_this5, value, indices.length);
  42932. }
  42933. var node;
  42934. var current = _this5.currToken;
  42935. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  42936. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  42937. if (~hasClass.indexOf(ind)) {
  42938. var classNameOpts = {
  42939. value: value.slice(1),
  42940. source: source,
  42941. sourceIndex: sourceIndex
  42942. };
  42943. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  42944. } else if (~hasId.indexOf(ind)) {
  42945. var idOpts = {
  42946. value: value.slice(1),
  42947. source: source,
  42948. sourceIndex: sourceIndex
  42949. };
  42950. node = new _id["default"](unescapeProp(idOpts, "value"));
  42951. } else {
  42952. var tagOpts = {
  42953. value: value,
  42954. source: source,
  42955. sourceIndex: sourceIndex
  42956. };
  42957. unescapeProp(tagOpts, "value");
  42958. node = new _tag["default"](tagOpts);
  42959. }
  42960. _this5.newNode(node, namespace); // Ensure that the namespace is used only once
  42961. namespace = null;
  42962. });
  42963. this.position++;
  42964. };
  42965. _proto.word = function word(namespace) {
  42966. var nextToken = this.nextToken;
  42967. if (nextToken && this.content(nextToken) === '|') {
  42968. this.position++;
  42969. return this.namespace();
  42970. }
  42971. return this.splitWord(namespace);
  42972. };
  42973. _proto.loop = function loop() {
  42974. while (this.position < this.tokens.length) {
  42975. this.parse(true);
  42976. }
  42977. this.current._inferEndPosition();
  42978. return this.root;
  42979. };
  42980. _proto.parse = function parse(throwOnParenthesis) {
  42981. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  42982. case tokens.space:
  42983. this.space();
  42984. break;
  42985. case tokens.comment:
  42986. this.comment();
  42987. break;
  42988. case tokens.openParenthesis:
  42989. this.parentheses();
  42990. break;
  42991. case tokens.closeParenthesis:
  42992. if (throwOnParenthesis) {
  42993. this.missingParenthesis();
  42994. }
  42995. break;
  42996. case tokens.openSquare:
  42997. this.attribute();
  42998. break;
  42999. case tokens.dollar:
  43000. case tokens.caret:
  43001. case tokens.equals:
  43002. case tokens.word:
  43003. this.word();
  43004. break;
  43005. case tokens.colon:
  43006. this.pseudo();
  43007. break;
  43008. case tokens.comma:
  43009. this.comma();
  43010. break;
  43011. case tokens.asterisk:
  43012. this.universal();
  43013. break;
  43014. case tokens.ampersand:
  43015. this.nesting();
  43016. break;
  43017. case tokens.slash:
  43018. case tokens.combinator:
  43019. this.combinator();
  43020. break;
  43021. case tokens.str:
  43022. this.string();
  43023. break;
  43024. // These cases throw; no break needed.
  43025. case tokens.closeSquare:
  43026. this.missingSquareBracket();
  43027. case tokens.semicolon:
  43028. this.missingBackslash();
  43029. default:
  43030. this.unexpected();
  43031. }
  43032. }
  43033. /**
  43034. * Helpers
  43035. */
  43036. ;
  43037. _proto.expected = function expected(description, index, found) {
  43038. if (Array.isArray(description)) {
  43039. var last = description.pop();
  43040. description = description.join(', ') + " or " + last;
  43041. }
  43042. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  43043. if (!found) {
  43044. return this.error("Expected " + an + " " + description + ".", {
  43045. index: index
  43046. });
  43047. }
  43048. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  43049. index: index
  43050. });
  43051. };
  43052. _proto.requiredSpace = function requiredSpace(space) {
  43053. return this.options.lossy ? ' ' : space;
  43054. };
  43055. _proto.optionalSpace = function optionalSpace(space) {
  43056. return this.options.lossy ? '' : space;
  43057. };
  43058. _proto.lossySpace = function lossySpace(space, required) {
  43059. if (this.options.lossy) {
  43060. return required ? ' ' : '';
  43061. } else {
  43062. return space;
  43063. }
  43064. };
  43065. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  43066. var content = this.content(token);
  43067. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  43068. return this.requiredSpace(content);
  43069. } else {
  43070. return content;
  43071. }
  43072. };
  43073. _proto.newNode = function newNode(node, namespace) {
  43074. if (namespace) {
  43075. if (/^ +$/.test(namespace)) {
  43076. if (!this.options.lossy) {
  43077. this.spaces = (this.spaces || '') + namespace;
  43078. }
  43079. namespace = true;
  43080. }
  43081. node.namespace = namespace;
  43082. unescapeProp(node, "namespace");
  43083. }
  43084. if (this.spaces) {
  43085. node.spaces.before = this.spaces;
  43086. this.spaces = '';
  43087. }
  43088. return this.current.append(node);
  43089. };
  43090. _proto.content = function content(token) {
  43091. if (token === void 0) {
  43092. token = this.currToken;
  43093. }
  43094. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  43095. };
  43096. /**
  43097. * returns the index of the next non-whitespace, non-comment token.
  43098. * returns -1 if no meaningful token is found.
  43099. */
  43100. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  43101. if (startPosition === void 0) {
  43102. startPosition = this.position + 1;
  43103. }
  43104. var searchPosition = startPosition;
  43105. while (searchPosition < this.tokens.length) {
  43106. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  43107. searchPosition++;
  43108. continue;
  43109. } else {
  43110. return searchPosition;
  43111. }
  43112. }
  43113. return -1;
  43114. };
  43115. _createClass(Parser, [{
  43116. key: "currToken",
  43117. get: function get() {
  43118. return this.tokens[this.position];
  43119. }
  43120. }, {
  43121. key: "nextToken",
  43122. get: function get() {
  43123. return this.tokens[this.position + 1];
  43124. }
  43125. }, {
  43126. key: "prevToken",
  43127. get: function get() {
  43128. return this.tokens[this.position - 1];
  43129. }
  43130. }]);
  43131. return Parser;
  43132. }();
  43133. exports["default"] = Parser;
  43134. module.exports = exports.default;
  43135. } (parser, parser.exports));
  43136. (function (module, exports) {
  43137. exports.__esModule = true;
  43138. exports["default"] = void 0;
  43139. var _parser = _interopRequireDefault(parser.exports);
  43140. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  43141. var Processor = /*#__PURE__*/function () {
  43142. function Processor(func, options) {
  43143. this.func = func || function noop() {};
  43144. this.funcRes = null;
  43145. this.options = options;
  43146. }
  43147. var _proto = Processor.prototype;
  43148. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  43149. if (options === void 0) {
  43150. options = {};
  43151. }
  43152. var merged = Object.assign({}, this.options, options);
  43153. if (merged.updateSelector === false) {
  43154. return false;
  43155. } else {
  43156. return typeof rule !== "string";
  43157. }
  43158. };
  43159. _proto._isLossy = function _isLossy(options) {
  43160. if (options === void 0) {
  43161. options = {};
  43162. }
  43163. var merged = Object.assign({}, this.options, options);
  43164. if (merged.lossless === false) {
  43165. return true;
  43166. } else {
  43167. return false;
  43168. }
  43169. };
  43170. _proto._root = function _root(rule, options) {
  43171. if (options === void 0) {
  43172. options = {};
  43173. }
  43174. var parser = new _parser["default"](rule, this._parseOptions(options));
  43175. return parser.root;
  43176. };
  43177. _proto._parseOptions = function _parseOptions(options) {
  43178. return {
  43179. lossy: this._isLossy(options)
  43180. };
  43181. };
  43182. _proto._run = function _run(rule, options) {
  43183. var _this = this;
  43184. if (options === void 0) {
  43185. options = {};
  43186. }
  43187. return new Promise(function (resolve, reject) {
  43188. try {
  43189. var root = _this._root(rule, options);
  43190. Promise.resolve(_this.func(root)).then(function (transform) {
  43191. var string = undefined;
  43192. if (_this._shouldUpdateSelector(rule, options)) {
  43193. string = root.toString();
  43194. rule.selector = string;
  43195. }
  43196. return {
  43197. transform: transform,
  43198. root: root,
  43199. string: string
  43200. };
  43201. }).then(resolve, reject);
  43202. } catch (e) {
  43203. reject(e);
  43204. return;
  43205. }
  43206. });
  43207. };
  43208. _proto._runSync = function _runSync(rule, options) {
  43209. if (options === void 0) {
  43210. options = {};
  43211. }
  43212. var root = this._root(rule, options);
  43213. var transform = this.func(root);
  43214. if (transform && typeof transform.then === "function") {
  43215. throw new Error("Selector processor returned a promise to a synchronous call.");
  43216. }
  43217. var string = undefined;
  43218. if (options.updateSelector && typeof rule !== "string") {
  43219. string = root.toString();
  43220. rule.selector = string;
  43221. }
  43222. return {
  43223. transform: transform,
  43224. root: root,
  43225. string: string
  43226. };
  43227. }
  43228. /**
  43229. * Process rule into a selector AST.
  43230. *
  43231. * @param rule {postcss.Rule | string} The css selector to be processed
  43232. * @param options The options for processing
  43233. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  43234. */
  43235. ;
  43236. _proto.ast = function ast(rule, options) {
  43237. return this._run(rule, options).then(function (result) {
  43238. return result.root;
  43239. });
  43240. }
  43241. /**
  43242. * Process rule into a selector AST synchronously.
  43243. *
  43244. * @param rule {postcss.Rule | string} The css selector to be processed
  43245. * @param options The options for processing
  43246. * @returns {parser.Root} The AST of the selector after processing it.
  43247. */
  43248. ;
  43249. _proto.astSync = function astSync(rule, options) {
  43250. return this._runSync(rule, options).root;
  43251. }
  43252. /**
  43253. * Process a selector into a transformed value asynchronously
  43254. *
  43255. * @param rule {postcss.Rule | string} The css selector to be processed
  43256. * @param options The options for processing
  43257. * @returns {Promise<any>} The value returned by the processor.
  43258. */
  43259. ;
  43260. _proto.transform = function transform(rule, options) {
  43261. return this._run(rule, options).then(function (result) {
  43262. return result.transform;
  43263. });
  43264. }
  43265. /**
  43266. * Process a selector into a transformed value synchronously.
  43267. *
  43268. * @param rule {postcss.Rule | string} The css selector to be processed
  43269. * @param options The options for processing
  43270. * @returns {any} The value returned by the processor.
  43271. */
  43272. ;
  43273. _proto.transformSync = function transformSync(rule, options) {
  43274. return this._runSync(rule, options).transform;
  43275. }
  43276. /**
  43277. * Process a selector into a new selector string asynchronously.
  43278. *
  43279. * @param rule {postcss.Rule | string} The css selector to be processed
  43280. * @param options The options for processing
  43281. * @returns {string} the selector after processing.
  43282. */
  43283. ;
  43284. _proto.process = function process(rule, options) {
  43285. return this._run(rule, options).then(function (result) {
  43286. return result.string || result.root.toString();
  43287. });
  43288. }
  43289. /**
  43290. * Process a selector into a new selector string synchronously.
  43291. *
  43292. * @param rule {postcss.Rule | string} The css selector to be processed
  43293. * @param options The options for processing
  43294. * @returns {string} the selector after processing.
  43295. */
  43296. ;
  43297. _proto.processSync = function processSync(rule, options) {
  43298. var result = this._runSync(rule, options);
  43299. return result.string || result.root.toString();
  43300. };
  43301. return Processor;
  43302. }();
  43303. exports["default"] = Processor;
  43304. module.exports = exports.default;
  43305. } (processor, processor.exports));
  43306. var selectors = {};
  43307. var constructors = {};
  43308. constructors.__esModule = true;
  43309. constructors.universal = constructors.tag = constructors.string = constructors.selector = constructors.root = constructors.pseudo = constructors.nesting = constructors.id = constructors.comment = constructors.combinator = constructors.className = constructors.attribute = void 0;
  43310. var _attribute = _interopRequireDefault(attribute$1);
  43311. var _className = _interopRequireDefault(className$1.exports);
  43312. var _combinator = _interopRequireDefault(combinator$2.exports);
  43313. var _comment = _interopRequireDefault(comment$2.exports);
  43314. var _id = _interopRequireDefault(id$1.exports);
  43315. var _nesting = _interopRequireDefault(nesting$1.exports);
  43316. var _pseudo = _interopRequireDefault(pseudo$1.exports);
  43317. var _root = _interopRequireDefault(root$1.exports);
  43318. var _selector = _interopRequireDefault(selector$1.exports);
  43319. var _string = _interopRequireDefault(string$1.exports);
  43320. var _tag = _interopRequireDefault(tag$1.exports);
  43321. var _universal = _interopRequireDefault(universal$1.exports);
  43322. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  43323. var attribute = function attribute(opts) {
  43324. return new _attribute["default"](opts);
  43325. };
  43326. constructors.attribute = attribute;
  43327. var className = function className(opts) {
  43328. return new _className["default"](opts);
  43329. };
  43330. constructors.className = className;
  43331. var combinator = function combinator(opts) {
  43332. return new _combinator["default"](opts);
  43333. };
  43334. constructors.combinator = combinator;
  43335. var comment = function comment(opts) {
  43336. return new _comment["default"](opts);
  43337. };
  43338. constructors.comment = comment;
  43339. var id = function id(opts) {
  43340. return new _id["default"](opts);
  43341. };
  43342. constructors.id = id;
  43343. var nesting = function nesting(opts) {
  43344. return new _nesting["default"](opts);
  43345. };
  43346. constructors.nesting = nesting;
  43347. var pseudo = function pseudo(opts) {
  43348. return new _pseudo["default"](opts);
  43349. };
  43350. constructors.pseudo = pseudo;
  43351. var root = function root(opts) {
  43352. return new _root["default"](opts);
  43353. };
  43354. constructors.root = root;
  43355. var selector = function selector(opts) {
  43356. return new _selector["default"](opts);
  43357. };
  43358. constructors.selector = selector;
  43359. var string = function string(opts) {
  43360. return new _string["default"](opts);
  43361. };
  43362. constructors.string = string;
  43363. var tag = function tag(opts) {
  43364. return new _tag["default"](opts);
  43365. };
  43366. constructors.tag = tag;
  43367. var universal = function universal(opts) {
  43368. return new _universal["default"](opts);
  43369. };
  43370. constructors.universal = universal;
  43371. var guards = {};
  43372. guards.__esModule = true;
  43373. guards.isNode = isNode;
  43374. guards.isPseudoElement = isPseudoElement;
  43375. guards.isPseudoClass = isPseudoClass;
  43376. guards.isContainer = isContainer;
  43377. guards.isNamespace = isNamespace;
  43378. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = guards.isPseudo = guards.isNesting = guards.isIdentifier = guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  43379. var _types = types;
  43380. var _IS_TYPE;
  43381. var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types.ATTRIBUTE] = true, _IS_TYPE[_types.CLASS] = true, _IS_TYPE[_types.COMBINATOR] = true, _IS_TYPE[_types.COMMENT] = true, _IS_TYPE[_types.ID] = true, _IS_TYPE[_types.NESTING] = true, _IS_TYPE[_types.PSEUDO] = true, _IS_TYPE[_types.ROOT] = true, _IS_TYPE[_types.SELECTOR] = true, _IS_TYPE[_types.STRING] = true, _IS_TYPE[_types.TAG] = true, _IS_TYPE[_types.UNIVERSAL] = true, _IS_TYPE);
  43382. function isNode(node) {
  43383. return typeof node === "object" && IS_TYPE[node.type];
  43384. }
  43385. function isNodeType(type, node) {
  43386. return isNode(node) && node.type === type;
  43387. }
  43388. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  43389. guards.isAttribute = isAttribute;
  43390. var isClassName = isNodeType.bind(null, _types.CLASS);
  43391. guards.isClassName = isClassName;
  43392. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  43393. guards.isCombinator = isCombinator;
  43394. var isComment = isNodeType.bind(null, _types.COMMENT);
  43395. guards.isComment = isComment;
  43396. var isIdentifier = isNodeType.bind(null, _types.ID);
  43397. guards.isIdentifier = isIdentifier;
  43398. var isNesting = isNodeType.bind(null, _types.NESTING);
  43399. guards.isNesting = isNesting;
  43400. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  43401. guards.isPseudo = isPseudo;
  43402. var isRoot = isNodeType.bind(null, _types.ROOT);
  43403. guards.isRoot = isRoot;
  43404. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  43405. guards.isSelector = isSelector;
  43406. var isString = isNodeType.bind(null, _types.STRING);
  43407. guards.isString = isString;
  43408. var isTag = isNodeType.bind(null, _types.TAG);
  43409. guards.isTag = isTag;
  43410. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  43411. guards.isUniversal = isUniversal;
  43412. function isPseudoElement(node) {
  43413. return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after");
  43414. }
  43415. function isPseudoClass(node) {
  43416. return isPseudo(node) && !isPseudoElement(node);
  43417. }
  43418. function isContainer(node) {
  43419. return !!(isNode(node) && node.walk);
  43420. }
  43421. function isNamespace(node) {
  43422. return isAttribute(node) || isTag(node);
  43423. }
  43424. (function (exports) {
  43425. exports.__esModule = true;
  43426. var _types = types;
  43427. Object.keys(_types).forEach(function (key) {
  43428. if (key === "default" || key === "__esModule") return;
  43429. if (key in exports && exports[key] === _types[key]) return;
  43430. exports[key] = _types[key];
  43431. });
  43432. var _constructors = constructors;
  43433. Object.keys(_constructors).forEach(function (key) {
  43434. if (key === "default" || key === "__esModule") return;
  43435. if (key in exports && exports[key] === _constructors[key]) return;
  43436. exports[key] = _constructors[key];
  43437. });
  43438. var _guards = guards;
  43439. Object.keys(_guards).forEach(function (key) {
  43440. if (key === "default" || key === "__esModule") return;
  43441. if (key in exports && exports[key] === _guards[key]) return;
  43442. exports[key] = _guards[key];
  43443. });
  43444. } (selectors));
  43445. (function (module, exports) {
  43446. exports.__esModule = true;
  43447. exports["default"] = void 0;
  43448. var _processor = _interopRequireDefault(processor.exports);
  43449. var selectors$1 = _interopRequireWildcard(selectors);
  43450. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  43451. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  43452. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  43453. var parser = function parser(processor) {
  43454. return new _processor["default"](processor);
  43455. };
  43456. Object.assign(parser, selectors$1);
  43457. delete parser.__esModule;
  43458. var _default = parser;
  43459. exports["default"] = _default;
  43460. module.exports = exports.default;
  43461. } (dist, dist.exports));
  43462. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(dist.exports);
  43463. const animationNameRE = /^(-\w+-)?animation-name$/;
  43464. const animationRE = /^(-\w+-)?animation$/;
  43465. const scopedPlugin = (id = '') => {
  43466. const keyframes = Object.create(null);
  43467. const shortId = id.replace(/^data-v-/, '');
  43468. return {
  43469. postcssPlugin: 'vue-sfc-scoped',
  43470. Rule(rule) {
  43471. processRule(id, rule);
  43472. },
  43473. AtRule(node) {
  43474. if (/-?keyframes$/.test(node.name) &&
  43475. !node.params.endsWith(`-${shortId}`)) {
  43476. // register keyframes
  43477. keyframes[node.params] = node.params = node.params + '-' + shortId;
  43478. }
  43479. },
  43480. OnceExit(root) {
  43481. if (Object.keys(keyframes).length) {
  43482. // If keyframes are found in this <style>, find and rewrite animation names
  43483. // in declarations.
  43484. // Caveat: this only works for keyframes and animation rules in the same
  43485. // <style> element.
  43486. // individual animation-name declaration
  43487. root.walkDecls(decl => {
  43488. if (animationNameRE.test(decl.prop)) {
  43489. decl.value = decl.value
  43490. .split(',')
  43491. .map(v => keyframes[v.trim()] || v.trim())
  43492. .join(',');
  43493. }
  43494. // shorthand
  43495. if (animationRE.test(decl.prop)) {
  43496. decl.value = decl.value
  43497. .split(',')
  43498. .map(v => {
  43499. const vals = v.trim().split(/\s+/);
  43500. const i = vals.findIndex(val => keyframes[val]);
  43501. if (i !== -1) {
  43502. vals.splice(i, 1, keyframes[vals[i]]);
  43503. return vals.join(' ');
  43504. }
  43505. else {
  43506. return v;
  43507. }
  43508. })
  43509. .join(',');
  43510. }
  43511. });
  43512. }
  43513. }
  43514. };
  43515. };
  43516. const processedRules = new WeakSet();
  43517. function processRule(id, rule) {
  43518. if (processedRules.has(rule) ||
  43519. (rule.parent &&
  43520. rule.parent.type === 'atrule' &&
  43521. /-?keyframes$/.test(rule.parent.name))) {
  43522. return;
  43523. }
  43524. processedRules.add(rule);
  43525. rule.selector = selectorParser(selectorRoot => {
  43526. selectorRoot.each(selector => {
  43527. rewriteSelector(id, selector, selectorRoot);
  43528. });
  43529. }).processSync(rule.selector);
  43530. }
  43531. function rewriteSelector(id, selector, selectorRoot, slotted = false) {
  43532. let node = null;
  43533. let shouldInject = true;
  43534. // find the last child node to insert attribute selector
  43535. selector.each(n => {
  43536. // DEPRECATED ">>>" and "/deep/" combinator
  43537. if (n.type === 'combinator' &&
  43538. (n.value === '>>>' || n.value === '/deep/')) {
  43539. n.value = ' ';
  43540. n.spaces.before = n.spaces.after = '';
  43541. warn$1(`the >>> and /deep/ combinators have been deprecated. ` +
  43542. `Use :deep() instead.`);
  43543. return false;
  43544. }
  43545. if (n.type === 'pseudo') {
  43546. const { value } = n;
  43547. // deep: inject [id] attribute at the node before the ::v-deep
  43548. // combinator.
  43549. if (value === ':deep' || value === '::v-deep') {
  43550. if (n.nodes.length) {
  43551. // .foo ::v-deep(.bar) -> .foo[xxxxxxx] .bar
  43552. // replace the current node with ::v-deep's inner selector
  43553. let last = n;
  43554. n.nodes[0].each(ss => {
  43555. selector.insertAfter(last, ss);
  43556. last = ss;
  43557. });
  43558. // insert a space combinator before if it doesn't already have one
  43559. const prev = selector.at(selector.index(n) - 1);
  43560. if (!prev || !isSpaceCombinator(prev)) {
  43561. selector.insertAfter(n, selectorParser.combinator({
  43562. value: ' '
  43563. }));
  43564. }
  43565. selector.removeChild(n);
  43566. }
  43567. else {
  43568. // DEPRECATED usage
  43569. // .foo ::v-deep .bar -> .foo[xxxxxxx] .bar
  43570. warn$1(`::v-deep usage as a combinator has ` +
  43571. `been deprecated. Use :deep(<inner-selector>) instead.`);
  43572. const prev = selector.at(selector.index(n) - 1);
  43573. if (prev && isSpaceCombinator(prev)) {
  43574. selector.removeChild(prev);
  43575. }
  43576. selector.removeChild(n);
  43577. }
  43578. return false;
  43579. }
  43580. // slot: use selector inside `::v-slotted` and inject [id + '-s']
  43581. // instead.
  43582. // ::v-slotted(.foo) -> .foo[xxxxxxx-s]
  43583. if (value === ':slotted' || value === '::v-slotted') {
  43584. rewriteSelector(id, n.nodes[0], selectorRoot, true /* slotted */);
  43585. let last = n;
  43586. n.nodes[0].each(ss => {
  43587. selector.insertAfter(last, ss);
  43588. last = ss;
  43589. });
  43590. // selector.insertAfter(n, n.nodes[0])
  43591. selector.removeChild(n);
  43592. // since slotted attribute already scopes the selector there's no
  43593. // need for the non-slot attribute.
  43594. shouldInject = false;
  43595. return false;
  43596. }
  43597. // global: replace with inner selector and do not inject [id].
  43598. // ::v-global(.foo) -> .foo
  43599. if (value === ':global' || value === '::v-global') {
  43600. selectorRoot.insertAfter(selector, n.nodes[0]);
  43601. selectorRoot.removeChild(selector);
  43602. return false;
  43603. }
  43604. }
  43605. if (n.type !== 'pseudo' && n.type !== 'combinator') {
  43606. node = n;
  43607. }
  43608. });
  43609. if (node) {
  43610. node.spaces.after = '';
  43611. }
  43612. else {
  43613. // For deep selectors & standalone pseudo selectors,
  43614. // the attribute selectors are prepended rather than appended.
  43615. // So all leading spaces must be eliminated to avoid problems.
  43616. selector.first.spaces.before = '';
  43617. }
  43618. if (shouldInject) {
  43619. const idToAdd = slotted ? id + '-s' : id;
  43620. selector.insertAfter(
  43621. // If node is null it means we need to inject [id] at the start
  43622. // insertAfter can handle `null` here
  43623. node, selectorParser.attribute({
  43624. attribute: idToAdd,
  43625. value: idToAdd,
  43626. raws: {},
  43627. quoteMark: `"`
  43628. }));
  43629. }
  43630. }
  43631. function isSpaceCombinator(node) {
  43632. return node.type === 'combinator' && /^\s+$/.test(node.value);
  43633. }
  43634. scopedPlugin.postcss = true;
  43635. var scopedPlugin$1 = scopedPlugin;
  43636. var sourceMap = sourceMap$2;
  43637. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  43638. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  43639. var mergeSourceMap = merge;
  43640. /**
  43641. * Merge old source map and new source map and return merged.
  43642. * If old or new source map value is falsy, return another one as it is.
  43643. *
  43644. * @param {object|string} [oldMap] old source map object
  43645. * @param {object|string} [newmap] new source map object
  43646. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  43647. */
  43648. function merge(oldMap, newMap) {
  43649. if (!oldMap) return newMap
  43650. if (!newMap) return oldMap
  43651. var oldMapConsumer = new SourceMapConsumer(oldMap);
  43652. var newMapConsumer = new SourceMapConsumer(newMap);
  43653. var mergedMapGenerator = new SourceMapGenerator();
  43654. // iterate on new map and overwrite original position of new map with one of old map
  43655. newMapConsumer.eachMapping(function(m) {
  43656. // pass when `originalLine` is null.
  43657. // It occurs in case that the node does not have origin in original code.
  43658. if (m.originalLine == null) return
  43659. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  43660. line: m.originalLine,
  43661. column: m.originalColumn
  43662. });
  43663. if (origPosInOldMap.source == null) return
  43664. mergedMapGenerator.addMapping({
  43665. original: {
  43666. line: origPosInOldMap.line,
  43667. column: origPosInOldMap.column
  43668. },
  43669. generated: {
  43670. line: m.generatedLine,
  43671. column: m.generatedColumn
  43672. },
  43673. source: origPosInOldMap.source,
  43674. name: origPosInOldMap.name
  43675. });
  43676. });
  43677. var consumers = [oldMapConsumer, newMapConsumer];
  43678. consumers.forEach(function(consumer) {
  43679. consumer.sources.forEach(function(sourceFile) {
  43680. mergedMapGenerator._sources.add(sourceFile);
  43681. var sourceContent = consumer.sourceContentFor(sourceFile);
  43682. if (sourceContent != null) {
  43683. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  43684. }
  43685. });
  43686. });
  43687. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  43688. mergedMapGenerator._file = oldMap.file;
  43689. return JSON.parse(mergedMapGenerator.toString())
  43690. }
  43691. var merge$1 = mergeSourceMap;
  43692. // .scss/.sass processor
  43693. const scss = (source, map, options, load = require) => {
  43694. const nodeSass = load('sass');
  43695. const finalOptions = Object.assign(Object.assign({}, options), { data: getSource(source, options.filename, options.additionalData), file: options.filename, outFile: options.filename, sourceMap: !!map });
  43696. try {
  43697. const result = nodeSass.renderSync(finalOptions);
  43698. const dependencies = result.stats.includedFiles;
  43699. if (map) {
  43700. return {
  43701. code: result.css.toString(),
  43702. map: merge$1(map, JSON.parse(result.map.toString())),
  43703. errors: [],
  43704. dependencies
  43705. };
  43706. }
  43707. return { code: result.css.toString(), errors: [], dependencies };
  43708. }
  43709. catch (e) {
  43710. return { code: '', errors: [e], dependencies: [] };
  43711. }
  43712. };
  43713. const sass = (source, map, options, load) => scss(source, map, Object.assign(Object.assign({}, options), { indentedSyntax: true }), load);
  43714. // .less
  43715. const less = (source, map, options, load = require) => {
  43716. const nodeLess = load('less');
  43717. let result;
  43718. let error = null;
  43719. nodeLess.render(getSource(source, options.filename, options.additionalData), Object.assign(Object.assign({}, options), { syncImport: true }), (err, output) => {
  43720. error = err;
  43721. result = output;
  43722. });
  43723. if (error)
  43724. return { code: '', errors: [error], dependencies: [] };
  43725. const dependencies = result.imports;
  43726. if (map) {
  43727. return {
  43728. code: result.css.toString(),
  43729. map: merge$1(map, result.map),
  43730. errors: [],
  43731. dependencies: dependencies
  43732. };
  43733. }
  43734. return {
  43735. code: result.css.toString(),
  43736. errors: [],
  43737. dependencies: dependencies
  43738. };
  43739. };
  43740. // .styl
  43741. const styl = (source, map, options, load = require) => {
  43742. const nodeStylus = load('stylus');
  43743. try {
  43744. const ref = nodeStylus(source);
  43745. Object.keys(options).forEach(key => ref.set(key, options[key]));
  43746. if (map)
  43747. ref.set('sourcemap', { inline: false, comment: false });
  43748. const result = ref.render();
  43749. const dependencies = ref.deps();
  43750. if (map) {
  43751. return {
  43752. code: result,
  43753. map: merge$1(map, ref.sourcemap),
  43754. errors: [],
  43755. dependencies
  43756. };
  43757. }
  43758. return { code: result, errors: [], dependencies };
  43759. }
  43760. catch (e) {
  43761. return { code: '', errors: [e], dependencies: [] };
  43762. }
  43763. };
  43764. function getSource(source, filename, additionalData) {
  43765. if (!additionalData)
  43766. return source;
  43767. if (isFunction$1(additionalData)) {
  43768. return additionalData(source, filename);
  43769. }
  43770. return additionalData + source;
  43771. }
  43772. const processors = {
  43773. less,
  43774. sass,
  43775. scss,
  43776. styl,
  43777. stylus: styl
  43778. };
  43779. function compileStyle(options) {
  43780. return doCompileStyle(Object.assign(Object.assign({}, options), { isAsync: false }));
  43781. }
  43782. function compileStyleAsync(options) {
  43783. return doCompileStyle(Object.assign(Object.assign({}, options), { isAsync: true }));
  43784. }
  43785. function doCompileStyle(options) {
  43786. const { filename, id, scoped = false, trim = true, isProd = false, modules = false, modulesOptions = {}, preprocessLang, postcssOptions, postcssPlugins } = options;
  43787. const preprocessor = preprocessLang && processors[preprocessLang];
  43788. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  43789. const map = preProcessedSource
  43790. ? preProcessedSource.map
  43791. : options.inMap || options.map;
  43792. const source = preProcessedSource ? preProcessedSource.code : options.source;
  43793. const shortId = id.replace(/^data-v-/, '');
  43794. const longId = `data-v-${shortId}`;
  43795. const plugins = (postcssPlugins || []).slice();
  43796. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  43797. if (trim) {
  43798. plugins.push(trimPlugin$1());
  43799. }
  43800. if (scoped) {
  43801. plugins.push(scopedPlugin$1(longId));
  43802. }
  43803. let cssModules;
  43804. if (modules) {
  43805. {
  43806. throw new Error('[@vue/compiler-sfc] `modules` option is not supported in the browser build.');
  43807. }
  43808. }
  43809. const postCSSOptions = Object.assign(Object.assign({}, postcssOptions), { to: filename, from: filename });
  43810. if (map) {
  43811. postCSSOptions.map = {
  43812. inline: false,
  43813. annotation: false,
  43814. prev: map
  43815. };
  43816. }
  43817. let result;
  43818. let code;
  43819. let outMap;
  43820. // stylus output include plain css. so need remove the repeat item
  43821. const dependencies = new Set(preProcessedSource ? preProcessedSource.dependencies : []);
  43822. // sass has filename self when provided filename option
  43823. dependencies.delete(filename);
  43824. const errors = [];
  43825. if (preProcessedSource && preProcessedSource.errors.length) {
  43826. errors.push(...preProcessedSource.errors);
  43827. }
  43828. const recordPlainCssDependencies = (messages) => {
  43829. messages.forEach(msg => {
  43830. if (msg.type === 'dependency') {
  43831. // postcss output path is absolute position path
  43832. dependencies.add(msg.file);
  43833. }
  43834. });
  43835. return dependencies;
  43836. };
  43837. try {
  43838. result = postcss$1(plugins).process(source, postCSSOptions);
  43839. // In async mode, return a promise.
  43840. if (options.isAsync) {
  43841. return result
  43842. .then(result => ({
  43843. code: result.css || '',
  43844. map: result.map && result.map.toJSON(),
  43845. errors,
  43846. modules: cssModules,
  43847. rawResult: result,
  43848. dependencies: recordPlainCssDependencies(result.messages)
  43849. }))
  43850. .catch(error => ({
  43851. code: '',
  43852. map: undefined,
  43853. errors: [...errors, error],
  43854. rawResult: undefined,
  43855. dependencies
  43856. }));
  43857. }
  43858. recordPlainCssDependencies(result.messages);
  43859. // force synchronous transform (we know we only have sync plugins)
  43860. code = result.css;
  43861. outMap = result.map;
  43862. }
  43863. catch (e) {
  43864. errors.push(e);
  43865. }
  43866. return {
  43867. code: code || ``,
  43868. map: outMap && outMap.toJSON(),
  43869. errors,
  43870. rawResult: result,
  43871. dependencies
  43872. };
  43873. }
  43874. function preprocess(options, preprocessor) {
  43875. if (!options.preprocessCustomRequire) {
  43876. throw new Error(`[@vue/compiler-sfc] Style preprocessing in the browser build must ` +
  43877. `provide the \`preprocessCustomRequire\` option to return the in-browser ` +
  43878. `version of the preprocessor.`);
  43879. }
  43880. return preprocessor(options.source, options.inMap || options.map, Object.assign({ filename: options.filename }, options.preprocessOptions), options.preprocessCustomRequire);
  43881. }
  43882. // API
  43883. const walk = walk$1;
  43884. export { MagicString$1 as MagicString, parse_1$1 as babelParse, compileScript, compileStyle, compileStyleAsync, compileTemplate, extractIdentifiers, generateCodeFrame, isInDestructureAssignment, isStaticProperty, parse$5 as parse, rewriteDefault, shouldTransform as shouldTransformRef, transform as transformRef, transformAST as transformRefAST, walk, walkIdentifiers };